Search is not available for this dataset
text
string
meta
dict
/* * Copyright (c) 2011-2018 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2013 Inria. All rights reserved. * * @precisions normal z -> c d s * */ #include <cblas.h> #include "dplasma.h" #include "dplasmatypes.h" static int dplasma_zlascal_operator( parsec_execution_stream_t *es, const parsec_tiled_matrix_dc_t *descA, void *_A, PLASMA_enum uplo, int m, int n, void *args ) { parsec_complex64_t *A = (parsec_complex64_t*)_A; parsec_complex64_t alpha = *((parsec_complex64_t*)args); int i; int tempmm, tempnn, ldam; (void)es; tempmm = ((m)==((descA->mt)-1)) ? ((descA->m)-(m*(descA->mb))) : (descA->mb); tempnn = ((n)==((descA->nt)-1)) ? ((descA->n)-(n*(descA->nb))) : (descA->nb); ldam = BLKLDD( descA, m ); /* Overwrite uplo when outside the diagonal */ if (m != n) { uplo = PlasmaUpperLower; } switch ( uplo ) { case PlasmaUpper: for(i=0; i<tempnn; i++) { cblas_zscal( dplasma_imin( i+1, tempmm ), CBLAS_SADDR(alpha), A+i*ldam, 1 ); } break; case PlasmaLower: for(i=0; i<tempnn; i++) { cblas_zscal( dplasma_imax( tempmm, tempmm-i ), CBLAS_SADDR(alpha), A+i*ldam, 1 ); } break; default: for(i=0; i<tempnn; i++) { cblas_zscal( tempmm, CBLAS_SADDR(alpha), A+i*ldam, 1 ); } break; } return 0; } /** ******************************************************************************* * * @ingroup dplasma_complex64 * * dplasma_zlascal_New - Generates the taskpool that scales a matrix by a given scalar. * * See parsec_apply_New() for further information. * * WARNINGS: * - The computations are not done by this call. * - This routine is equivalent to the pzlascal routine from ScaLapack and * not to the zlascl/pzlascl routines from Lapack/ScaLapack. * ******************************************************************************* * * @param[in] uplo * Specifies which part of matrix A is set: * = PlasmaUpperLower: All matrix is referenced. * = PlasmaUpper: Only upper part is referenced. * = PlasmaLower: Only lower part is referenced. * = PlasmaUpperHessenberg: A is an upper Hessenberg matrix (Not * supported) * * @param[in] alpha * The scalar to use to scale the matrix. * * @param[in,out] A * Descriptor of the distributed matrix A. Any tiled matrix * descriptor can be used. * On exit, the matrix A is scaled by alpha. * ******************************************************************************* * * @return * \retval NULL if incorrect parameters are given. * \retval The parsec taskpool describing the operation that can be * enqueued in the runtime with parsec_context_add_taskpool(). It, then, needs to be * destroy with dplasma_zlascal_Destruct(); * ******************************************************************************* * * @sa dplasma_zlascal * @sa dplasma_zlascal_Destruct * @sa dplasma_clascal_New * @sa dplasma_dlascal_New * @sa dplasma_slascal_New * ******************************************************************************/ parsec_taskpool_t* dplasma_zlascal_New( PLASMA_enum uplo, parsec_complex64_t alpha, parsec_tiled_matrix_dc_t *A ) { parsec_complex64_t *a = (parsec_complex64_t*)malloc(sizeof(parsec_complex64_t)); *a = alpha; return parsec_apply_New( uplo, A, dplasma_zlascal_operator, (void*)a ); } /** ******************************************************************************* * * @ingroup dplasma_complex64 * * dplasma_zlascal_Destruct - Free the data structure associated to an taskpool * created with dplasma_zlascal_New(). * ******************************************************************************* * * @param[in,out] taskpool * On entry, the taskpool to destroy. * On exit, the taskpool cannot be used anymore. * ******************************************************************************* * * @sa dplasma_zlascal_New * @sa dplasma_zlascal * ******************************************************************************/ void dplasma_zlascal_Destruct( parsec_taskpool_t *tp ) { parsec_apply_Destruct(tp); } /** ******************************************************************************* * * @ingroup dplasma_complex64 * * dplasma_zlascal - Scales a matrix by a given scalar. * * * WARNINGS: * - This routine is equivalent to the pzlascal routine from ScaLapack and * not to the zlascl/pzlascl routines from Lapack/ScaLapack. * ******************************************************************************* * * @param[in,out] parsec * The parsec context of the application that will run the operation. * * @param[in] uplo * Specifies which part of matrix A is set: * = PlasmaUpperLower: All matrix is referenced. * = PlasmaUpper: Only upper part is referenced. * = PlasmaLower: Only lower part is referenced. * = PlasmaUpperHessenberg: A is an upper Hessenberg matrix (Not * supported) * * @param[in] alpha * The scalar to use to scale the matrix. * * @param[in,out] A * Descriptor of the distributed matrix A. Any tiled matrix * descriptor can be used. * On exit, the matrix A is scaled by alpha. * ******************************************************************************* * * @return * \retval -i if the ith parameters is incorrect. * \retval 0 on success. * ******************************************************************************* * * @sa dplasma_zlascal_New * @sa dplasma_zlascal_Destruct * @sa dplasma_clascal * @sa dplasma_dlascal * @sa dplasma_slascal * ******************************************************************************/ int dplasma_zlascal( parsec_context_t *parsec, PLASMA_enum uplo, parsec_complex64_t alpha, parsec_tiled_matrix_dc_t *A ) { parsec_taskpool_t *parsec_zlascal = NULL; /* Check input arguments */ if ((uplo != PlasmaLower) && (uplo != PlasmaUpper) && (uplo != PlasmaUpperLower)) { dplasma_error("dplasma_zlascal", "illegal value of type"); return -2; } parsec_zlascal = dplasma_zlascal_New(uplo, alpha, A); if ( parsec_zlascal != NULL ) { parsec_context_add_taskpool(parsec, (parsec_taskpool_t*)parsec_zlascal); dplasma_wait_until_completion(parsec); dplasma_zlascal_Destruct( parsec_zlascal ); } return 0; }
{ "alphanum_fraction": 0.5121393887, "avg_line_length": 31.8272727273, "ext": "c", "hexsha": "bcb7596867b3ce8d75844e5735a379fc59821b75", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_path": "dplasma/lib/zlascal_wrapper.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_path": "dplasma/lib/zlascal_wrapper.c", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_path": "dplasma/lib/zlascal_wrapper.c", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "num_tokens": 1670, "size": 7002 }
/* GStreamer * Copyright (C) <2005> Thomas Vander Stichele <thomas at apestaart dot org> * Copyright (C) <2006> Tim-Philipp Müller <tim centricular net> * * gstutils.c: Unit test for functions in gstutils * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/check/gstcheck.h> #define SPECIAL_POINTER(x) ((void*)(19283847+(x))) static int n_data_probes = 0; static int n_buffer_probes = 0; static int n_event_probes = 0; static GstPadProbeReturn probe_do_nothing (GstPad * pad, GstPadProbeInfo * info, gpointer data) { GstMiniObject *obj = GST_PAD_PROBE_INFO_DATA (info); GST_DEBUG_OBJECT (pad, "is buffer:%d", GST_IS_BUFFER (obj)); return GST_PAD_PROBE_OK; } static GstPadProbeReturn data_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data) { GstMiniObject *obj = GST_PAD_PROBE_INFO_DATA (info); n_data_probes++; GST_DEBUG_OBJECT (pad, "data probe %d", n_data_probes); g_assert (GST_IS_BUFFER (obj) || GST_IS_EVENT (obj)); g_assert (data == SPECIAL_POINTER (0)); return GST_PAD_PROBE_OK; } static GstPadProbeReturn buffer_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data) { GstBuffer *obj = GST_PAD_PROBE_INFO_BUFFER (info); n_buffer_probes++; GST_DEBUG_OBJECT (pad, "buffer probe %d", n_buffer_probes); g_assert (GST_IS_BUFFER (obj)); g_assert (data == SPECIAL_POINTER (1)); return GST_PAD_PROBE_OK; } static GstPadProbeReturn event_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data) { GstEvent *obj = GST_PAD_PROBE_INFO_EVENT (info); n_event_probes++; GST_DEBUG_OBJECT (pad, "event probe %d [%s]", n_event_probes, GST_EVENT_TYPE_NAME (obj)); g_assert (GST_IS_EVENT (obj)); g_assert (data == SPECIAL_POINTER (2)); return GST_PAD_PROBE_OK; } GST_START_TEST (test_buffer_probe_n_times) { GstElement *pipeline, *fakesrc, *fakesink; GstBus *bus; GstMessage *message; GstPad *pad; pipeline = gst_element_factory_make ("pipeline", NULL); fakesrc = gst_element_factory_make ("fakesrc", NULL); fakesink = gst_element_factory_make ("fakesink", NULL); g_object_set (fakesrc, "num-buffers", (int) 10, NULL); gst_bin_add_many (GST_BIN (pipeline), fakesrc, fakesink, NULL); gst_element_link (fakesrc, fakesink); pad = gst_element_get_static_pad (fakesink, "sink"); /* add the probes we need for the test */ gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_DATA_BOTH, data_probe, SPECIAL_POINTER (0), NULL); gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER, buffer_probe, SPECIAL_POINTER (1), NULL); gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_BOTH, event_probe, SPECIAL_POINTER (2), NULL); /* add some string probes just to test that the data is free'd * properly as it should be */ gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_DATA_BOTH, probe_do_nothing, g_strdup ("data probe string"), (GDestroyNotify) g_free); gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER, probe_do_nothing, g_strdup ("buffer probe string"), (GDestroyNotify) g_free); gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_BOTH, probe_do_nothing, g_strdup ("event probe string"), (GDestroyNotify) g_free); gst_object_unref (pad); gst_element_set_state (pipeline, GST_STATE_PLAYING); bus = gst_element_get_bus (pipeline); message = gst_bus_poll (bus, GST_MESSAGE_EOS, -1); gst_message_unref (message); gst_object_unref (bus); g_assert (n_buffer_probes == 10); /* one for every buffer */ g_assert (n_event_probes == 4); /* stream-start, new segment, latency and eos */ g_assert (n_data_probes == 14); /* duh */ gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (pipeline); /* make sure nothing was sent in addition to the above when shutting down */ g_assert (n_buffer_probes == 10); /* one for every buffer */ g_assert (n_event_probes == 4); /* stream-start, new segment, latency and eos */ g_assert (n_data_probes == 14); /* duh */ } GST_END_TEST; static int n_data_probes_once = 0; static int n_buffer_probes_once = 0; static int n_event_probes_once = 0; static GstPadProbeReturn data_probe_once (GstPad * pad, GstPadProbeInfo * info, guint * data) { GstMiniObject *obj = GST_PAD_PROBE_INFO_DATA (info); n_data_probes_once++; g_assert (GST_IS_BUFFER (obj) || GST_IS_EVENT (obj)); gst_pad_remove_probe (pad, *data); return GST_PAD_PROBE_OK; } static GstPadProbeReturn buffer_probe_once (GstPad * pad, GstPadProbeInfo * info, guint * data) { GstBuffer *obj = GST_PAD_PROBE_INFO_BUFFER (info); n_buffer_probes_once++; g_assert (GST_IS_BUFFER (obj)); gst_pad_remove_probe (pad, *data); return GST_PAD_PROBE_OK; } static GstPadProbeReturn event_probe_once (GstPad * pad, GstPadProbeInfo * info, guint * data) { GstEvent *obj = GST_PAD_PROBE_INFO_EVENT (info); n_event_probes_once++; g_assert (GST_IS_EVENT (obj)); gst_pad_remove_probe (pad, *data); return GST_PAD_PROBE_OK; } GST_START_TEST (test_buffer_probe_once) { GstElement *pipeline, *fakesrc, *fakesink; GstBus *bus; GstMessage *message; GstPad *pad; guint id1, id2, id3; pipeline = gst_element_factory_make ("pipeline", NULL); fakesrc = gst_element_factory_make ("fakesrc", NULL); fakesink = gst_element_factory_make ("fakesink", NULL); g_object_set (fakesrc, "num-buffers", (int) 10, NULL); gst_bin_add_many (GST_BIN (pipeline), fakesrc, fakesink, NULL); gst_element_link (fakesrc, fakesink); pad = gst_element_get_static_pad (fakesink, "sink"); id1 = gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_DATA_BOTH, (GstPadProbeCallback) data_probe_once, &id1, NULL); id2 = gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER, (GstPadProbeCallback) buffer_probe_once, &id2, NULL); id3 = gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_BOTH, (GstPadProbeCallback) event_probe_once, &id3, NULL); gst_object_unref (pad); gst_element_set_state (pipeline, GST_STATE_PLAYING); bus = gst_element_get_bus (pipeline); message = gst_bus_poll (bus, GST_MESSAGE_EOS, -1); gst_message_unref (message); gst_object_unref (bus); gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (pipeline); g_assert (n_buffer_probes_once == 1); /* can we hit it and quit? */ g_assert (n_event_probes_once == 1); /* i said, can we hit it and quit? */ g_assert (n_data_probes_once == 1); /* let's hit it and quit!!! */ } GST_END_TEST; GST_START_TEST (test_math_scale) { fail_if (gst_util_uint64_scale_int (1, 1, 1) != 1); fail_if (gst_util_uint64_scale_int (10, 10, 1) != 100); fail_if (gst_util_uint64_scale_int (10, 10, 2) != 50); fail_if (gst_util_uint64_scale_int (0, 10, 2) != 0); fail_if (gst_util_uint64_scale_int (0, 0, 2) != 0); fail_if (gst_util_uint64_scale_int (G_MAXUINT32, 5, 1) != G_MAXUINT32 * 5LL); fail_if (gst_util_uint64_scale_int (G_MAXUINT32, 10, 2) != G_MAXUINT32 * 5LL); fail_if (gst_util_uint64_scale_int (G_MAXUINT32, 1, 5) != G_MAXUINT32 / 5LL); fail_if (gst_util_uint64_scale_int (G_MAXUINT32, 2, 10) != G_MAXUINT32 / 5LL); /* not quite overflow */ fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 1, 10, 10) != G_MAXUINT64 - 1); fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 1, G_MAXINT32, G_MAXINT32) != G_MAXUINT64 - 1); fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 100, G_MAXINT32, G_MAXINT32) != G_MAXUINT64 - 100); /* overflow */ fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 1, 10, 1) != G_MAXUINT64); fail_if (gst_util_uint64_scale_int (G_MAXUINT64 - 1, G_MAXINT32, 1) != G_MAXUINT64); } GST_END_TEST; GST_START_TEST (test_math_scale_round) { fail_if (gst_util_uint64_scale_int_round (2, 1, 2) != 1); fail_if (gst_util_uint64_scale_int_round (3, 1, 2) != 2); fail_if (gst_util_uint64_scale_int_round (4, 1, 2) != 2); fail_if (gst_util_uint64_scale_int_round (200, 100, 20000) != 1); fail_if (gst_util_uint64_scale_int_round (299, 100, 20000) != 1); fail_if (gst_util_uint64_scale_int_round (300, 100, 20000) != 2); fail_if (gst_util_uint64_scale_int_round (301, 100, 20000) != 2); fail_if (gst_util_uint64_scale_int_round (400, 100, 20000) != 2); } GST_END_TEST; GST_START_TEST (test_math_scale_ceil) { fail_if (gst_util_uint64_scale_int_ceil (2, 1, 2) != 1); fail_if (gst_util_uint64_scale_int_ceil (3, 1, 2) != 2); fail_if (gst_util_uint64_scale_int_ceil (4, 1, 2) != 2); fail_if (gst_util_uint64_scale_int_ceil (200, 100, 20000) != 1); fail_if (gst_util_uint64_scale_int_ceil (299, 100, 20000) != 2); fail_if (gst_util_uint64_scale_int_ceil (300, 100, 20000) != 2); fail_if (gst_util_uint64_scale_int_ceil (301, 100, 20000) != 2); fail_if (gst_util_uint64_scale_int_ceil (400, 100, 20000) != 2); } GST_END_TEST; GST_START_TEST (test_math_scale_uint64) { fail_if (gst_util_uint64_scale (1, 1, 1) != 1); fail_if (gst_util_uint64_scale (10, 10, 1) != 100); fail_if (gst_util_uint64_scale (10, 10, 2) != 50); fail_if (gst_util_uint64_scale (0, 10, 2) != 0); fail_if (gst_util_uint64_scale (0, 0, 2) != 0); fail_if (gst_util_uint64_scale (G_MAXUINT32, 5, 1) != G_MAXUINT32 * 5LL); fail_if (gst_util_uint64_scale (G_MAXUINT32, 10, 2) != G_MAXUINT32 * 5LL); fail_if (gst_util_uint64_scale (G_MAXUINT32, 1, 5) != G_MAXUINT32 / 5LL); fail_if (gst_util_uint64_scale (G_MAXUINT32, 2, 10) != G_MAXUINT32 / 5LL); /* not quite overflow */ fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, 10, 10) != G_MAXUINT64 - 1); fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, G_MAXUINT32, G_MAXUINT32) != G_MAXUINT64 - 1); fail_if (gst_util_uint64_scale (G_MAXUINT64 - 100, G_MAXUINT32, G_MAXUINT32) != G_MAXUINT64 - 100); fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, 10, 10) != G_MAXUINT64 - 1); fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, G_MAXUINT64, G_MAXUINT64) != G_MAXUINT64 - 1); fail_if (gst_util_uint64_scale (G_MAXUINT64 - 100, G_MAXUINT64, G_MAXUINT64) != G_MAXUINT64 - 100); /* overflow */ fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, 10, 1) != G_MAXUINT64); fail_if (gst_util_uint64_scale (G_MAXUINT64 - 1, G_MAXUINT64, 1) != G_MAXUINT64); } GST_END_TEST; GST_START_TEST (test_math_scale_random) { guint64 val, num, denom, res; GRand *rand; gint i; rand = g_rand_new (); i = 100000; while (i--) { guint64 check, diff; val = ((guint64) g_rand_int (rand)) << 32 | g_rand_int (rand); num = ((guint64) g_rand_int (rand)) << 32 | g_rand_int (rand); denom = ((guint64) g_rand_int (rand)) << 32 | g_rand_int (rand); res = gst_util_uint64_scale (val, num, denom); check = gst_gdouble_to_guint64 (gst_guint64_to_gdouble (val) * gst_guint64_to_gdouble (num) / gst_guint64_to_gdouble (denom)); if (res < G_MAXUINT64 && check < G_MAXUINT64) { if (res > check) diff = res - check; else diff = check - res; /* some arbitrary value, really.. someone do the proper math to get * the upper bound */ if (diff > 20000) fail_if (diff > 20000); } } g_rand_free (rand); } GST_END_TEST; GST_START_TEST (test_guint64_to_gdouble) { guint64 from[] = { 0, 1, 100, 10000, (guint64) (1) << 63, ((guint64) (1) << 63) + 1, ((guint64) (1) << 63) + (G_GINT64_CONSTANT (1) << 62) }; gdouble to[] = { 0., 1., 100., 10000., 9223372036854775808., 9223372036854775809., 13835058055282163712. }; gdouble tolerance[] = { 0., 0., 0., 0., 0., 1., 1. }; gint i; gdouble result; gdouble delta; for (i = 0; i < G_N_ELEMENTS (from); ++i) { result = gst_util_guint64_to_gdouble (from[i]); delta = ABS (to[i] - result); fail_unless (delta <= tolerance[i], "Could not convert %d: %" G_GUINT64_FORMAT " -> %f, got %f instead, delta of %e with tolerance of %e", i, from[i], to[i], result, delta, tolerance[i]); } } GST_END_TEST; GST_START_TEST (test_gdouble_to_guint64) { gdouble from[] = { 0., 1., 100., 10000., 9223372036854775808., 9223372036854775809., 13835058055282163712. }; guint64 to[] = { 0, 1, 100, 10000, (guint64) (1) << 63, ((guint64) (1) << 63) + 1, ((guint64) (1) << 63) + (G_GINT64_CONSTANT (1) << 62) }; guint64 tolerance[] = { 0, 0, 0, 0, 0, 1, 1 }; gint i; gdouble result; guint64 delta; for (i = 0; i < G_N_ELEMENTS (from); ++i) { result = gst_util_gdouble_to_guint64 (from[i]); delta = ABS (to[i] - result); fail_unless (delta <= tolerance[i], "Could not convert %f: %" G_GUINT64_FORMAT " -> %d, got %d instead, delta of %e with tolerance of %e", i, from[i], to[i], result, delta, tolerance[i]); } } GST_END_TEST; #ifndef GST_DISABLE_PARSE GST_START_TEST (test_parse_bin_from_description) { struct { const gchar *bin_desc; const gchar *pad_names; } bin_tests[] = { { "identity", "identity0/sink,identity0/src"}, { "identity ! identity ! identity", "identity1/sink,identity3/src"}, { "identity ! fakesink", "identity4/sink"}, { "fakesrc ! identity", "identity5/src"}, { "fakesrc ! fakesink", ""} }; gint i; for (i = 0; i < G_N_ELEMENTS (bin_tests); ++i) { GstElement *bin, *parent; GString *s; GstPad *ghost_pad, *target_pad; GError *err = NULL; bin = gst_parse_bin_from_description (bin_tests[i].bin_desc, TRUE, &err); if (err) { g_error ("ERROR in gst_parse_bin_from_description (%s): %s", bin_tests[i].bin_desc, err->message); } g_assert (bin != NULL); s = g_string_new (""); if ((ghost_pad = gst_element_get_static_pad (bin, "sink"))) { g_assert (GST_IS_GHOST_PAD (ghost_pad)); target_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (ghost_pad)); g_assert (target_pad != NULL); g_assert (GST_IS_PAD (target_pad)); parent = gst_pad_get_parent_element (target_pad); g_assert (parent != NULL); g_string_append_printf (s, "%s/sink", GST_ELEMENT_NAME (parent)); gst_object_unref (parent); gst_object_unref (target_pad); gst_object_unref (ghost_pad); } if ((ghost_pad = gst_element_get_static_pad (bin, "src"))) { g_assert (GST_IS_GHOST_PAD (ghost_pad)); target_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (ghost_pad)); g_assert (target_pad != NULL); g_assert (GST_IS_PAD (target_pad)); parent = gst_pad_get_parent_element (target_pad); g_assert (parent != NULL); if (s->len > 0) { g_string_append (s, ","); } g_string_append_printf (s, "%s/src", GST_ELEMENT_NAME (parent)); gst_object_unref (parent); gst_object_unref (target_pad); gst_object_unref (ghost_pad); } if (strcmp (s->str, bin_tests[i].pad_names) != 0) { g_error ("FAILED: expected '%s', got '%s' for bin '%s'", bin_tests[i].pad_names, s->str, bin_tests[i].bin_desc); } g_string_free (s, TRUE); gst_object_unref (bin); } } GST_END_TEST; #endif GST_START_TEST (test_element_found_tags) { GstElement *pipeline, *fakesrc, *fakesink; GstTagList *list; GstBus *bus; GstMessage *message; GstPad *srcpad; pipeline = gst_element_factory_make ("pipeline", NULL); fakesrc = gst_element_factory_make ("fakesrc", NULL); fakesink = gst_element_factory_make ("fakesink", NULL); list = gst_tag_list_new_empty (); g_object_set (fakesrc, "num-buffers", (int) 10, NULL); gst_bin_add_many (GST_BIN (pipeline), fakesrc, fakesink, NULL); gst_element_link (fakesrc, fakesink); gst_element_set_state (pipeline, GST_STATE_PLAYING); srcpad = gst_element_get_static_pad (fakesrc, "src"); gst_pad_push_event (srcpad, gst_event_new_tag (list)); gst_object_unref (srcpad); bus = gst_element_get_bus (pipeline); message = gst_bus_poll (bus, GST_MESSAGE_EOS, -1); gst_message_unref (message); gst_object_unref (bus); /* FIXME: maybe also check if the fakesink receives the message */ gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (pipeline); } GST_END_TEST; GST_START_TEST (test_element_unlink) { GstElement *src, *sink; src = gst_element_factory_make ("fakesrc", NULL); sink = gst_element_factory_make ("fakesink", NULL); fail_unless (gst_element_link (src, sink) != FALSE); gst_element_unlink (src, sink); gst_object_unref (src); gst_object_unref (sink); } GST_END_TEST; GST_START_TEST (test_set_value_from_string) { GValue val = { 0, }; /* g_return_if_fail */ ASSERT_CRITICAL (gst_util_set_value_from_string (NULL, "xyz")); g_value_init (&val, G_TYPE_STRING); ASSERT_CRITICAL (gst_util_set_value_from_string (&val, NULL)); g_value_unset (&val); /* string => string */ g_value_init (&val, G_TYPE_STRING); gst_util_set_value_from_string (&val, "Y00"); fail_unless (g_value_get_string (&val) != NULL); fail_unless_equals_string (g_value_get_string (&val), "Y00"); g_value_unset (&val); /* string => int */ g_value_init (&val, G_TYPE_INT); gst_util_set_value_from_string (&val, "987654321"); fail_unless (g_value_get_int (&val) == 987654321); g_value_unset (&val); g_value_init (&val, G_TYPE_INT); ASSERT_CRITICAL (gst_util_set_value_from_string (&val, "xyz")); g_value_unset (&val); /* string => uint */ g_value_init (&val, G_TYPE_UINT); gst_util_set_value_from_string (&val, "987654321"); fail_unless (g_value_get_uint (&val) == 987654321); g_value_unset (&val); /* CHECKME: is this really desired behaviour? (tpm) */ g_value_init (&val, G_TYPE_UINT); gst_util_set_value_from_string (&val, "-999"); fail_unless (g_value_get_uint (&val) == ((guint) 0 - (guint) 999)); g_value_unset (&val); g_value_init (&val, G_TYPE_UINT); ASSERT_CRITICAL (gst_util_set_value_from_string (&val, "xyz")); g_value_unset (&val); /* string => long */ g_value_init (&val, G_TYPE_LONG); gst_util_set_value_from_string (&val, "987654321"); fail_unless (g_value_get_long (&val) == 987654321); g_value_unset (&val); g_value_init (&val, G_TYPE_LONG); ASSERT_CRITICAL (gst_util_set_value_from_string (&val, "xyz")); g_value_unset (&val); /* string => ulong */ g_value_init (&val, G_TYPE_ULONG); gst_util_set_value_from_string (&val, "987654321"); fail_unless (g_value_get_ulong (&val) == 987654321); g_value_unset (&val); /* CHECKME: is this really desired behaviour? (tpm) */ g_value_init (&val, G_TYPE_ULONG); gst_util_set_value_from_string (&val, "-999"); fail_unless (g_value_get_ulong (&val) == ((gulong) 0 - (gulong) 999)); g_value_unset (&val); g_value_init (&val, G_TYPE_ULONG); ASSERT_CRITICAL (gst_util_set_value_from_string (&val, "xyz")); g_value_unset (&val); /* string => boolean */ g_value_init (&val, G_TYPE_BOOLEAN); gst_util_set_value_from_string (&val, "true"); fail_unless_equals_int (g_value_get_boolean (&val), TRUE); g_value_unset (&val); g_value_init (&val, G_TYPE_BOOLEAN); gst_util_set_value_from_string (&val, "TRUE"); fail_unless_equals_int (g_value_get_boolean (&val), TRUE); g_value_unset (&val); g_value_init (&val, G_TYPE_BOOLEAN); gst_util_set_value_from_string (&val, "false"); fail_unless_equals_int (g_value_get_boolean (&val), FALSE); g_value_unset (&val); g_value_init (&val, G_TYPE_BOOLEAN); gst_util_set_value_from_string (&val, "FALSE"); fail_unless_equals_int (g_value_get_boolean (&val), FALSE); g_value_unset (&val); g_value_init (&val, G_TYPE_BOOLEAN); gst_util_set_value_from_string (&val, "bleh"); fail_unless_equals_int (g_value_get_boolean (&val), FALSE); g_value_unset (&val); #if 0 /* string => float (yay, localisation issues involved) */ g_value_init (&val, G_TYPE_FLOAT); gst_util_set_value_from_string (&val, "987.654"); fail_unless (g_value_get_float (&val) >= 987.653 && g_value_get_float (&val) <= 987.655); g_value_unset (&val); g_value_init (&val, G_TYPE_FLOAT); gst_util_set_value_from_string (&val, "987,654"); fail_unless (g_value_get_float (&val) >= 987.653 && g_value_get_float (&val) <= 987.655); g_value_unset (&val); /* string => double (yay, localisation issues involved) */ g_value_init (&val, G_TYPE_DOUBLE); gst_util_set_value_from_string (&val, "987.654"); fail_unless (g_value_get_double (&val) >= 987.653 && g_value_get_double (&val) <= 987.655); g_value_unset (&val); g_value_init (&val, G_TYPE_DOUBLE); gst_util_set_value_from_string (&val, "987,654"); fail_unless (g_value_get_double (&val) >= 987.653 && g_value_get_double (&val) <= 987.655); g_value_unset (&val); #endif } GST_END_TEST; static gint _binary_search_compare (guint32 * a, guint32 * b) { return *a - *b; } GST_START_TEST (test_binary_search) { guint32 data[257]; guint32 *match; guint32 search_element = 121 * 2; guint i; for (i = 0; i < 257; i++) data[i] = (i + 1) * 2; match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_EXACT, &search_element, NULL); fail_unless (match != NULL); fail_unless_equals_int (match - data, 120); match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_BEFORE, &search_element, NULL); fail_unless (match != NULL); fail_unless_equals_int (match - data, 120); match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_AFTER, &search_element, NULL); fail_unless (match != NULL); fail_unless_equals_int (match - data, 120); search_element = 0; match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_EXACT, &search_element, NULL); fail_unless (match == NULL); match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_AFTER, &search_element, NULL); fail_unless (match != NULL); fail_unless_equals_int (match - data, 0); match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_BEFORE, &search_element, NULL); fail_unless (match == NULL); search_element = 1000; match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_EXACT, &search_element, NULL); fail_unless (match == NULL); match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_AFTER, &search_element, NULL); fail_unless (match == NULL); match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_BEFORE, &search_element, NULL); fail_unless (match != NULL); fail_unless_equals_int (match - data, 256); search_element = 121 * 2 - 1; match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_EXACT, &search_element, NULL); fail_unless (match == NULL); match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_AFTER, &search_element, NULL); fail_unless (match != NULL); fail_unless_equals_int (match - data, 120); match = (guint32 *) gst_util_array_binary_search (data, 257, sizeof (guint32), (GCompareDataFunc) _binary_search_compare, GST_SEARCH_MODE_BEFORE, &search_element, NULL); fail_unless (match != NULL); fail_unless_equals_int (match - data, 119); } GST_END_TEST; #ifdef HAVE_GSL #ifdef HAVE_GMP #include <gsl/gsl_rng.h> #include <gmp.h> static guint64 randguint64 (gsl_rng * rng, guint64 n) { union { guint64 x; struct { guint16 a, b, c, d; } parts; } x; x.parts.a = gsl_rng_uniform_int (rng, 1 << 16); x.parts.b = gsl_rng_uniform_int (rng, 1 << 16); x.parts.c = gsl_rng_uniform_int (rng, 1 << 16); x.parts.d = gsl_rng_uniform_int (rng, 1 << 16); return x.x % n; } enum round_t { ROUND_TONEAREST = 0, ROUND_UP, ROUND_DOWN }; static void gmp_set_uint64 (mpz_t mp, guint64 x) { mpz_t two_32, tmp; mpz_init (two_32); mpz_init (tmp); mpz_ui_pow_ui (two_32, 2, 32); mpz_set_ui (mp, (unsigned long) ((x >> 32) & G_MAXUINT32)); mpz_mul (tmp, mp, two_32); mpz_add_ui (mp, tmp, (unsigned long) (x & G_MAXUINT32)); mpz_clear (two_32); mpz_clear (tmp); } static guint64 gmp_get_uint64 (mpz_t mp) { mpz_t two_64, two_32, tmp; guint64 ret; mpz_init (two_64); mpz_init (two_32); mpz_init (tmp); mpz_ui_pow_ui (two_64, 2, 64); mpz_ui_pow_ui (two_32, 2, 32); if (mpz_cmp (tmp, two_64) >= 0) return G_MAXUINT64; mpz_clear (two_64); mpz_tdiv_q (tmp, mp, two_32); ret = mpz_get_ui (tmp); ret <<= 32; ret |= mpz_get_ui (mp); mpz_clear (two_32); mpz_clear (tmp); return ret; } static guint64 gmp_scale (guint64 x, guint64 a, guint64 b, enum round_t mode) { mpz_t mp1, mp2, mp3; if (!b) /* overflow */ return G_MAXUINT64; mpz_init (mp1); mpz_init (mp2); mpz_init (mp3); gmp_set_uint64 (mp1, x); gmp_set_uint64 (mp3, a); mpz_mul (mp2, mp1, mp3); switch (mode) { case ROUND_TONEAREST: gmp_set_uint64 (mp1, b); mpz_tdiv_q_ui (mp3, mp1, 2); mpz_add (mp1, mp2, mp3); mpz_set (mp2, mp1); break; case ROUND_UP: gmp_set_uint64 (mp1, b); mpz_sub_ui (mp3, mp1, 1); mpz_add (mp1, mp2, mp3); mpz_set (mp2, mp1); break; case ROUND_DOWN: break; } gmp_set_uint64 (mp3, b); mpz_tdiv_q (mp1, mp2, mp3); x = gmp_get_uint64 (mp1); mpz_clear (mp1); mpz_clear (mp2); mpz_clear (mp3); return x; } static void _gmp_test_scale (gsl_rng * rng) { guint64 bygst, bygmp; guint64 a = randguint64 (rng, gsl_rng_uniform_int (rng, 2) ? G_MAXUINT64 : G_MAXUINT32); guint64 b = randguint64 (rng, gsl_rng_uniform_int (rng, 2) ? G_MAXUINT64 - 1 : G_MAXUINT32 - 1) + 1; /* 0 not allowed */ guint64 val = randguint64 (rng, gmp_scale (G_MAXUINT64, b, a, ROUND_DOWN)); enum round_t mode = gsl_rng_uniform_int (rng, 3); const char *func; bygmp = gmp_scale (val, a, b, mode); switch (mode) { case ROUND_TONEAREST: bygst = gst_util_uint64_scale_round (val, a, b); func = "gst_util_uint64_scale_round"; break; case ROUND_UP: bygst = gst_util_uint64_scale_ceil (val, a, b); func = "gst_util_uint64_scale_ceil"; break; case ROUND_DOWN: bygst = gst_util_uint64_scale (val, a, b); func = "gst_util_uint64_scale"; break; default: g_assert_not_reached (); break; } fail_unless (bygst == bygmp, "error: %s(): %" G_GUINT64_FORMAT " * %" G_GUINT64_FORMAT " / %" G_GUINT64_FORMAT " = %" G_GUINT64_FORMAT ", correct = %" G_GUINT64_FORMAT "\n", func, val, a, b, bygst, bygmp); } static void _gmp_test_scale_int (gsl_rng * rng) { guint64 bygst, bygmp; gint32 a = randguint64 (rng, G_MAXINT32); gint32 b = randguint64 (rng, G_MAXINT32 - 1) + 1; /* 0 not allowed */ guint64 val = randguint64 (rng, gmp_scale (G_MAXUINT64, b, a, ROUND_DOWN)); enum round_t mode = gsl_rng_uniform_int (rng, 3); const char *func; bygmp = gmp_scale (val, a, b, mode); switch (mode) { case ROUND_TONEAREST: bygst = gst_util_uint64_scale_int_round (val, a, b); func = "gst_util_uint64_scale_int_round"; break; case ROUND_UP: bygst = gst_util_uint64_scale_int_ceil (val, a, b); func = "gst_util_uint64_scale_int_ceil"; break; case ROUND_DOWN: bygst = gst_util_uint64_scale_int (val, a, b); func = "gst_util_uint64_scale_int"; break; default: g_assert_not_reached (); break; } fail_unless (bygst == bygmp, "error: %s(): %" G_GUINT64_FORMAT " * %d / %d = %" G_GUINT64_FORMAT ", correct = %" G_GUINT64_FORMAT "\n", func, val, a, b, bygst, bygmp); } #define GMP_TEST_RUNS 100000 GST_START_TEST (test_math_scale_gmp) { gsl_rng *rng = gsl_rng_alloc (gsl_rng_mt19937); gint n; for (n = 0; n < GMP_TEST_RUNS; n++) _gmp_test_scale (rng); gsl_rng_free (rng); } GST_END_TEST; GST_START_TEST (test_math_scale_gmp_int) { gsl_rng *rng = gsl_rng_alloc (gsl_rng_mt19937); gint n; for (n = 0; n < GMP_TEST_RUNS; n++) _gmp_test_scale_int (rng); gsl_rng_free (rng); } GST_END_TEST; #endif #endif GST_START_TEST (test_pad_proxy_query_caps_aggregation) { GstElement *tee, *sink1, *sink2; GstCaps *caps; GstPad *tee_src1, *tee_src2, *tee_sink, *sink1_sink, *sink2_sink; tee = gst_element_factory_make ("tee", "tee"); sink1 = gst_element_factory_make ("fakesink", "sink1"); tee_src1 = gst_element_get_request_pad (tee, "src_%u"); sink1_sink = gst_element_get_static_pad (sink1, "sink"); fail_unless_equals_int (gst_pad_link (tee_src1, sink1_sink), GST_PAD_LINK_OK); sink2 = gst_element_factory_make ("fakesink", "sink2"); tee_src2 = gst_element_get_request_pad (tee, "src_%u"); sink2_sink = gst_element_get_static_pad (sink2, "sink"); fail_unless_equals_int (gst_pad_link (tee_src2, sink2_sink), GST_PAD_LINK_OK); tee_sink = gst_element_get_static_pad (tee, "sink"); gst_element_set_state (sink1, GST_STATE_PAUSED); gst_element_set_state (sink2, GST_STATE_PAUSED); gst_element_set_state (tee, GST_STATE_PAUSED); /* by default, ANY caps should intersect to ANY */ caps = gst_pad_query_caps (tee_sink, NULL); GST_INFO ("got caps: %" GST_PTR_FORMAT, caps); fail_unless (caps != NULL); fail_unless (gst_caps_is_any (caps)); gst_caps_unref (caps); /* these don't intersect we should get empty caps */ caps = gst_caps_new_empty_simple ("foo/bar"); fail_unless (gst_pad_set_caps (sink1_sink, caps)); gst_pad_use_fixed_caps (sink1_sink); gst_caps_unref (caps); caps = gst_caps_new_empty_simple ("bar/ter"); fail_unless (gst_pad_set_caps (sink2_sink, caps)); gst_pad_use_fixed_caps (sink2_sink); gst_caps_unref (caps); caps = gst_pad_query_caps (tee_sink, NULL); GST_INFO ("got caps: %" GST_PTR_FORMAT, caps); fail_unless (caps != NULL); fail_unless (gst_caps_is_empty (caps)); gst_caps_unref (caps); /* test intersection */ caps = gst_caps_new_simple ("foo/bar", "barversion", G_TYPE_INT, 1, NULL); GST_OBJECT_FLAG_UNSET (sink2_sink, GST_PAD_FLAG_FIXED_CAPS); fail_unless (gst_pad_set_caps (sink2_sink, caps)); gst_pad_use_fixed_caps (sink2_sink); gst_caps_unref (caps); caps = gst_pad_query_caps (tee_sink, NULL); GST_INFO ("got caps: %" GST_PTR_FORMAT, caps); fail_unless (caps != NULL); fail_if (gst_caps_is_empty (caps)); { GstStructure *s = gst_caps_get_structure (caps, 0); fail_unless_equals_string (gst_structure_get_name (s), "foo/bar"); fail_unless (gst_structure_has_field_typed (s, "barversion", G_TYPE_INT)); } gst_caps_unref (caps); gst_element_set_state (sink1, GST_STATE_NULL); gst_element_set_state (sink2, GST_STATE_NULL); gst_element_set_state (tee, GST_STATE_NULL); /* clean up */ gst_element_release_request_pad (tee, tee_src1); gst_object_unref (tee_src1); gst_element_release_request_pad (tee, tee_src2); gst_object_unref (tee_src2); gst_object_unref (tee_sink); gst_object_unref (tee); gst_object_unref (sink1_sink); gst_object_unref (sink1); gst_object_unref (sink2_sink); gst_object_unref (sink2); } GST_END_TEST; GST_START_TEST (test_greatest_common_divisor) { fail_if (gst_util_greatest_common_divisor (1, 1) != 1); fail_if (gst_util_greatest_common_divisor (2, 3) != 1); fail_if (gst_util_greatest_common_divisor (3, 5) != 1); fail_if (gst_util_greatest_common_divisor (-1, 1) != 1); fail_if (gst_util_greatest_common_divisor (-2, 3) != 1); fail_if (gst_util_greatest_common_divisor (-3, 5) != 1); fail_if (gst_util_greatest_common_divisor (-1, -1) != 1); fail_if (gst_util_greatest_common_divisor (-2, -3) != 1); fail_if (gst_util_greatest_common_divisor (-3, -5) != 1); fail_if (gst_util_greatest_common_divisor (1, -1) != 1); fail_if (gst_util_greatest_common_divisor (2, -3) != 1); fail_if (gst_util_greatest_common_divisor (3, -5) != 1); fail_if (gst_util_greatest_common_divisor (2, 2) != 2); fail_if (gst_util_greatest_common_divisor (2, 4) != 2); fail_if (gst_util_greatest_common_divisor (1001, 11) != 11); } GST_END_TEST; GST_START_TEST (test_read_macros) { guint8 carray[] = "ABCDEFGH"; /* 0x41 ... 0x48 */ guint32 uarray[2]; guint8 *cpointer; memcpy (uarray, carray, 8); cpointer = carray; /* 16 bit */ /* First try the standard pointer variants */ fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer), 0x4142); fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 1), 0x4243); fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 2), 0x4344); fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 3), 0x4445); fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 4), 0x4546); fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 5), 0x4647); fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer + 6), 0x4748); fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer), 0x4241); fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 1), 0x4342); fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 2), 0x4443); fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 3), 0x4544); fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 4), 0x4645); fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 5), 0x4746); fail_unless_equals_int_hex (GST_READ_UINT16_LE (cpointer + 6), 0x4847); /* On an array of guint8 */ fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray), 0x4142); fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 1), 0x4243); fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 2), 0x4344); fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 3), 0x4445); fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 4), 0x4546); fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 5), 0x4647); fail_unless_equals_int_hex (GST_READ_UINT16_BE (carray + 6), 0x4748); fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray), 0x4241); fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 1), 0x4342); fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 2), 0x4443); fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 3), 0x4544); fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 4), 0x4645); fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 5), 0x4746); fail_unless_equals_int_hex (GST_READ_UINT16_LE (carray + 6), 0x4847); /* On an array of guint32 */ fail_unless_equals_int_hex (GST_READ_UINT16_BE (uarray), 0x4142); fail_unless_equals_int_hex (GST_READ_UINT16_BE (uarray + 1), 0x4546); fail_unless_equals_int_hex (GST_READ_UINT16_LE (uarray), 0x4241); fail_unless_equals_int_hex (GST_READ_UINT16_LE (uarray + 1), 0x4645); /* 24bit */ /* First try the standard pointer variants */ fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer), 0x414243); fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 1), 0x424344); fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 2), 0x434445); fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 3), 0x444546); fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 4), 0x454647); fail_unless_equals_int_hex (GST_READ_UINT24_BE (cpointer + 5), 0x464748); fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer), 0x434241); fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 1), 0x444342); fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 2), 0x454443); fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 3), 0x464544); fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 4), 0x474645); fail_unless_equals_int_hex (GST_READ_UINT24_LE (cpointer + 5), 0x484746); /* On an array of guint8 */ fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray), 0x414243); fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 1), 0x424344); fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 2), 0x434445); fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 3), 0x444546); fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 4), 0x454647); fail_unless_equals_int_hex (GST_READ_UINT24_BE (carray + 5), 0x464748); fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray), 0x434241); fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 1), 0x444342); fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 2), 0x454443); fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 3), 0x464544); fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 4), 0x474645); fail_unless_equals_int_hex (GST_READ_UINT24_LE (carray + 5), 0x484746); /* On an array of guint32 */ fail_unless_equals_int_hex (GST_READ_UINT24_BE (uarray), 0x414243); fail_unless_equals_int_hex (GST_READ_UINT24_BE (uarray + 1), 0x454647); fail_unless_equals_int_hex (GST_READ_UINT24_LE (uarray), 0x434241); fail_unless_equals_int_hex (GST_READ_UINT24_LE (uarray + 1), 0x474645); /* 32bit */ /* First try the standard pointer variants */ fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer), 0x41424344); fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer + 1), 0x42434445); fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer + 2), 0x43444546); fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer + 3), 0x44454647); fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer + 4), 0x45464748); fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer), 0x44434241); fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer + 1), 0x45444342); fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer + 2), 0x46454443); fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer + 3), 0x47464544); fail_unless_equals_int_hex (GST_READ_UINT32_LE (cpointer + 4), 0x48474645); /* On an array of guint8 */ fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray), 0x41424344); fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray + 1), 0x42434445); fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray + 2), 0x43444546); fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray + 3), 0x44454647); fail_unless_equals_int_hex (GST_READ_UINT32_BE (carray + 4), 0x45464748); fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray), 0x44434241); fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray + 1), 0x45444342); fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray + 2), 0x46454443); fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray + 3), 0x47464544); fail_unless_equals_int_hex (GST_READ_UINT32_LE (carray + 4), 0x48474645); /* On an array of guint32 */ fail_unless_equals_int_hex (GST_READ_UINT32_BE (uarray), 0x41424344); fail_unless_equals_int_hex (GST_READ_UINT32_BE (uarray + 1), 0x45464748); fail_unless_equals_int_hex (GST_READ_UINT32_LE (uarray), 0x44434241); fail_unless_equals_int_hex (GST_READ_UINT32_LE (uarray + 1), 0x48474645); /* 64bit */ fail_unless_equals_int64_hex (GST_READ_UINT64_BE (cpointer), 0x4142434445464748); fail_unless_equals_int64_hex (GST_READ_UINT64_LE (cpointer), 0x4847464544434241); fail_unless_equals_int64_hex (GST_READ_UINT64_BE (carray), 0x4142434445464748); fail_unless_equals_int64_hex (GST_READ_UINT64_LE (carray), 0x4847464544434241); fail_unless_equals_int64_hex (GST_READ_UINT64_BE (uarray), 0x4142434445464748); fail_unless_equals_int64_hex (GST_READ_UINT64_LE (uarray), 0x4847464544434241); /* make sure the data argument is not duplicated inside the macro * with possibly unexpected side-effects */ cpointer = carray; fail_unless_equals_int (GST_READ_UINT8 (cpointer++), 'A'); fail_unless (cpointer == carray + 1); cpointer = carray; fail_unless_equals_int_hex (GST_READ_UINT16_BE (cpointer++), 0x4142); fail_unless (cpointer == carray + 1); cpointer = carray; fail_unless_equals_int_hex (GST_READ_UINT32_BE (cpointer++), 0x41424344); fail_unless (cpointer == carray + 1); cpointer = carray; fail_unless_equals_int64_hex (GST_READ_UINT64_BE (cpointer++), 0x4142434445464748); fail_unless (cpointer == carray + 1); } GST_END_TEST; GST_START_TEST (test_write_macros) { guint8 carray[8]; guint8 *cpointer; /* make sure the data argument is not duplicated inside the macro * with possibly unexpected side-effects */ memset (carray, 0, sizeof (carray)); cpointer = carray; GST_WRITE_UINT8 (cpointer++, 'A'); fail_unless_equals_pointer (cpointer, carray + 1); fail_unless_equals_int (carray[0], 'A'); memset (carray, 0, sizeof (carray)); cpointer = carray; GST_WRITE_UINT16_BE (cpointer++, 0x4142); fail_unless_equals_pointer (cpointer, carray + 1); fail_unless_equals_int (carray[0], 'A'); fail_unless_equals_int (carray[1], 'B'); memset (carray, 0, sizeof (carray)); cpointer = carray; GST_WRITE_UINT32_BE (cpointer++, 0x41424344); fail_unless_equals_pointer (cpointer, carray + 1); fail_unless_equals_int (carray[0], 'A'); fail_unless_equals_int (carray[3], 'D'); memset (carray, 0, sizeof (carray)); cpointer = carray; GST_WRITE_UINT64_BE (cpointer++, 0x4142434445464748); fail_unless_equals_pointer (cpointer, carray + 1); fail_unless_equals_int (carray[0], 'A'); fail_unless_equals_int (carray[7], 'H'); memset (carray, 0, sizeof (carray)); cpointer = carray; GST_WRITE_UINT16_LE (cpointer++, 0x4142); fail_unless_equals_pointer (cpointer, carray + 1); fail_unless_equals_int (carray[0], 'B'); fail_unless_equals_int (carray[1], 'A'); memset (carray, 0, sizeof (carray)); cpointer = carray; GST_WRITE_UINT32_LE (cpointer++, 0x41424344); fail_unless_equals_pointer (cpointer, carray + 1); fail_unless_equals_int (carray[0], 'D'); fail_unless_equals_int (carray[3], 'A'); memset (carray, 0, sizeof (carray)); cpointer = carray; GST_WRITE_UINT64_LE (cpointer++, 0x4142434445464748); fail_unless_equals_pointer (cpointer, carray + 1); fail_unless_equals_int (carray[0], 'H'); fail_unless_equals_int (carray[7], 'A'); } GST_END_TEST; static void count_request_pad (const GValue * item, gpointer user_data) { GstPad *pad = GST_PAD (g_value_get_object (item)); guint *count = (guint *) user_data; if (GST_PAD_TEMPLATE_PRESENCE (GST_PAD_PAD_TEMPLATE (pad)) == GST_PAD_REQUEST) (*count)++; } static guint request_pads (GstElement * element) { GstIterator *iter; guint pads = 0; iter = gst_element_iterate_pads (element); fail_unless (gst_iterator_foreach (iter, count_request_pad, &pads) == GST_ITERATOR_DONE); gst_iterator_free (iter); return pads; } static GstPadLinkReturn refuse_to_link (GstPad * pad, GstObject * parent, GstPad * peer) { return GST_PAD_LINK_REFUSED; } typedef struct _GstFakeReqSink GstFakeReqSink; typedef struct _GstFakeReqSinkClass GstFakeReqSinkClass; struct _GstFakeReqSink { GstElement element; }; struct _GstFakeReqSinkClass { GstElementClass parent_class; }; G_GNUC_INTERNAL GType gst_fakereqsink_get_type (void); static GstStaticPadTemplate fakereqsink_sink_template = GST_STATIC_PAD_TEMPLATE ("sink_%u", GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS_ANY); G_DEFINE_TYPE (GstFakeReqSink, gst_fakereqsink, GST_TYPE_ELEMENT); static GstPad * gst_fakereqsink_request_new_pad (GstElement * element, GstPadTemplate * templ, const gchar * name, const GstCaps * caps) { GstPad *pad; pad = gst_pad_new_from_static_template (&fakereqsink_sink_template, name); gst_pad_set_link_function (pad, refuse_to_link); gst_element_add_pad (GST_ELEMENT_CAST (element), pad); return pad; } static void gst_fakereqsink_release_pad (GstElement * element, GstPad * pad) { gst_pad_set_active (pad, FALSE); gst_element_remove_pad (element, pad); } static void gst_fakereqsink_class_init (GstFakeReqSinkClass * klass) { GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); gst_element_class_set_static_metadata (gstelement_class, "Fake Request Sink", "Sink", "Fake sink with request pads", "Sebastian Rasmussen <sebras@hotmail.com>"); gst_element_class_add_static_pad_template (gstelement_class, &fakereqsink_sink_template); gstelement_class->request_new_pad = gst_fakereqsink_request_new_pad; gstelement_class->release_pad = gst_fakereqsink_release_pad; } static void gst_fakereqsink_init (GstFakeReqSink * fakereqsink) { } static void test_link (const gchar * expectation, const gchar * srcname, const gchar * srcpad, const gchar * srcstate, const gchar * sinkname, const gchar * sinkpad, const gchar * sinkstate) { GstElement *src, *sink, *othersrc, *othersink; guint src_pads, sink_pads; if (g_strcmp0 (srcname, "requestsrc") == 0) src = gst_element_factory_make ("tee", NULL); else if (g_strcmp0 (srcname, "requestsink") == 0) src = gst_element_factory_make ("funnel", NULL); else if (g_strcmp0 (srcname, "staticsrc") == 0) src = gst_element_factory_make ("fakesrc", NULL); else if (g_strcmp0 (srcname, "staticsink") == 0) src = gst_element_factory_make ("fakesink", NULL); else g_assert_not_reached (); if (g_strcmp0 (sinkname, "requestsink") == 0) sink = gst_element_factory_make ("funnel", NULL); else if (g_strcmp0 (sinkname, "requestsrc") == 0) sink = gst_element_factory_make ("tee", NULL); else if (g_strcmp0 (sinkname, "staticsink") == 0) sink = gst_element_factory_make ("fakesink", NULL); else if (g_strcmp0 (sinkname, "staticsrc") == 0) sink = gst_element_factory_make ("fakesrc", NULL); else if (g_strcmp0 (sinkname, "fakerequestsink") == 0) sink = gst_element_factory_make ("fakereqsink", NULL); else g_assert_not_reached (); othersrc = gst_element_factory_make ("fakesrc", NULL); othersink = gst_element_factory_make ("fakesink", NULL); if (g_strcmp0 (srcstate, "linked") == 0) fail_unless (gst_element_link_pads (src, srcpad, othersink, NULL)); if (g_strcmp0 (sinkstate, "linked") == 0) fail_unless (gst_element_link_pads (othersrc, NULL, sink, sinkpad)); if (g_strcmp0 (srcstate, "unlinkable") == 0) { GstPad *pad = gst_element_get_static_pad (src, srcpad ? srcpad : "src"); gst_pad_set_link_function (pad, refuse_to_link); gst_object_unref (pad); } if (g_strcmp0 (sinkstate, "unlinkable") == 0) { GstPad *pad = gst_element_get_static_pad (sink, sinkpad ? sinkpad : "sink"); gst_pad_set_link_function (pad, refuse_to_link); gst_object_unref (pad); } src_pads = request_pads (src); sink_pads = request_pads (sink); if (g_strcmp0 (expectation, "OK") == 0) { fail_unless (gst_element_link_pads (src, srcpad, sink, sinkpad)); if (g_str_has_prefix (srcname, "request")) { fail_unless_equals_int (request_pads (src), src_pads + 1); } else { fail_unless_equals_int (request_pads (src), src_pads); } if (g_str_has_prefix (sinkname, "request")) { fail_unless_equals_int (request_pads (sink), sink_pads + 1); } else { fail_unless_equals_int (request_pads (sink), sink_pads); } } else { fail_if (gst_element_link_pads (src, srcpad, sink, sinkpad)); fail_unless_equals_int (request_pads (src), src_pads); fail_unless_equals_int (request_pads (sink), sink_pads); } gst_object_unref (othersrc); gst_object_unref (othersink); gst_object_unref (src); gst_object_unref (sink); } GST_START_TEST (test_element_link) { /* Successful cases */ gst_element_register (NULL, "fakereqsink", GST_RANK_NONE, gst_fakereqsink_get_type ()); test_link ("OK", "staticsrc", "src", "", "staticsink", "sink", ""); test_link ("OK", "staticsrc", "src", "", "requestsink", "sink_0", ""); test_link ("OK", "staticsrc", "src", "", "staticsink", NULL, ""); test_link ("OK", "staticsrc", "src", "", "requestsink", NULL, ""); test_link ("OK", "requestsrc", "src_0", "", "staticsink", "sink", ""); test_link ("OK", "requestsrc", "src_0", "", "requestsink", "sink_0", ""); test_link ("OK", "requestsrc", "src_0", "", "staticsink", NULL, ""); test_link ("OK", "requestsrc", "src_0", "", "requestsink", NULL, ""); test_link ("OK", "staticsrc", NULL, "", "staticsink", "sink", ""); test_link ("OK", "staticsrc", NULL, "", "requestsink", "sink_0", ""); test_link ("OK", "staticsrc", NULL, "", "staticsink", NULL, ""); test_link ("OK", "staticsrc", NULL, "", "requestsink", NULL, ""); test_link ("OK", "requestsrc", NULL, "", "staticsink", "sink", ""); test_link ("OK", "requestsrc", NULL, "", "requestsink", "sink_0", ""); test_link ("OK", "requestsrc", NULL, "", "staticsink", NULL, ""); test_link ("OK", "requestsrc", NULL, "", "requestsink", NULL, ""); /* Failure cases */ test_link ("NOK", "staticsrc", "missing", "", "staticsink", "sink", ""); test_link ("NOK", "staticsink", "sink", "", "staticsink", "sink", ""); test_link ("NOK", "staticsrc", "src", "linked", "staticsink", "sink", ""); test_link ("NOK", "staticsrc", "src", "", "staticsink", "missing", ""); test_link ("NOK", "staticsrc", "src", "", "staticsrc", "src", ""); test_link ("NOK", "staticsrc", "src", "", "staticsink", "sink", "linked"); test_link ("NOK", "staticsrc", "src", "", "staticsink", "sink", "unlinkable"); test_link ("NOK", "staticsrc", NULL, "", "staticsink", "sink", "unlinkable"); test_link ("NOK", "staticsrc", NULL, "", "staticsink", NULL, "unlinkable"); test_link ("NOK", "requestsrc", "missing", "", "staticsink", "sink", ""); test_link ("NOK", "requestsink", "sink_0", "", "staticsink", "sink", ""); test_link ("NOK", "requestsrc", "src_0", "linked", "staticsink", "sink", ""); test_link ("NOK", "requestsrc", "src_0", "", "staticsink", "missing", ""); test_link ("NOK", "requestsrc", "src_0", "", "staticsrc", "src", ""); test_link ("NOK", "requestsrc", "src_0", "", "staticsink", "sink", "linked"); test_link ("NOK", "requestsrc", "src_0", "", "staticsink", "sink", "unlinkable"); test_link ("NOK", "requestsrc", NULL, "", "staticsink", "sink", "unlinkable"); test_link ("NOK", "requestsrc", NULL, "", "staticsink", NULL, "unlinkable"); test_link ("NOK", "staticsrc", "missing", "", "requestsink", "sink_0", ""); test_link ("NOK", "staticsink", "sink", "", "requestsink", "sink_0", ""); test_link ("NOK", "staticsrc", "src", "linked", "requestsink", "sink_0", ""); test_link ("NOK", "staticsrc", "src", "", "requestsink", "missing", ""); test_link ("NOK", "staticsrc", "src", "", "requestsrc", "src_0", ""); test_link ("NOK", "staticsrc", "src", "", "requestsink", "sink_0", "linked"); test_link ("NOK", "staticsrc", "src", "unlinkable", "requestsink", "sink_0", ""); test_link ("NOK", "staticsrc", NULL, "unlinkable", "requestsink", "sink_0", ""); test_link ("NOK", "staticsrc", NULL, "unlinkable", "requestsink", NULL, ""); test_link ("NOK", "requestsrc", "src_0", "", "staticsink", NULL, "unlinkable"); test_link ("NOK", "requestsrc", NULL, "", "fakerequestsink", NULL, ""); } GST_END_TEST; typedef struct _GstTestPadReqSink GstTestPadReqSink; typedef struct _GstTestPadReqSinkClass GstTestPadReqSinkClass; struct _GstTestPadReqSink { GstElement element; }; struct _GstTestPadReqSinkClass { GstElementClass parent_class; }; G_GNUC_INTERNAL GType gst_testpadreqsink_get_type (void); static GstStaticPadTemplate testpadreqsink_video_template = GST_STATIC_PAD_TEMPLATE ("video_%u", GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS ("video/x-raw")); static GstStaticPadTemplate testpadreqsink_audio_template = GST_STATIC_PAD_TEMPLATE ("audio_%u", GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS ("audio/x-raw")); G_DEFINE_TYPE (GstTestPadReqSink, gst_testpadreqsink, GST_TYPE_ELEMENT); static GstPad * gst_testpadreqsink_request_new_pad (GstElement * element, GstPadTemplate * templ, const gchar * name, const GstCaps * caps) { GstPad *pad; pad = gst_pad_new_from_template (templ, name); gst_pad_set_active (pad, TRUE); gst_element_add_pad (GST_ELEMENT_CAST (element), pad); return pad; } static void gst_testpadreqsink_release_pad (GstElement * element, GstPad * pad) { gst_pad_set_active (pad, FALSE); gst_element_remove_pad (element, pad); } static void gst_testpadreqsink_class_init (GstTestPadReqSinkClass * klass) { GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); gst_element_class_set_static_metadata (gstelement_class, "Test Pad Request Sink", "Sink", "Sink for unit tests with request pads", "Thiago Santos <thiagoss@osg.samsung.com>"); gst_element_class_add_static_pad_template (gstelement_class, &testpadreqsink_video_template); gst_element_class_add_static_pad_template (gstelement_class, &testpadreqsink_audio_template); gstelement_class->request_new_pad = gst_testpadreqsink_request_new_pad; gstelement_class->release_pad = gst_testpadreqsink_release_pad; } static void gst_testpadreqsink_init (GstTestPadReqSink * testpadeqsink) { } static GstCaps *padreqsink_query_caps = NULL; static gboolean testpadreqsink_peer_query (GstPad * pad, GstObject * parent, GstQuery * query) { gboolean res; switch (GST_QUERY_TYPE (query)) { case GST_QUERY_CAPS: if (padreqsink_query_caps) { gst_query_set_caps_result (query, padreqsink_query_caps); res = TRUE; break; } default: res = gst_pad_query_default (pad, parent, query); break; } return res; } static void check_get_compatible_pad_request (GstElement * element, GstCaps * peer_caps, GstCaps * filter, gboolean should_get_pad, const gchar * pad_tmpl_name) { GstPad *peer, *requested; GstPadTemplate *tmpl; gst_caps_replace (&padreqsink_query_caps, peer_caps); peer = gst_pad_new ("src", GST_PAD_SRC); gst_pad_set_query_function (peer, testpadreqsink_peer_query); requested = gst_element_get_compatible_pad (element, peer, filter); if (should_get_pad) { fail_unless (requested != NULL); if (pad_tmpl_name) { tmpl = gst_pad_get_pad_template (requested); fail_unless (strcmp (GST_PAD_TEMPLATE_NAME_TEMPLATE (tmpl), pad_tmpl_name) == 0); gst_object_unref (tmpl); } gst_element_release_request_pad (element, requested); gst_object_unref (requested); } else { fail_unless (requested == NULL); } if (peer_caps) gst_caps_unref (peer_caps); if (filter) gst_caps_unref (filter); gst_object_unref (peer); } GST_START_TEST (test_element_get_compatible_pad_request) { GstElement *element; gst_element_register (NULL, "testpadreqsink", GST_RANK_NONE, gst_testpadreqsink_get_type ()); element = gst_element_factory_make ("testpadreqsink", NULL); /* Try with a peer pad with any caps and no filter, * returning any pad is ok */ check_get_compatible_pad_request (element, NULL, NULL, TRUE, NULL); /* Try with a peer pad with any caps and video as filter */ check_get_compatible_pad_request (element, NULL, gst_caps_from_string ("video/x-raw"), TRUE, "video_%u"); /* Try with a peer pad with any caps and audio as filter */ check_get_compatible_pad_request (element, NULL, gst_caps_from_string ("audio/x-raw"), TRUE, "audio_%u"); /* Try with a peer pad with any caps and fake caps as filter */ check_get_compatible_pad_request (element, NULL, gst_caps_from_string ("foo/bar"), FALSE, NULL); /* Try with a peer pad with video caps and no caps as filter */ check_get_compatible_pad_request (element, gst_caps_from_string ("video/x-raw"), NULL, TRUE, "video_%u"); /* Try with a peer pad with audio caps and no caps as filter */ check_get_compatible_pad_request (element, gst_caps_from_string ("audio/x-raw"), NULL, TRUE, "audio_%u"); /* Try with a peer pad with video caps and foo caps as filter */ check_get_compatible_pad_request (element, gst_caps_from_string ("video/x-raw"), gst_caps_from_string ("foo/bar"), FALSE, NULL); gst_caps_replace (&padreqsink_query_caps, NULL); gst_object_unref (element); } GST_END_TEST; GST_START_TEST (test_element_link_with_ghost_pads) { GstElement *sink_bin, *sink2_bin, *pipeline; GstElement *src, *tee, *queue, *queue2, *sink, *sink2; GstMessage *message; GstBus *bus; fail_unless (pipeline = gst_pipeline_new (NULL)); fail_unless (sink_bin = gst_bin_new (NULL)); fail_unless (sink2_bin = gst_bin_new (NULL)); fail_unless (src = gst_element_factory_make ("fakesrc", NULL)); fail_unless (tee = gst_element_factory_make ("tee", NULL)); fail_unless (queue = gst_element_factory_make ("queue", NULL)); fail_unless (sink = gst_element_factory_make ("fakesink", NULL)); fail_unless (queue2 = gst_element_factory_make ("queue", NULL)); fail_unless (sink2 = gst_element_factory_make ("fakesink", NULL)); gst_bin_add_many (GST_BIN (pipeline), src, tee, queue, sink, sink2_bin, NULL); fail_unless (gst_element_link_many (src, tee, queue, sink, NULL)); fail_unless (gst_element_set_state (pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_ASYNC); /* wait for a buffer to arrive at the sink */ bus = gst_element_get_bus (pipeline); message = gst_bus_poll (bus, GST_MESSAGE_ASYNC_DONE, -1); gst_message_unref (message); gst_object_unref (bus); gst_bin_add_many (GST_BIN (sink_bin), queue2, sink2, NULL); fail_unless (gst_element_link (queue2, sink2)); gst_bin_add (GST_BIN (sink2_bin), sink_bin); /* The two levels of bins with the outer bin in the running state is * important, when the second ghost pad is created (from this * gst_element_link()) in the running bin, we need to activate the * created ghost pad */ fail_unless (gst_element_link (tee, queue2)); fail_unless (gst_element_set_state (pipeline, GST_STATE_NULL) == GST_STATE_CHANGE_SUCCESS); gst_object_unref (pipeline); } GST_END_TEST; static const GstClockTime times1[] = { 257116899087539, 120632754291904, 257117935914250, 120633825367344, 257119448289434, 120635306141271, 257120493671524, 120636384357825, 257121550784861, 120637417438878, 257123042669403, 120638895344150, 257124089184865, 120639971729651, 257125545836474, 120641406788243, 257127030618490, 120642885914220, 257128033712770, 120643888843907, 257129081768074, 120644981892002, 257130145383845, 120646016376867, 257131532530200, 120647389850987, 257132578136034, 120648472767247, 257134102475722, 120649953785315, 257135142994788, 120651028858556, 257136585079868, 120652441303624, 257137618260656, 120653491627112, 257139108694546, 120654963978184, 257140644022048, 120656500233068, 257141685671825, 120657578510655, 257142741238288, 120658610889805, 257144243633074, 120660093098060, 257145287962271, 120661172901525, 257146740596716, 120662591572179, 257147757607150, 120663622822179, 257149263992401, 120665135578527, 257150303719290, 120666176166905, 257151355569906, 120667217304601, 257152430578406, 120668326099768, 257153490501095, 120669360554111, 257154512360784, 120670365497960, 257155530610577, 120671399006259, 257156562091659, 120672432728185, 257157945388742, 120673800312414, 257159287547073, 120675142444983, 257160324912880, 120676215076817, 257345408328042, 120861261738196, 257346412270919, 120862265613926, 257347420532284, 120863278644933, 257348431187638, 120864284412754, 257349439018028, 120865293110265, 257351796217938, 120867651111973, 257352803038092, 120868659107578, 257354152688899, 120870008594883, 257355157088906, 120871011097327, 257356162439182, 120872016346348, 257357167872040, 120873021656407, 257358182440058, 120874048633945, 257359198881356, 120875052265538, 257100756525466, 120616619282139, 257101789337770, 120617655475988, 257102816323472, 120618674000157, 257103822485250, 120619679005039, 257104840760423, 120620710743321, 257105859459496, 120621715351476, 257106886662470, 120622764942539, 257108387497864, 120624244221106, 257109428859191, 120625321461096, 257110485892785, 120626356892003, 257111869872141, 120627726459874, 257112915903774, 120628813190830, 257114329982208, 120630187061682, 257115376666026, 120631271992101 }; static const GstClockTime times2[] = { 291678579009762, 162107345029507, 291679770464405, 162108597684538, 291680972924370, 162109745816863, 291682278949629, 162111000577605, 291683590706117, 162112357724822, 291684792322541, 162113613156950, 291685931362506, 162114760556854, 291687132156589, 162115909238493, 291688265012060, 162117120603240, 291689372183047, 162118126279508, 291705506022294, 162134329373992, 291667914301004, 162096795553658, 291668119537668, 162096949051905, 291668274671455, 162097049238371, 291668429435600, 162097256356719, 291668586128535, 162097355689763, 291668741306233, 162097565678460, 291668893789203, 162097661044916, 291669100256555, 162097865694145, 291669216417563, 162098069214693, 291669836394620, 162098677275530, 291669990447821, 162098792601263, 291670149426086, 162098916899184, 291670300232152, 162099114225621, 291670411261917, 162099236784112, 291670598483507, 162099402158751, 291671716582687, 162100558744122, 291672600759788, 162101499326359, 291673919988307, 162102751981384, 291675174441643, 162104005551939, 291676271562197, 162105105252898, 291677376345374, 162106195737516 }; static const GstClockTime times3[] = { 291881924291688, 162223997578228, 291883318122262, 162224167198360, 291884786394838, 162224335172501, 291886004374386, 162224503695531, 291887224353285, 162224673560021, 291888472403367, 162224843760361, 291889727977561, 162225014479362, 291890989982306, 162225174554558, 291892247875763, 162225339753039, 291893502163547, 162225673230987, 291894711382216, 162225829494101, 291895961021506, 162225964530832, 291897251690854, 162226127287981, 291898508630785, 162226303710406, 291899740172868, 162226472478047, 291900998878873, 162226637402085, 291902334919875, 162226797873245, 291903572196610, 162226964352963, 291904727342699, 162227125312525, 291906071189108, 162228361337153, 291907308146005, 162229560625638, 291908351925126, 162230604986650, 291909396411423, 162231653690543, 291910453965348, 162232698550995, 291912096870744, 162233475264947, 291913234148395, 162233606516855, 291915448096576, 162233921145559, 291916707748827, 162234047154298, 291918737451070, 162234370837425, 291919896016205, 162234705504337, 291921098663980, 162234872320397, 291922315691409, 162235031023366 }; static const GstClockTime times4[] = { 10, 0, 20, 20, 30, 40, 40, 60, 50, 80, 60, 100 }; struct test_entry { gint n; const GstClockTime *v; GstClockTime expect_internal; GstClockTime expect_external; guint64 expect_num; guint64 expect_denom; } times[] = { { 32, times1, 257154512360784, 120670380469753, 4052622913376634109, 4052799313904261962}, { 64, times1, 257359198881356, 120875054227405, 2011895759027682422, 2012014931360215503}, { 32, times2, 291705506022294, 162134297192792, 2319535707505209857, 2321009753483354451}, { 32, times3, 291922315691409, 162234934150296, 1370930728180888261, 4392719527011673456}, { 6, times4, 60, 100, 2, 1} }; GST_START_TEST (test_regression) { GstClockTime m_num, m_den, internal, external; gdouble r_squared, rate, expect_rate; gint i; for (i = 0; i < G_N_ELEMENTS (times); i++) { fail_unless (gst_calculate_linear_regression (times[i].v, NULL, times[i].n, &m_num, &m_den, &external, &internal, &r_squared)); GST_LOG ("xbase %" G_GUINT64_FORMAT " ybase %" G_GUINT64_FORMAT " rate = %" G_GUINT64_FORMAT " / %" G_GUINT64_FORMAT " = %.10f r_squared %f\n", internal, external, m_num, m_den, (gdouble) (m_num) / (m_den), r_squared); /* Require high correlation */ fail_unless (r_squared >= 0.9); fail_unless (internal == times[i].expect_internal, "Regression params %d fail. internal %" G_GUINT64_FORMAT " != expected %" G_GUINT64_FORMAT, i, internal, times[i].expect_internal); /* Rate must be within 1% tolerance */ expect_rate = ((gdouble) (times[i].expect_num) / times[i].expect_denom); rate = ((gdouble) (m_num) / m_den); fail_unless ((expect_rate - rate) >= -0.1 && (expect_rate - rate) <= 0.1, "Regression params %d fail. Rate out of range. Expected %f, got %f", i, expect_rate, rate); fail_unless (external >= times[i].expect_external * 0.99 && external <= times[i].expect_external * 1.01, "Regression params %d fail. external %" G_GUINT64_FORMAT " != expected %" G_GUINT64_FORMAT, i, external, times[i].expect_external); } } GST_END_TEST; static Suite * gst_utils_suite (void) { Suite *s = suite_create ("GstUtils"); TCase *tc_chain = tcase_create ("general"); suite_add_tcase (s, tc_chain); tcase_add_test (tc_chain, test_buffer_probe_n_times); tcase_add_test (tc_chain, test_buffer_probe_once); tcase_add_test (tc_chain, test_math_scale); tcase_add_test (tc_chain, test_math_scale_round); tcase_add_test (tc_chain, test_math_scale_ceil); tcase_add_test (tc_chain, test_math_scale_uint64); tcase_add_test (tc_chain, test_math_scale_random); #ifdef HAVE_GSL #ifdef HAVE_GMP tcase_add_test (tc_chain, test_math_scale_gmp); tcase_add_test (tc_chain, test_math_scale_gmp_int); #endif #endif tcase_add_test (tc_chain, test_guint64_to_gdouble); tcase_add_test (tc_chain, test_gdouble_to_guint64); #ifndef GST_DISABLE_PARSE tcase_add_test (tc_chain, test_parse_bin_from_description); #endif tcase_add_test (tc_chain, test_element_found_tags); tcase_add_test (tc_chain, test_element_link); tcase_add_test (tc_chain, test_element_link_with_ghost_pads); tcase_add_test (tc_chain, test_element_unlink); tcase_add_test (tc_chain, test_element_get_compatible_pad_request); tcase_add_test (tc_chain, test_set_value_from_string); tcase_add_test (tc_chain, test_binary_search); tcase_add_test (tc_chain, test_pad_proxy_query_caps_aggregation); tcase_add_test (tc_chain, test_greatest_common_divisor); tcase_add_test (tc_chain, test_read_macros); tcase_add_test (tc_chain, test_write_macros); tcase_add_test (tc_chain, test_regression); return s; } GST_CHECK_MAIN (gst_utils);
{ "alphanum_fraction": 0.7175292499, "avg_line_length": 33.7866066967, "ext": "c", "hexsha": "18ba199b98dc6926def327925da14cbc18b194ab", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-10-21T01:33:56.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-26T08:40:35.000Z", "max_forks_repo_head_hexsha": "209f4385425405676a581a749bb915e257dbc1c1", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "isabella232/aistreams", "max_forks_repo_path": "third_party/gstreamer/tests/check/gst/gstutils.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "209f4385425405676a581a749bb915e257dbc1c1", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:22:14.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-10T13:17:39.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "isabella232/aistreams", "max_issues_repo_path": "third_party/gstreamer/tests/check/gst/gstutils.c", "max_line_length": 123, "max_stars_count": 6, "max_stars_repo_head_hexsha": "209f4385425405676a581a749bb915e257dbc1c1", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "isabella232/aistreams", "max_stars_repo_path": "third_party/gstreamer/tests/check/gst/gstutils.c", "max_stars_repo_stars_event_max_datetime": "2021-10-21T01:34:04.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-22T18:07:15.000Z", "num_tokens": 21204, "size": 67607 }
#pragma once #include "Library.h" #include "Tile.h" #include "TileContentLoadResult.h" #include "TileContentLoader.h" #include "TileRefine.h" #include <gsl/span> #include <spdlog/fwd.h> #include <cstddef> #include <memory> #include <vector> namespace Cesium3DTilesSelection { class Tileset; /** * @brief Creates a {@link TileContentLoadResult} from 3D Tiles external * `tileset.json` data. */ class CESIUM3DTILESSELECTION_API ExternalTilesetContent final : public TileContentLoader { public: /** * @copydoc TileContentLoader::load * * The result will only contain the `childTiles` and the `pNewTileContext`. * Other fields will be empty or have default values. */ CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>> load(const TileContentLoadInput& input) override; private: /** * @brief Create the {@link TileContentLoadResult} from the given input data. * * @param pLogger The logger that receives details of loading errors and * warnings. * @param tileRefine The {@link TileRefine} * @param url The source URL * @param data The raw input data * @return The {@link TileContentLoadResult} */ static std::unique_ptr<TileContentLoadResult> load( const std::shared_ptr<spdlog::logger>& pLogger, const glm::dmat4& tileTransform, TileRefine tileRefine, const std::string& url, const gsl::span<const std::byte>& data); }; } // namespace Cesium3DTilesSelection
{ "alphanum_fraction": 0.7178082192, "avg_line_length": 26.0714285714, "ext": "h", "hexsha": "5325ea3f42d0bd96a74fbabb0ebe0225fb3e77f5", "lang": "C", "max_forks_count": 66, "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/ExternalTilesetContent.h", "max_issues_count": 256, "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/ExternalTilesetContent.h", "max_line_length": 79, "max_stars_count": 154, "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/ExternalTilesetContent.h", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "num_tokens": 375, "size": 1460 }
/* blas/blas.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2009 Gerard Jungman & Brian * Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* GSL implementation of BLAS operations for vectors and dense * matrices. Note that GSL native storage is row-major. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas_types.h> #include <gsl/gsl_blas.h> /* ======================================================================== * Level 1 * ======================================================================== */ /* CBLAS defines vector sizes in terms of int. GSL defines sizes in terms of size_t, so we need to convert these into integers. There is the possibility of overflow here. FIXME: Maybe this could be caught */ #define INT(X) ((int)(X)) int gsl_blas_sdsdot (float alpha, const gsl_vector_float * X, const gsl_vector_float * Y, float *result) { if (X->size == Y->size) { *result = cblas_sdsdot (INT (X->size), alpha, X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dsdot (const gsl_vector_float * X, const gsl_vector_float * Y, double *result) { if (X->size == Y->size) { *result = cblas_dsdot (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_sdot (const gsl_vector_float * X, const gsl_vector_float * Y, float *result) { if (X->size == Y->size) { *result = cblas_sdot (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_ddot (const gsl_vector * X, const gsl_vector * Y, double *result) { if (X->size == Y->size) { *result = cblas_ddot (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_cdotu (const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_complex_float * dotu) { if (X->size == Y->size) { cblas_cdotu_sub (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride), GSL_COMPLEX_P (dotu)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_cdotc (const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_complex_float * dotc) { if (X->size == Y->size) { cblas_cdotc_sub (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride), GSL_COMPLEX_P (dotc)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zdotu (const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_complex * dotu) { if (X->size == Y->size) { cblas_zdotu_sub (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride), GSL_COMPLEX_P (dotu)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zdotc (const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_complex * dotc) { if (X->size == Y->size) { cblas_zdotc_sub (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride), GSL_COMPLEX_P (dotc)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* Norms of vectors */ float gsl_blas_snrm2 (const gsl_vector_float * X) { return cblas_snrm2 (INT (X->size), X->data, INT (X->stride)); } double gsl_blas_dnrm2 (const gsl_vector * X) { return cblas_dnrm2 (INT (X->size), X->data, INT (X->stride)); } float gsl_blas_scnrm2 (const gsl_vector_complex_float * X) { return cblas_scnrm2 (INT (X->size), X->data, INT (X->stride)); } double gsl_blas_dznrm2 (const gsl_vector_complex * X) { return cblas_dznrm2 (INT (X->size), X->data, INT (X->stride)); } /* Absolute sums of vectors */ float gsl_blas_sasum (const gsl_vector_float * X) { return cblas_sasum (INT (X->size), X->data, INT (X->stride)); } double gsl_blas_dasum (const gsl_vector * X) { return cblas_dasum (INT (X->size), X->data, INT (X->stride)); } float gsl_blas_scasum (const gsl_vector_complex_float * X) { return cblas_scasum (INT (X->size), X->data, INT (X->stride)); } double gsl_blas_dzasum (const gsl_vector_complex * X) { return cblas_dzasum (INT (X->size), X->data, INT (X->stride)); } /* Maximum elements of vectors */ CBLAS_INDEX_t gsl_blas_isamax (const gsl_vector_float * X) { return cblas_isamax (INT (X->size), X->data, INT (X->stride)); } CBLAS_INDEX_t gsl_blas_idamax (const gsl_vector * X) { return cblas_idamax (INT (X->size), X->data, INT (X->stride)); } CBLAS_INDEX_t gsl_blas_icamax (const gsl_vector_complex_float * X) { return cblas_icamax (INT (X->size), X->data, INT (X->stride)); } CBLAS_INDEX_t gsl_blas_izamax (const gsl_vector_complex * X) { return cblas_izamax (INT (X->size), X->data, INT (X->stride)); } /* Swap vectors */ int gsl_blas_sswap (gsl_vector_float * X, gsl_vector_float * Y) { if (X->size == Y->size) { cblas_sswap (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dswap (gsl_vector * X, gsl_vector * Y) { if (X->size == Y->size) { cblas_dswap (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); }; } int gsl_blas_cswap (gsl_vector_complex_float * X, gsl_vector_complex_float * Y) { if (X->size == Y->size) { cblas_cswap (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zswap (gsl_vector_complex * X, gsl_vector_complex * Y) { if (X->size == Y->size) { cblas_zswap (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* Copy vectors */ int gsl_blas_scopy (const gsl_vector_float * X, gsl_vector_float * Y) { if (X->size == Y->size) { cblas_scopy (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dcopy (const gsl_vector * X, gsl_vector * Y) { if (X->size == Y->size) { cblas_dcopy (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_ccopy (const gsl_vector_complex_float * X, gsl_vector_complex_float * Y) { if (X->size == Y->size) { cblas_ccopy (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zcopy (const gsl_vector_complex * X, gsl_vector_complex * Y) { if (X->size == Y->size) { cblas_zcopy (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* Compute Y = alpha X + Y */ int gsl_blas_saxpy (float alpha, const gsl_vector_float * X, gsl_vector_float * Y) { if (X->size == Y->size) { cblas_saxpy (INT (X->size), alpha, X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_daxpy (double alpha, const gsl_vector * X, gsl_vector * Y) { if (X->size == Y->size) { cblas_daxpy (INT (X->size), alpha, X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_caxpy (const gsl_complex_float alpha, const gsl_vector_complex_float * X, gsl_vector_complex_float * Y) { if (X->size == Y->size) { cblas_caxpy (INT (X->size), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zaxpy (const gsl_complex alpha, const gsl_vector_complex * X, gsl_vector_complex * Y) { if (X->size == Y->size) { cblas_zaxpy (INT (X->size), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* Generate rotation */ int gsl_blas_srotg (float a[], float b[], float c[], float s[]) { cblas_srotg (a, b, c, s); return GSL_SUCCESS; } int gsl_blas_drotg (double a[], double b[], double c[], double s[]) { cblas_drotg (a, b, c, s); return GSL_SUCCESS; } /* Apply rotation to vectors */ int gsl_blas_srot (gsl_vector_float * X, gsl_vector_float * Y, float c, float s) { if (X->size == Y->size) { cblas_srot (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride), c, s); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_drot (gsl_vector * X, gsl_vector * Y, const double c, const double s) { if (X->size == Y->size) { cblas_drot (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride), c, s); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* Generate modified rotation */ int gsl_blas_srotmg (float d1[], float d2[], float b1[], float b2, float P[]) { cblas_srotmg (d1, d2, b1, b2, P); return GSL_SUCCESS; } int gsl_blas_drotmg (double d1[], double d2[], double b1[], double b2, double P[]) { cblas_drotmg (d1, d2, b1, b2, P); return GSL_SUCCESS; } /* Apply modified rotation */ int gsl_blas_srotm (gsl_vector_float * X, gsl_vector_float * Y, const float P[]) { if (X->size == Y->size) { cblas_srotm (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride), P); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_drotm (gsl_vector * X, gsl_vector * Y, const double P[]) { if (X->size == Y->size) { cblas_drotm (INT (X->size), X->data, INT (X->stride), Y->data, INT (Y->stride), P); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* Scale vector */ void gsl_blas_sscal (float alpha, gsl_vector_float * X) { cblas_sscal (INT (X->size), alpha, X->data, INT (X->stride)); } void gsl_blas_dscal (double alpha, gsl_vector * X) { cblas_dscal (INT (X->size), alpha, X->data, INT (X->stride)); } void gsl_blas_cscal (const gsl_complex_float alpha, gsl_vector_complex_float * X) { cblas_cscal (INT (X->size), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride)); } void gsl_blas_zscal (const gsl_complex alpha, gsl_vector_complex * X) { cblas_zscal (INT (X->size), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride)); } void gsl_blas_csscal (float alpha, gsl_vector_complex_float * X) { cblas_csscal (INT (X->size), alpha, X->data, INT (X->stride)); } void gsl_blas_zdscal (double alpha, gsl_vector_complex * X) { cblas_zdscal (INT (X->size), alpha, X->data, INT (X->stride)); } /* =========================================================================== * Level 2 * =========================================================================== */ /* GEMV */ int gsl_blas_sgemv (CBLAS_TRANSPOSE_t TransA, float alpha, const gsl_matrix_float * A, const gsl_vector_float * X, float beta, gsl_vector_float * Y) { const size_t M = A->size1; const size_t N = A->size2; if ((TransA == CblasNoTrans && N == X->size && M == Y->size) || (TransA == CblasTrans && M == X->size && N == Y->size)) { cblas_sgemv (CblasRowMajor, TransA, INT (M), INT (N), alpha, A->data, INT (A->tda), X->data, INT (X->stride), beta, Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA, double alpha, const gsl_matrix * A, const gsl_vector * X, double beta, gsl_vector * Y) { const size_t M = A->size1; const size_t N = A->size2; if ((TransA == CblasNoTrans && N == X->size && M == Y->size) || (TransA == CblasTrans && M == X->size && N == Y->size)) { cblas_dgemv (CblasRowMajor, TransA, INT (M), INT (N), alpha, A->data, INT (A->tda), X->data, INT (X->stride), beta, Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_cgemv (CBLAS_TRANSPOSE_t TransA, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_vector_complex_float * X, const gsl_complex_float beta, gsl_vector_complex_float * Y) { const size_t M = A->size1; const size_t N = A->size2; if ((TransA == CblasNoTrans && N == X->size && M == Y->size) || (TransA == CblasTrans && M == X->size && N == Y->size) || (TransA == CblasConjTrans && M == X->size && N == Y->size)) { cblas_cgemv (CblasRowMajor, TransA, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), X->data, INT (X->stride), GSL_COMPLEX_P (&beta), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zgemv (CBLAS_TRANSPOSE_t TransA, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_vector_complex * X, const gsl_complex beta, gsl_vector_complex * Y) { const size_t M = A->size1; const size_t N = A->size2; if ((TransA == CblasNoTrans && N == X->size && M == Y->size) || (TransA == CblasTrans && M == X->size && N == Y->size) || (TransA == CblasConjTrans && M == X->size && N == Y->size)) { cblas_zgemv (CblasRowMajor, TransA, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), X->data, INT (X->stride), GSL_COMPLEX_P (&beta), Y->data, INT (Y->stride)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* HEMV */ int gsl_blas_chemv (CBLAS_UPLO_t Uplo, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_vector_complex_float * X, const gsl_complex_float beta, gsl_vector_complex_float * Y) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size || N != Y->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_chemv (CblasRowMajor, Uplo, INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), X->data, INT (X->stride), GSL_COMPLEX_P (&beta), Y->data, INT (Y->stride)); return GSL_SUCCESS; } int gsl_blas_zhemv (CBLAS_UPLO_t Uplo, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_vector_complex * X, const gsl_complex beta, gsl_vector_complex * Y) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size || N != Y->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_zhemv (CblasRowMajor, Uplo, INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), X->data, INT (X->stride), GSL_COMPLEX_P (&beta), Y->data, INT (Y->stride)); return GSL_SUCCESS; } /* SYMV */ int gsl_blas_ssymv (CBLAS_UPLO_t Uplo, float alpha, const gsl_matrix_float * A, const gsl_vector_float * X, float beta, gsl_vector_float * Y) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size || N != Y->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ssymv (CblasRowMajor, Uplo, INT (N), alpha, A->data, INT (A->tda), X->data, INT (X->stride), beta, Y->data, INT (Y->stride)); return GSL_SUCCESS; } int gsl_blas_dsymv (CBLAS_UPLO_t Uplo, double alpha, const gsl_matrix * A, const gsl_vector * X, double beta, gsl_vector * Y) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size || N != Y->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_dsymv (CblasRowMajor, Uplo, INT (N), alpha, A->data, INT (A->tda), X->data, INT (X->stride), beta, Y->data, INT (Y->stride)); return GSL_SUCCESS; } /* TRMV */ int gsl_blas_strmv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_float * A, gsl_vector_float * X) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_strmv (CblasRowMajor, Uplo, TransA, Diag, INT (N), A->data, INT (A->tda), X->data, INT (X->stride)); return GSL_SUCCESS; } int gsl_blas_dtrmv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix * A, gsl_vector * X) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_dtrmv (CblasRowMajor, Uplo, TransA, Diag, INT (N), A->data, INT (A->tda), X->data, INT (X->stride)); return GSL_SUCCESS; } int gsl_blas_ctrmv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_complex_float * A, gsl_vector_complex_float * X) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ctrmv (CblasRowMajor, Uplo, TransA, Diag, INT (N), A->data, INT (A->tda), X->data, INT (X->stride)); return GSL_SUCCESS; } int gsl_blas_ztrmv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_complex * A, gsl_vector_complex * X) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ztrmv (CblasRowMajor, Uplo, TransA, Diag, INT (N), A->data, INT (A->tda), X->data, INT (X->stride)); return GSL_SUCCESS; } /* TRSV */ int gsl_blas_strsv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_float * A, gsl_vector_float * X) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_strsv (CblasRowMajor, Uplo, TransA, Diag, INT (N), A->data, INT (A->tda), X->data, INT (X->stride)); return GSL_SUCCESS; } int gsl_blas_dtrsv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix * A, gsl_vector * X) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_dtrsv (CblasRowMajor, Uplo, TransA, Diag, INT (N), A->data, INT (A->tda), X->data, INT (X->stride)); return GSL_SUCCESS; } int gsl_blas_ctrsv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_complex_float * A, gsl_vector_complex_float * X) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ctrsv (CblasRowMajor, Uplo, TransA, Diag, INT (N), A->data, INT (A->tda), X->data, INT (X->stride)); return GSL_SUCCESS; } int gsl_blas_ztrsv (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_matrix_complex * A, gsl_vector_complex * X) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N != X->size) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ztrsv (CblasRowMajor, Uplo, TransA, Diag, INT (N), A->data, INT (A->tda), X->data, INT (X->stride)); return GSL_SUCCESS; } /* GER */ int gsl_blas_sger (float alpha, const gsl_vector_float * X, const gsl_vector_float * Y, gsl_matrix_float * A) { const size_t M = A->size1; const size_t N = A->size2; if (X->size == M && Y->size == N) { cblas_sger (CblasRowMajor, INT (M), INT (N), alpha, X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dger (double alpha, const gsl_vector * X, const gsl_vector * Y, gsl_matrix * A) { const size_t M = A->size1; const size_t N = A->size2; if (X->size == M && Y->size == N) { cblas_dger (CblasRowMajor, INT (M), INT (N), alpha, X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* GERU */ int gsl_blas_cgeru (const gsl_complex_float alpha, const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_matrix_complex_float * A) { const size_t M = A->size1; const size_t N = A->size2; if (X->size == M && Y->size == N) { cblas_cgeru (CblasRowMajor, INT (M), INT (N), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zgeru (const gsl_complex alpha, const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_matrix_complex * A) { const size_t M = A->size1; const size_t N = A->size2; if (X->size == M && Y->size == N) { cblas_zgeru (CblasRowMajor, INT (M), INT (N), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* GERC */ int gsl_blas_cgerc (const gsl_complex_float alpha, const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_matrix_complex_float * A) { const size_t M = A->size1; const size_t N = A->size2; if (X->size == M && Y->size == N) { cblas_cgerc (CblasRowMajor, INT (M), INT (N), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zgerc (const gsl_complex alpha, const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_matrix_complex * A) { const size_t M = A->size1; const size_t N = A->size2; if (X->size == M && Y->size == N) { cblas_zgerc (CblasRowMajor, INT (M), INT (N), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* HER */ int gsl_blas_cher (CBLAS_UPLO_t Uplo, float alpha, const gsl_vector_complex_float * X, gsl_matrix_complex_float * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (X->size != N) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_cher (CblasRowMajor, Uplo, INT (M), alpha, X->data, INT (X->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } int gsl_blas_zher (CBLAS_UPLO_t Uplo, double alpha, const gsl_vector_complex * X, gsl_matrix_complex * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (X->size != N) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_zher (CblasRowMajor, Uplo, INT (N), alpha, X->data, INT (X->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } /* HER2 */ int gsl_blas_cher2 (CBLAS_UPLO_t Uplo, const gsl_complex_float alpha, const gsl_vector_complex_float * X, const gsl_vector_complex_float * Y, gsl_matrix_complex_float * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (X->size != N || Y->size != N) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_cher2 (CblasRowMajor, Uplo, INT (N), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } int gsl_blas_zher2 (CBLAS_UPLO_t Uplo, const gsl_complex alpha, const gsl_vector_complex * X, const gsl_vector_complex * Y, gsl_matrix_complex * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (X->size != N || Y->size != N) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_zher2 (CblasRowMajor, Uplo, INT (N), GSL_COMPLEX_P (&alpha), X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } /* SYR */ int gsl_blas_ssyr (CBLAS_UPLO_t Uplo, float alpha, const gsl_vector_float * X, gsl_matrix_float * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (X->size != N) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ssyr (CblasRowMajor, Uplo, INT (N), alpha, X->data, INT (X->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } int gsl_blas_dsyr (CBLAS_UPLO_t Uplo, double alpha, const gsl_vector * X, gsl_matrix * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (X->size != N) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_dsyr (CblasRowMajor, Uplo, INT (N), alpha, X->data, INT (X->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } /* SYR2 */ int gsl_blas_ssyr2 (CBLAS_UPLO_t Uplo, float alpha, const gsl_vector_float * X, const gsl_vector_float * Y, gsl_matrix_float * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (X->size != N || Y->size != N) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ssyr2 (CblasRowMajor, Uplo, INT (N), alpha, X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } int gsl_blas_dsyr2 (CBLAS_UPLO_t Uplo, double alpha, const gsl_vector * X, const gsl_vector * Y, gsl_matrix * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (X->size != N || Y->size != N) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_dsyr2 (CblasRowMajor, Uplo, INT (N), alpha, X->data, INT (X->stride), Y->data, INT (Y->stride), A->data, INT (A->tda)); return GSL_SUCCESS; } /* * =========================================================================== * Prototypes for level 3 BLAS * =========================================================================== */ /* GEMM */ int gsl_blas_sgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, float alpha, const gsl_matrix_float * A, const gsl_matrix_float * B, float beta, gsl_matrix_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (TransA == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (TransA == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (TransB == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (TransB == CblasNoTrans) ? B->size2 : B->size1; if (M == MA && N == NB && NA == MB) /* [MxN] = [MAxNA][MBxNB] */ { cblas_sgemm (CblasRowMajor, TransA, TransB, INT (M), INT (N), INT (NA), alpha, A->data, INT (A->tda), B->data, INT (B->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (TransA == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (TransA == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (TransB == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (TransB == CblasNoTrans) ? B->size2 : B->size1; if (M == MA && N == NB && NA == MB) /* [MxN] = [MAxNA][MBxNB] */ { cblas_dgemm (CblasRowMajor, TransA, TransB, INT (M), INT (N), INT (NA), alpha, A->data, INT (A->tda), B->data, INT (B->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_cgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, const gsl_complex_float beta, gsl_matrix_complex_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (TransA == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (TransA == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (TransB == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (TransB == CblasNoTrans) ? B->size2 : B->size1; if (M == MA && N == NB && NA == MB) /* [MxN] = [MAxNA][MBxNB] */ { cblas_cgemm (CblasRowMajor, TransA, TransB, INT (M), INT (N), INT (NA), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, const gsl_complex beta, gsl_matrix_complex * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (TransA == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (TransA == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (TransB == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (TransB == CblasNoTrans) ? B->size2 : B->size1; if (M == MA && N == NB && NA == MB) /* [MxN] = [MAxNA][MBxNB] */ { cblas_zgemm (CblasRowMajor, TransA, TransB, INT (M), INT (N), INT (NA), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* SYMM */ int gsl_blas_ssymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, float alpha, const gsl_matrix_float * A, const gsl_matrix_float * B, float beta, gsl_matrix_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = A->size1; const size_t NA = A->size2; const size_t MB = B->size1; const size_t NB = B->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && (M == MA && N == NB && NA == MB)) || (Side == CblasRight && (M == MB && N == NA && NB == MA))) { cblas_ssymm (CblasRowMajor, Side, Uplo, INT (M), INT (N), alpha, A->data, INT (A->tda), B->data, INT (B->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dsymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = A->size1; const size_t NA = A->size2; const size_t MB = B->size1; const size_t NB = B->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && (M == MA && N == NB && NA == MB)) || (Side == CblasRight && (M == MB && N == NA && NB == MA))) { cblas_dsymm (CblasRowMajor, Side, Uplo, INT (M), INT (N), alpha, A->data, INT (A->tda), B->data, INT (B->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_csymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, const gsl_complex_float beta, gsl_matrix_complex_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = A->size1; const size_t NA = A->size2; const size_t MB = B->size1; const size_t NB = B->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && (M == MA && N == NB && NA == MB)) || (Side == CblasRight && (M == MB && N == NA && NB == MA))) { cblas_csymm (CblasRowMajor, Side, Uplo, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zsymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, const gsl_complex beta, gsl_matrix_complex * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = A->size1; const size_t NA = A->size2; const size_t MB = B->size1; const size_t NB = B->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && (M == MA && N == NB && NA == MB)) || (Side == CblasRight && (M == MB && N == NA && NB == MA))) { cblas_zsymm (CblasRowMajor, Side, Uplo, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* HEMM */ int gsl_blas_chemm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, const gsl_complex_float beta, gsl_matrix_complex_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = A->size1; const size_t NA = A->size2; const size_t MB = B->size1; const size_t NB = B->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && (M == MA && N == NB && NA == MB)) || (Side == CblasRight && (M == MB && N == NA && NB == MA))) { cblas_chemm (CblasRowMajor, Side, Uplo, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_zhemm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, const gsl_complex beta, gsl_matrix_complex * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = A->size1; const size_t NA = A->size2; const size_t MB = B->size1; const size_t NB = B->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && (M == MA && N == NB && NA == MB)) || (Side == CblasRight && (M == MB && N == NA && NB == MA))) { cblas_zhemm (CblasRowMajor, Side, Uplo, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* SYRK */ int gsl_blas_ssyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha, const gsl_matrix_float * A, float beta, gsl_matrix_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t J = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t K = (Trans == CblasNoTrans) ? A->size2 : A->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != J) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ssyrk (CblasRowMajor, Uplo, Trans, INT (N), INT (K), alpha, A->data, INT (A->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } int gsl_blas_dsyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, double alpha, const gsl_matrix * A, double beta, gsl_matrix * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t J = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t K = (Trans == CblasNoTrans) ? A->size2 : A->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != J) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_dsyrk (CblasRowMajor, Uplo, Trans, INT (N), INT (K), alpha, A->data, INT (A->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } int gsl_blas_csyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_complex_float beta, gsl_matrix_complex_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t J = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t K = (Trans == CblasNoTrans) ? A->size2 : A->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != J) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_csyrk (CblasRowMajor, Uplo, Trans, INT (N), INT (K), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } int gsl_blas_zsyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_complex beta, gsl_matrix_complex * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t J = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t K = (Trans == CblasNoTrans) ? A->size2 : A->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != J) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_zsyrk (CblasRowMajor, Uplo, Trans, INT (N), INT (K), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } /* HERK */ int gsl_blas_cherk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha, const gsl_matrix_complex_float * A, float beta, gsl_matrix_complex_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t J = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t K = (Trans == CblasNoTrans) ? A->size2 : A->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != J) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_cherk (CblasRowMajor, Uplo, Trans, INT (N), INT (K), alpha, A->data, INT (A->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } int gsl_blas_zherk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, double alpha, const gsl_matrix_complex * A, double beta, gsl_matrix_complex * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t J = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t K = (Trans == CblasNoTrans) ? A->size2 : A->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != J) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_zherk (CblasRowMajor, Uplo, Trans, INT (N), INT (K), alpha, A->data, INT (A->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } /* SYR2K */ int gsl_blas_ssyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha, const gsl_matrix_float * A, const gsl_matrix_float * B, float beta, gsl_matrix_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (Trans == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (Trans == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (Trans == CblasNoTrans) ? B->size2 : B->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != MA || N != MB || NA != NB) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_ssyr2k (CblasRowMajor, Uplo, Trans, INT (N), INT (NA), alpha, A->data, INT (A->tda), B->data, INT (B->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } int gsl_blas_dsyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (Trans == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (Trans == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (Trans == CblasNoTrans) ? B->size2 : B->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != MA || N != MB || NA != NB) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_dsyr2k (CblasRowMajor, Uplo, Trans, INT (N), INT (NA), alpha, A->data, INT (A->tda), B->data, INT (B->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } int gsl_blas_csyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, const gsl_complex_float beta, gsl_matrix_complex_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (Trans == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (Trans == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (Trans == CblasNoTrans) ? B->size2 : B->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != MA || N != MB || NA != NB) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_csyr2k (CblasRowMajor, Uplo, Trans, INT (N), INT (NA), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } int gsl_blas_zsyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, const gsl_complex beta, gsl_matrix_complex * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (Trans == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (Trans == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (Trans == CblasNoTrans) ? B->size2 : B->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != MA || N != MB || NA != NB) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_zsyr2k (CblasRowMajor, Uplo, Trans, INT (N), INT (NA), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), GSL_COMPLEX_P (&beta), C->data, INT (C->tda)); return GSL_SUCCESS; } /* HER2K */ int gsl_blas_cher2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, const gsl_matrix_complex_float * B, float beta, gsl_matrix_complex_float * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (Trans == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (Trans == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (Trans == CblasNoTrans) ? B->size2 : B->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != MA || N != MB || NA != NB) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_cher2k (CblasRowMajor, Uplo, Trans, INT (N), INT (NA), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } int gsl_blas_zher2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, const gsl_complex alpha, const gsl_matrix_complex * A, const gsl_matrix_complex * B, double beta, gsl_matrix_complex * C) { const size_t M = C->size1; const size_t N = C->size2; const size_t MA = (Trans == CblasNoTrans) ? A->size1 : A->size2; const size_t NA = (Trans == CblasNoTrans) ? A->size2 : A->size1; const size_t MB = (Trans == CblasNoTrans) ? B->size1 : B->size2; const size_t NB = (Trans == CblasNoTrans) ? B->size2 : B->size1; if (M != N) { GSL_ERROR ("matrix C must be square", GSL_ENOTSQR); } else if (N != MA || N != MB || NA != NB) { GSL_ERROR ("invalid length", GSL_EBADLEN); } cblas_zher2k (CblasRowMajor, Uplo, Trans, INT (N), INT (NA), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda), beta, C->data, INT (C->tda)); return GSL_SUCCESS; } /* TRMM */ int gsl_blas_strmm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, float alpha, const gsl_matrix_float * A, gsl_matrix_float * B) { const size_t M = B->size1; const size_t N = B->size2; const size_t MA = A->size1; const size_t NA = A->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && M == MA) || (Side == CblasRight && N == MA)) { cblas_strmm (CblasRowMajor, Side, Uplo, TransA, Diag, INT (M), INT (N), alpha, A->data, INT (A->tda), B->data, INT (B->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dtrmm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, double alpha, const gsl_matrix * A, gsl_matrix * B) { const size_t M = B->size1; const size_t N = B->size2; const size_t MA = A->size1; const size_t NA = A->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && M == MA) || (Side == CblasRight && N == MA)) { cblas_dtrmm (CblasRowMajor, Side, Uplo, TransA, Diag, INT (M), INT (N), alpha, A->data, INT (A->tda), B->data, INT (B->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_ctrmm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, gsl_matrix_complex_float * B) { const size_t M = B->size1; const size_t N = B->size2; const size_t MA = A->size1; const size_t NA = A->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && M == MA) || (Side == CblasRight && N == MA)) { cblas_ctrmm (CblasRowMajor, Side, Uplo, TransA, Diag, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_ztrmm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_complex alpha, const gsl_matrix_complex * A, gsl_matrix_complex * B) { const size_t M = B->size1; const size_t N = B->size2; const size_t MA = A->size1; const size_t NA = A->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && M == MA) || (Side == CblasRight && N == MA)) { cblas_ztrmm (CblasRowMajor, Side, Uplo, TransA, Diag, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } /* TRSM */ int gsl_blas_strsm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, float alpha, const gsl_matrix_float * A, gsl_matrix_float * B) { const size_t M = B->size1; const size_t N = B->size2; const size_t MA = A->size1; const size_t NA = A->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && M == MA) || (Side == CblasRight && N == MA)) { cblas_strsm (CblasRowMajor, Side, Uplo, TransA, Diag, INT (M), INT (N), alpha, A->data, INT (A->tda), B->data, INT (B->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_dtrsm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, double alpha, const gsl_matrix * A, gsl_matrix * B) { const size_t M = B->size1; const size_t N = B->size2; const size_t MA = A->size1; const size_t NA = A->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && M == MA) || (Side == CblasRight && N == MA)) { cblas_dtrsm (CblasRowMajor, Side, Uplo, TransA, Diag, INT (M), INT (N), alpha, A->data, INT (A->tda), B->data, INT (B->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_ctrsm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_complex_float alpha, const gsl_matrix_complex_float * A, gsl_matrix_complex_float * B) { const size_t M = B->size1; const size_t N = B->size2; const size_t MA = A->size1; const size_t NA = A->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && M == MA) || (Side == CblasRight && N == MA)) { cblas_ctrsm (CblasRowMajor, Side, Uplo, TransA, Diag, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } } int gsl_blas_ztrsm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, const gsl_complex alpha, const gsl_matrix_complex * A, gsl_matrix_complex * B) { const size_t M = B->size1; const size_t N = B->size2; const size_t MA = A->size1; const size_t NA = A->size2; if (MA != NA) { GSL_ERROR ("matrix A must be square", GSL_ENOTSQR); } if ((Side == CblasLeft && M == MA) || (Side == CblasRight && N == MA)) { cblas_ztrsm (CblasRowMajor, Side, Uplo, TransA, Diag, INT (M), INT (N), GSL_COMPLEX_P (&alpha), A->data, INT (A->tda), B->data, INT (B->tda)); return GSL_SUCCESS; } else { GSL_ERROR ("invalid length", GSL_EBADLEN); } }
{ "alphanum_fraction": 0.5694730234, "avg_line_length": 26.1734367869, "ext": "c", "hexsha": "9ef62a6d768e1dd9fb65158a5560b5234d75e383", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/blas/blas.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/blas/blas.c", "max_line_length": 81, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/blas/blas.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 17830, "size": 57346 }
/* convolvedexponential.c -- model functions for multiple exponentials + background, convolved with an instrument response */ ///////////////////////////////////////////////////////////////////////////////// // // Calculation of multiple exponentials convolved with an instrument response. // using GNU Scientific Library. Also, calls Levenberg-Marquardt minimization routine // for fitting event counting histograms. Options include using the Maximum Likelihood Estimator // for Poisson deviates and least squares fitting. // // Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory. Written by Ted Laurence (laurence2@llnl.gov) // LLNL-CODE-424602 All rights reserved. // This file is part of dlevmar_mle_der // // Please also read Our Notice and GNU General Public License. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ///////////////////////////////////////////////////////////////////////////////// #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_fft_halfcomplex.h> #include <gsl/gsl_vector.h> #include "levmar_mle.h" struct data { double deltaT; /*Spacing between bins*/ size_t n; /*Number of data elements*/ size_t nRadix2; /*Next higher power of 2 for n, giving size of irf and fWork arrays*/ double *irfWork;/*Instrument Response Function*/ double *fWork; /*Workspace for function calculation*/ size_t m_total; /*Number of parameters (number of exponentials = (m-1)/2 ) */ double *a; /*Parameter Array; fitted parameters x are subsituted into this array */ size_t m; /*Number of fitted parameters*/ int *ip; /*Mapping of fitted parameter array x to parameter array a*/ }; void complex_convolution_multiply(double *a, const double *b, int n) { int i,j; double re,im,factor; factor = 1.0/n; /* to normalize inverse FFT */ a[0]*=b[0]*factor; a[n/2]*=b[n/2]*factor; for (i=1;i<n/2;i++) { j=n-i; re=a[i]; im=a[j]; a[i]=(re*b[i]-im*b[j])*factor; a[j]=(im*b[i]+re*b[j])*factor; } } void convolved_exp_f(double *p, double *f, int m, int n, void *data) { double deltaT=((struct data *)data)->deltaT; size_t nRadix2 = ((struct data *)data)->nRadix2; double *irfWork = ((struct data *) data)->irfWork; double *fWork = ((struct data *) data)->fWork; size_t m_total = ((struct data *)data)->m_total; double *a = ((struct data *) data)->a; int *ip = ((struct data *) data)->ip; int i,j; int numExponentials = (m_total-1)/2; double tau, amp, sqrtTau,sqrtAmp; double constantValue; double totalT=deltaT*n; double factor1; double factor2; if ( (n != ((struct data *)data)->n ) || (m != ((struct data *)data)->m) ) return; for (i=0; i<m; i++) a[ ip[i] ] = p[i]; constantValue=a[0]*a[0]/n; for (i=0; i<n; i++) fWork[i] = constantValue; for (i=n; i<nRadix2; i++) fWork[i] = 0.0; for (j=0;j<numExponentials;j++) { sqrtAmp=a[2*j+1]; sqrtTau=a[2*j+2]; amp=sqrtAmp*sqrtAmp; tau=sqrtTau*sqrtTau; factor1=1-exp(-deltaT/tau); factor2=1-exp(-totalT/tau); for (i=0;i<n;i++) fWork[i]+=amp*factor1/factor2*exp(-deltaT*i/tau); } gsl_fft_real_radix2_transform(fWork,1,nRadix2); complex_convolution_multiply(fWork,irfWork,nRadix2); gsl_fft_halfcomplex_radix2_backward(fWork,1,nRadix2); // This loop uses 0 offset indexing for (i=n;i<nRadix2;i++) fWork[i%n]+=fWork[i]; for (i=0;i<n;i++) f[i]=fWork[i]; return; } void convolved_exp_df(double *p, double *jac, int m, int n, void *data) { double deltaT=((struct data *)data)->deltaT; size_t nRadix2 = ((struct data *)data)->nRadix2; double *irfWork = ((struct data *) data)->irfWork; double *fWork = ((struct data *) data)->fWork; size_t m_total = ((struct data *)data)->m_total; double *a = ((struct data *) data)->a; int *ip = ((struct data *) data)->ip; double *jac_row; int i,k; if ( (n != ((struct data *)data)->n ) || (m != ((struct data *)data)->m) ) return; for (k=0; k<m; k++) { double tau, amp, sqrtTau,sqrtAmp; double temp, totalT=deltaT*n; double factor1; double factor2; if (ip[k]==0) { double d_constant=2*a[0]/n; jac_row=jac; for (i=0;i<n;i++,jac_row+=m) jac_row[k]=d_constant; continue; } for (i=0; i<nRadix2; i++) fWork[i] = 0.0; if ((ip[k]-1)%2==0) /* Amplitude */ { sqrtAmp=a[ip[k]]; sqrtTau=a[ip[k]+1]; amp=sqrtAmp*sqrtAmp; tau=sqrtTau*sqrtTau; factor1=1-exp(-deltaT/tau); factor2=1-exp(-totalT/tau); for (i=0;i<n;i++) fWork[i]=2*sqrtAmp*factor1/factor2*exp(-deltaT*i/tau); } else /* lifetime */ { sqrtAmp=a[ip[k]-1]; sqrtTau=a[ip[k]]; amp=sqrtAmp*sqrtAmp; tau=sqrtTau*sqrtTau; factor1=1-exp(-deltaT/tau); factor2=1-exp(-totalT/tau); for (i=0;i<n;i++) { temp=factor1/factor2*exp(-deltaT*i/tau); fWork[i]= -2*amp*deltaT*exp(-(deltaT*i+deltaT)/tau)/(factor2*tau*sqrtTau) +2*temp*amp*deltaT*i/(tau*sqrtTau) +2*temp*amp*totalT*exp(-totalT/tau)/(factor2*tau*sqrtTau); } } gsl_fft_real_radix2_transform(fWork,1,nRadix2); complex_convolution_multiply(fWork,irfWork,nRadix2); gsl_fft_halfcomplex_radix2_backward(fWork,1,nRadix2); // This loop uses 0 offset indexing for (i=n;i<nRadix2;i++) fWork[i%n]+=fWork[i]; jac_row=jac; for (i=0;i<n;i++,jac_row+=m) jac_row[k]=fWork[i]; } return; } int fit_convolved_exponential(int n, // number of measurement bins double deltaT, // time resolution for each bin double *x, // Data Measured double *f, // Space for function double *irf, // Instrument Response int m_total, // Total number of parameters (including those not fitted) double *a, // Parameter array (length m_total) int m, // Number of fitted parameters int *ip, // Array of length m with indices of fitted parameters in a double *chisq, // Result for chisq int *nIterations, // Number of iterations performed int fitType, // 0 = MLE, 1 = Neyman weighting, 2 = Equal Weighting (sigma=1) double deltaChisqLimit, // Stop criterion for change in chisq int maxIterations) // maximum number of iterations { struct data importedData; double tempN,nRadix2; double *irfWork, *fWork; double opts[LM_OPTS_SZ],info[LM_INFO_SZ]; int i; int status; unsigned iter = 0; double *p; opts[0]=LM_INIT_MU; opts[1]=LM_STOP_THRESH; opts[2]=LM_STOP_THRESH; opts[3]=LM_STOP_THRESH; opts[4]=deltaChisqLimit; importedData.n=n; importedData.deltaT=deltaT; importedData.m_total=m_total; importedData.a=a; importedData.m=m; importedData.ip=ip; for (i=0; i<m_total; i++) a[i]=sqrt(a[i]); /* Determine power of 2 higher than n required for performing convolutions via FFT */ tempN = pow(2, 1.0+ceil( log((double)n)/log(2.0) ) ); nRadix2 = ( (int) tempN ); irfWork=malloc(nRadix2*sizeof(double)); if (irfWork==NULL) return GSL_ENOMEM; fWork=malloc(nRadix2*sizeof(double)); if (fWork==NULL) { free(irfWork); return GSL_ENOMEM; } p=malloc(m*sizeof(double)); if (p==NULL) { free(irfWork); free(fWork); return GSL_ENOMEM; } for (i=0; i<n; i++) irfWork[i]=irf[i]; for (i=n; i<nRadix2; i++) irfWork[i]=0.0; gsl_fft_real_radix2_transform(irfWork,1,nRadix2); importedData.nRadix2=nRadix2; importedData.irfWork=irfWork; importedData.fWork=fWork; for (i=0; i<m; i++) p[i]=a[ip[i]]; status = dlevmar_mle_der( &convolved_exp_f, &convolved_exp_df, p, x, m, n, maxIterations,opts,info,NULL,NULL,&importedData,fitType); *chisq = info[1]/(n-m); *nIterations=info[5]; convolved_exp_f(p, f, m, n, &importedData); /* Evaluate function for external use in array f */ for (i=0; i<m; i++) a[ip[i]]=p[i]; free(p); free(fWork); free(irfWork); for (i=0; i<m_total; i++) a[i]=a[i]*a[i]; return info[6]; }
{ "alphanum_fraction": 0.6547338672, "avg_line_length": 28.4966442953, "ext": "c", "hexsha": "a0640196566162c58c9396ba69b5c0eac1e7d70d", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2019-10-31T07:28:06.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-04T18:52:35.000Z", "max_forks_repo_head_hexsha": "f9f19ef5b0a00169562947c78a41c1f02e222a6a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "david-hoffman/dphtools", "max_forks_repo_path": "notebooks/nmeth0510-338-S2/convolvedexponential.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "d2156587cbeeb0433511811d49b69b2687b45fd6", "max_issues_repo_issues_event_max_datetime": "2022-02-09T06:49:58.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-18T18:15:39.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "david-hoffman/dphutils", "max_issues_repo_path": "notebooks/nmeth0510-338-S2/convolvedexponential.c", "max_line_length": 167, "max_stars_count": 2, "max_stars_repo_head_hexsha": "f9f19ef5b0a00169562947c78a41c1f02e222a6a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "david-hoffman/dphtools", "max_stars_repo_path": "notebooks/nmeth0510-338-S2/convolvedexponential.c", "max_stars_repo_stars_event_max_datetime": "2019-10-31T03:35:35.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-15T00:04:06.000Z", "num_tokens": 2723, "size": 8492 }
/* ODE: a program to get optime Runge-Kutta and multi-steps methods. Copyright 2011-2019, Javier Burguete Tolosa. 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. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``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 Javier Burguete Tolosa 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. */ /** * \file rk_3_2.c * \brief Source file to optimize Runge-Kutta 3 steps 2nd order methods. * \author Javier Burguete Tolosa. * \copyright Copyright 2011-2019. */ #define _GNU_SOURCE #include <string.h> #include <math.h> #include <libxml/parser.h> #include <glib.h> #include <libintl.h> #include <gsl/gsl_rng.h> #include "config.h" #include "utils.h" #include "optimize.h" #include "rk.h" #include "rk_3_2.h" #define DEBUG_RK_3_2 0 ///< macro to debug. /** * Function to obtain the coefficients of a 3 steps 2nd order Runge-Kutta * method. */ int rk_tb_3_2 (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_3_2 fprintf (stderr, "rk_tb_3_2: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t3 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; b21 (tb) = r[2]; b32 (tb) = r[3]; b31 (tb) = (0.5L - b32 (tb) * t2 (tb)) / t1 (tb); if (isnan (b31 (tb))) return 0; rk_b_3 (tb); #if DEBUG_RK_3_2 rk_print_tb (optimize, "rk_tb_3_2", stderr); fprintf (stderr, "rk_tb_3_2: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 2nd order, 3rd order in * equations depending only in time, Runge-Kutta method. */ int rk_tb_3_2t (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_3_2 fprintf (stderr, "rk_tb_3_2t: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t3 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; b21 (tb) = r[2]; b32 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb))); if (isnan (b32 (tb))) return 0; b31 (tb) = (0.5L - b32 (tb) * t2 (tb)) / t1 (tb); if (isnan (b31 (tb))) return 0; rk_b_3 (tb); #if DEBUG_RK_3_2 rk_print_tb (optimize, "rk_tb_3_2t", stderr); fprintf (stderr, "rk_tb_3_2t: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 1st-2nd order Runge-Kutta * pair. */ int rk_tb_3_2p (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_3_2 fprintf (stderr, "rk_tb_3_2p: start\n"); #endif if (!rk_tb_3_2 (optimize)) return 0; tb = optimize->coefficient; e31 (tb) = 0.L; rk_e_3 (tb); #if DEBUG_RK_3_2 rk_print_e (optimize, "rk_tb_3_2p", stderr); fprintf (stderr, "rk_tb_3_2p: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 1st-2nd order, 1st-3rd order * in equations depending only in time, Runge-Kutta method. */ int rk_tb_3_2tp (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_3_2 fprintf (stderr, "rk_tb_3_2tp: start\n"); #endif if (!rk_tb_3_2t (optimize)) return 0; tb = optimize->coefficient; e31 (tb) = 0.L; rk_e_3 (tb); #if DEBUG_RK_3_2 rk_print_tb (optimize, "rk_tb_3_2tp", stderr); fprintf (stderr, "rk_tb_3_2pt: end\n"); #endif return 1; } /** * Function to calculate the objective function of a 3 steps 2nd order * Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_3_2 (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_2 fprintf (stderr, "rk_objective_tb_3_2: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_2 fprintf (stderr, "rk_objective_tb_3_2: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_2: end\n"); #endif return o; } /** * Function to calculate the objective function of a 3 steps 2nd order, 3rd * order in equations depending only in time, Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_3_2t (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_2 fprintf (stderr, "rk_objective_tb_3_2t: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_2 fprintf (stderr, "rk_objective_tb_3_2t: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_2t: end\n"); #endif return o; }
{ "alphanum_fraction": 0.6567413851, "avg_line_length": 25.547008547, "ext": "c", "hexsha": "77d8716ebfc1f0b93c4c9f7145194ae4b75ffb17", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/ode", "max_forks_repo_path": "rk_3_2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/ode", "max_issues_repo_path": "rk_3_2.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/ode", "max_stars_repo_path": "rk_3_2.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2041, "size": 5978 }
/* specfunc/ellint.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_precision.h> #include "gsl_sf_ellint.h" #include "error.h" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ inline static double locMAX3(double x, double y, double z) { double xy = GSL_MAX(x, y); return GSL_MAX(xy, z); } inline static double locMAX4(double x, double y, double z, double w) { double xy = GSL_MAX(x, y); double xyz = GSL_MAX(xy, z); return GSL_MAX(xyz, w); } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ /* based on Carlson's algorithms: [B. C. Carlson Numer. Math. 33, 1 (1979)] see also: [B.C. Carlson, Special Functions of Applied Mathematics (1977)] */ /* According to Carlson's algorithm, the errtol parameter typically effects the relative error in the following way: relative error < 16 errtol^6 / (1 - 2 errtol) errtol precision ------ ---------- 0.001 1.0e-17 0.003 2.0e-14 0.01 2.0e-11 0.03 2.0e-8 0.1 2.0e-5 */ int gsl_sf_ellint_RC_e(double x, double y, gsl_mode_t mode, gsl_sf_result * result) { const double lolim = 5.0 * GSL_DBL_MIN; const double uplim = 0.2 * GSL_DBL_MAX; const gsl_prec_t goal = GSL_MODE_PREC(mode); const double errtol = ( goal == GSL_PREC_DOUBLE ? 0.001 : 0.03 ); const double prec = gsl_prec_eps[goal]; if(x < 0.0 || y < 0.0 || x + y < lolim) { DOMAIN_ERROR(result); } else if(GSL_MAX(x, y) < uplim) { const double c1 = 1.0 / 7.0; const double c2 = 9.0 / 22.0; double xn = x; double yn = y; double mu, sn, lamda, s; while(1) { mu = (xn + yn + yn) / 3.0; sn = (yn + mu) / mu - 2.0; if (fabs(sn) < errtol) break; lamda = 2.0 * sqrt(xn) * sqrt(yn) + yn; xn = (xn + lamda) * 0.25; yn = (yn + lamda) * 0.25; } s = sn * sn * (0.3 + sn * (c1 + sn * (0.375 + sn * c2))); result->val = (1.0 + s) / sqrt(mu); result->err = prec * fabs(result->val); return GSL_SUCCESS; } else { DOMAIN_ERROR(result); } } int gsl_sf_ellint_RD_e(double x, double y, double z, gsl_mode_t mode, gsl_sf_result * result) { const gsl_prec_t goal = GSL_MODE_PREC(mode); const double errtol = ( goal == GSL_PREC_DOUBLE ? 0.001 : 0.03 ); const double prec = gsl_prec_eps[goal]; const double lolim = 2.0/pow(GSL_DBL_MAX, 2.0/3.0); const double uplim = pow(0.1*errtol/GSL_DBL_MIN, 2.0/3.0); if(GSL_MIN(x,y) < 0.0 || GSL_MIN(x+y,z) < lolim) { DOMAIN_ERROR(result); } else if(locMAX3(x,y,z) < uplim) { const double c1 = 3.0 / 14.0; const double c2 = 1.0 / 6.0; const double c3 = 9.0 / 22.0; const double c4 = 3.0 / 26.0; double xn = x; double yn = y; double zn = z; double sigma = 0.0; double power4 = 1.0; double ea, eb, ec, ed, ef, s1, s2; double mu, xndev, yndev, zndev; while(1) { double xnroot, ynroot, znroot, lamda; double epslon; mu = (xn + yn + 3.0 * zn) * 0.2; xndev = (mu - xn) / mu; yndev = (mu - yn) / mu; zndev = (mu - zn) / mu; epslon = locMAX3(fabs(xndev), fabs(yndev), fabs(zndev)); if (epslon < errtol) break; xnroot = sqrt(xn); ynroot = sqrt(yn); znroot = sqrt(zn); lamda = xnroot * (ynroot + znroot) + ynroot * znroot; sigma += power4 / (znroot * (zn + lamda)); power4 *= 0.25; xn = (xn + lamda) * 0.25; yn = (yn + lamda) * 0.25; zn = (zn + lamda) * 0.25; } ea = xndev * yndev; eb = zndev * zndev; ec = ea - eb; ed = ea - 6.0 * eb; ef = ed + ec + ec; s1 = ed * (- c1 + 0.25 * c3 * ed - 1.5 * c4 * zndev * ef); s2 = zndev * (c2 * ef + zndev * (- c3 * ec + zndev * c4 * ea)); result->val = 3.0 * sigma + power4 * (1.0 + s1 + s2) / (mu * sqrt(mu)); result->err = prec * fabs(result->val); return GSL_SUCCESS; } else { DOMAIN_ERROR(result); } } int gsl_sf_ellint_RF_e(double x, double y, double z, gsl_mode_t mode, gsl_sf_result * result) { const double lolim = 5.0 * GSL_DBL_MIN; const double uplim = 0.2 * GSL_DBL_MAX; const gsl_prec_t goal = GSL_MODE_PREC(mode); const double errtol = ( goal == GSL_PREC_DOUBLE ? 0.001 : 0.03 ); const double prec = gsl_prec_eps[goal]; if(x < 0.0 || y < 0.0 || z < 0.0) { DOMAIN_ERROR(result); } else if(x+y < lolim || x+z < lolim || y+z < lolim) { DOMAIN_ERROR(result); } else if(locMAX3(x,y,z) < uplim) { const double c1 = 1.0 / 24.0; const double c2 = 3.0 / 44.0; const double c3 = 1.0 / 14.0; double xn = x; double yn = y; double zn = z; double mu, xndev, yndev, zndev, e2, e3, s; while(1) { double epslon, lamda; double xnroot, ynroot, znroot; mu = (xn + yn + zn) / 3.0; xndev = 2.0 - (mu + xn) / mu; yndev = 2.0 - (mu + yn) / mu; zndev = 2.0 - (mu + zn) / mu; epslon = locMAX3(fabs(xndev), fabs(yndev), fabs(zndev)); if (epslon < errtol) break; xnroot = sqrt(xn); ynroot = sqrt(yn); znroot = sqrt(zn); lamda = xnroot * (ynroot + znroot) + ynroot * znroot; xn = (xn + lamda) * 0.25; yn = (yn + lamda) * 0.25; zn = (zn + lamda) * 0.25; } e2 = xndev * yndev - zndev * zndev; e3 = xndev * yndev * zndev; s = 1.0 + (c1 * e2 - 0.1 - c2 * e3) * e2 + c3 * e3; result->val = s / sqrt(mu); result->err = prec * fabs(result->val); return GSL_SUCCESS; } else { DOMAIN_ERROR(result); } } int gsl_sf_ellint_RJ_e(double x, double y, double z, double p, gsl_mode_t mode, gsl_sf_result * result) { const gsl_prec_t goal = GSL_MODE_PREC(mode); const double errtol = ( goal == GSL_PREC_DOUBLE ? 0.001 : 0.03 ); const double prec = gsl_prec_eps[goal]; const double lolim = pow(5.0 * GSL_DBL_MIN, 1.0/3.0); const double uplim = 0.3 * pow(0.2 * GSL_DBL_MAX, 1.0/3.0); if(x < 0.0 || y < 0.0 || z < 0.0) { DOMAIN_ERROR(result); } else if(x + y < lolim || x + z < lolim || y + z < lolim || p < lolim) { DOMAIN_ERROR(result); } else if(locMAX4(x,y,z,p) < uplim) { const double c1 = 3.0 / 14.0; const double c2 = 1.0 / 3.0; const double c3 = 3.0 / 22.0; const double c4 = 3.0 / 26.0; double xn = x; double yn = y; double zn = z; double pn = p; double sigma = 0.0; double power4 = 1.0; double mu, xndev, yndev, zndev, pndev; double ea, eb, ec, e2, e3, s1, s2, s3; while(1) { double xnroot, ynroot, znroot; double lamda, alfa, beta; double epslon; gsl_sf_result rcresult; int rcstatus; mu = (xn + yn + zn + pn + pn) * 0.2; xndev = (mu - xn) / mu; yndev = (mu - yn) / mu; zndev = (mu - zn) / mu; pndev = (mu - pn) / mu; epslon = locMAX4(fabs(xndev), fabs(yndev), fabs(zndev), fabs(pndev)); if(epslon < errtol) break; xnroot = sqrt(xn); ynroot = sqrt(yn); znroot = sqrt(zn); lamda = xnroot * (ynroot + znroot) + ynroot * znroot; alfa = pn * (xnroot + ynroot + znroot) + xnroot * ynroot * znroot; alfa = alfa * alfa; beta = pn * (pn + lamda) * (pn + lamda); rcstatus = gsl_sf_ellint_RC_e(alfa, beta, mode, &rcresult); if(rcstatus != GSL_SUCCESS) { result->val = 0.0; result->err = 0.0; return rcstatus; } sigma += power4 * rcresult.val; power4 *= 0.25; xn = (xn + lamda) * 0.25; yn = (yn + lamda) * 0.25; zn = (zn + lamda) * 0.25; pn = (pn + lamda) * 0.25; } ea = xndev * (yndev + zndev) + yndev * zndev; eb = xndev * yndev * zndev; ec = pndev * pndev; e2 = ea - 3.0 * ec; e3 = eb + 2.0 * pndev * (ea - ec); s1 = 1.0 + e2 * (- c1 + 0.75 * c3 * e2 - 1.5 * c4 * e3); s2 = eb * (0.5 * c2 + pndev * (- c3 - c3 + pndev * c4)); s3 = pndev * ea * (c2 - pndev * c3) - c2 * pndev * ec; result->val = 3.0 * sigma + power4 * (s1 + s2 + s3) / (mu * sqrt(mu)); result->err = prec * fabs(result->val); return GSL_SUCCESS; } else { DOMAIN_ERROR(result); } } /* [Carlson, Numer. Math. 33 (1979) 1, (4.1)] */ int gsl_sf_ellint_F_e(double phi, double k, gsl_mode_t mode, gsl_sf_result * result) { double sin_phi = sin(phi); double sin2_phi = sin_phi*sin_phi; double x = 1.0 - sin2_phi; double y = 1.0 - k*k*sin2_phi; gsl_sf_result rf; int status = gsl_sf_ellint_RF_e(x, y, 1.0, mode, &rf); result->val = sin_phi * rf.val; result->err = GSL_DBL_EPSILON * fabs(result->val) + fabs(sin_phi*rf.err); return status; } /* [Carlson, Numer. Math. 33 (1979) 1, (4.2)] */ int gsl_sf_ellint_E_e(double phi, double k, gsl_mode_t mode, gsl_sf_result * result) { const double sin_phi = sin(phi); const double sin2_phi = sin_phi * sin_phi; const double x = 1.0 - sin2_phi; const double y = 1.0 - k*k*sin2_phi; if(x < GSL_DBL_EPSILON) { return gsl_sf_ellint_Ecomp_e(k, mode, result); } else { gsl_sf_result rf; gsl_sf_result rd; const double sin3_phi = sin2_phi * sin_phi; const int rfstatus = gsl_sf_ellint_RF_e(x, y, 1.0, mode, &rf); const int rdstatus = gsl_sf_ellint_RD_e(x, y, 1.0, mode, &rd); result->val = sin_phi * rf.val - k*k/3.0 * sin3_phi * rd.val; result->err = GSL_DBL_EPSILON * fabs(sin_phi * rf.val); result->err += fabs(sin_phi*rf.err); result->err += k*k/3.0 * GSL_DBL_EPSILON * fabs(sin3_phi * rd.val); result->err += k*k/3.0 * fabs(sin3_phi*rd.err); return GSL_ERROR_SELECT_2(rfstatus, rdstatus); } } /* [Carlson, Numer. Math. 33 (1979) 1, (4.3)] */ int gsl_sf_ellint_P_e(double phi, double k, double n, gsl_mode_t mode, gsl_sf_result * result) { const double sin_phi = sin(phi); const double sin2_phi = sin_phi * sin_phi; const double sin3_phi = sin2_phi * sin_phi; const double x = 1.0 - sin2_phi; const double y = 1.0 - k*k*sin2_phi; gsl_sf_result rf; gsl_sf_result rj; const int rfstatus = gsl_sf_ellint_RF_e(x, y, 1.0, mode, &rf); const int rjstatus = gsl_sf_ellint_RJ_e(x, y, 1.0, 1.0 + n*sin2_phi, mode, &rj); result->val = sin_phi * rf.val - n/3.0*sin3_phi * rj.val; result->err = GSL_DBL_EPSILON * fabs(sin_phi * rf.val); result->err += n/3.0 * fabs(sin3_phi*rj.err); return GSL_ERROR_SELECT_2(rfstatus, rjstatus); } /* [Carlson, Numer. Math. 33 (1979) 1, (4.4)] */ int gsl_sf_ellint_D_e(double phi, double k, double n, gsl_mode_t mode, gsl_sf_result * result) { const double sin_phi = sin(phi); const double sin2_phi = sin_phi * sin_phi; const double sin3_phi = sin2_phi * sin_phi; const double x = 1.0 - sin2_phi; const double y = 1.0 - k*k*sin2_phi; gsl_sf_result rd; const int status = gsl_sf_ellint_RD_e(x, y, 1.0, mode, &rd); result->val = sin3_phi/3.0 * rd.val; result->err = GSL_DBL_EPSILON * fabs(result->val) + fabs(sin3_phi/3.0 * rd.err); return status; } /* [Carlson, Numer. Math. 33 (1979) 1, (4.5)] */ int gsl_sf_ellint_Kcomp_e(double k, gsl_mode_t mode, gsl_sf_result * result) { if(k*k >= 1.0) { DOMAIN_ERROR(result); } else if(k*k >= 1.0 - GSL_SQRT_DBL_EPSILON) { /* [Abramowitz+Stegun, 17.3.33] */ const double y = 1.0 - k*k; const double a[] = { 1.38629436112, 0.09666344259, 0.03590092383 }; const double b[] = { 0.5, 0.12498593597, 0.06880248576 }; const double ta = a[0] + y*(a[1] + y*a[2]); const double tb = -log(y) * (b[0] * y*(b[1] + y*b[2])); result->val = ta + tb; result->err = 2.0 * GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else { return gsl_sf_ellint_RF_e(0.0, 1.0 - k*k, 1.0, mode, result); } } /* [Carlson, Numer. Math. 33 (1979) 1, (4.6)] */ int gsl_sf_ellint_Ecomp_e(double k, gsl_mode_t mode, gsl_sf_result * result) { if(k*k >= 1.0) { DOMAIN_ERROR(result); } else if(k*k >= 1.0 - GSL_SQRT_DBL_EPSILON) { /* [Abramowitz+Stegun, 17.3.36] */ const double y = 1.0 - k*k; const double a[] = { 0.44325141463, 0.06260601220, 0.04757383546 }; const double b[] = { 0.24998368310, 0.09200180037, 0.04069697526 }; const double ta = 1.0 + y*(a[0] + y*(a[1] + a[2]*y)); const double tb = -y*log(y) * (b[0] + y*(b[1] + b[2]*y)); result->val = ta + tb; result->err = 2.0 * GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else { gsl_sf_result rf; gsl_sf_result rd; const double y = 1.0 - k*k; const int rfstatus = gsl_sf_ellint_RF_e(0.0, y, 1.0, mode, &rf); const int rdstatus = gsl_sf_ellint_RD_e(0.0, y, 1.0, mode, &rd); result->val = rf.val - k*k/3.0 * rd.val; result->err = rf.err + k*k/3.0 * rd.err; return GSL_ERROR_SELECT_2(rfstatus, rdstatus); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_ellint_Kcomp(double k, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_Kcomp_e(k, mode, &result)); } double gsl_sf_ellint_Ecomp(double k, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_Ecomp_e(k, mode, &result)); } double gsl_sf_ellint_F(double phi, double k, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_F_e(phi, k, mode, &result)); } double gsl_sf_ellint_E(double phi, double k, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_E_e(phi, k, mode, &result)); } double gsl_sf_ellint_P(double phi, double k, double n, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_P_e(phi, k, n, mode, &result)); } double gsl_sf_ellint_D(double phi, double k, double n, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_D_e(phi, k, n, mode, &result)); } double gsl_sf_ellint_RC(double x, double y, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_RC_e(x, y, mode, &result)); } double gsl_sf_ellint_RD(double x, double y, double z, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_RD_e(x, y, z, mode, &result)); } double gsl_sf_ellint_RF(double x, double y, double z, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_RF_e(x, y, z, mode, &result)); } double gsl_sf_ellint_RJ(double x, double y, double z, double p, gsl_mode_t mode) { EVAL_RESULT(gsl_sf_ellint_RJ_e(x, y, z, p, mode, &result)); }
{ "alphanum_fraction": 0.5943910149, "avg_line_length": 30.283095723, "ext": "c", "hexsha": "88d63ad14d16c2ee09474988c71b6f32f9e9583f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/ellint.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/ellint.c", "max_line_length": 99, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/ellint.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 5500, "size": 14869 }
/* * Author: Nicu Tofan * License: BSD * * See below for getRealTime() license. */ #include <cblas.h> #include <stdlib.h> #include <stdio.h> #define test_m 2 #define test_k 3 #define test_n 4 #define test_m_extra 5 #define test_k_extra 7 #define test_n_extra 8 #define test_row_major 1 #define test_col_major 0 double getRealTime(); //! prints a matrix in either row major or column major order static void printMatrix (double *data, int rows, int cols, int row_major) { int i,j; // column header printf (" "); for(j=0; j<cols;j++) { printf (" Col %2d ", j+1); } printf ("\n"); for(i=0; i<rows;i++) { printf ("Row %2d: ", i+1); for(j=0; j<cols;j++) { if (row_major) { printf ("%7.4f ", data[i*cols+j]); } else { printf ("%7.4f ", data[j*rows+i]); } } printf ("\n"); } printf ("\n--------------------------------------------------------\n\n"); } //! test printMatrix() to make sure it works static void testPrintMatrix() { printf ("==========================================================\n"); printf ("Test print function\n"); printf ("==========================================================\n\n"); printf ("Matrix in row major order\n\n"); double A[2*3] = { 1, 2, 3, 4, 5, 6 }; printMatrix (A, 2, 3, test_row_major); printf ("Matrix in column major order\n\n"); double B[2*3] = { 1, 4, 2, 5, 3, 6 }; printMatrix (B, 2, 3, test_col_major); } //! testing the extra-space static void testMulColMajorExtraSpace() { printf ("==========================================================\n"); printf ("Extra space in matrix not used in ops\n"); printf ("==========================================================\n\n"); /* MATRIX A[2x3] Col 1 Col 2 Col 3 Row 1: 1.0000 2.0000 3.0000 Row 2: 4.0000 5.0000 6.0000 */ printf ("A\n\n"); double A[] = { 1, 4, 9, 9, 9, // 9's will not affect the computation 2, 5, 9, 9, 9, 3, 6, 9, 9, 9 }; printMatrix (A, test_m_extra, test_k, test_col_major); /* MATRIX B[3x4] Col 1 Col 2 Col 3 Col 4 Row 1: 1.0000 2.0000 3.0000 4.0000 Row 2: 0.1000 0.2000 0.3000 0.4000 Row 3: 0.0100 0.0200 0.0300 0.0400 */ printf ("B\n\n"); double B[] = { 1.0, 0.1, 0.01, 9.0, 9.0, 9.0, 9.0, // 9's will not affect the computation 2.0, 0.2, 0.02, 9.0, 9.0, 9.0, 9.0, 3.0, 0.3, 0.03, 9.0, 9.0, 9.0, 9.0, 4.0, 0.4, 0.04, 9.0, 9.0, 9.0, 9.0, }; printMatrix (B, test_k_extra, test_n, test_col_major); /* MATRIX C[2x4] Col 1 Col 2 Col 3 Col 4 Row 1: 1.2300 2.4600 3.6900 4.9200 Row 2: 4.5600 9.1200 13.6800 18.2400 */ double C[test_n_extra*test_n] = {0}; printf ("C\n\n"); // C = alpha*A*B+beta*C cblas_dgemm( CblasColMajor, CblasNoTrans, // TRANSA: CblasNoTrans, // TRANSB: test_m, // A matrix: m rows, k columns test_n, // B matrix: k rows, n columns test_k, // C matrix: m rows, n columns 1.0, // alpha = 1.0 A, // A source matrix test_m_extra, // true lenght of a column in A // if TRANSA = 'N' then >= m // if TRANSA = 'T' then >= k B, // B source matrix test_k_extra, // true lenght of a column in B // if TRANSB = 'N' then >= k // if TRANSB = 'T' then >= n 0.0, // beta = 0.0 C, // C destination matrix test_n_extra); // true lenght of a row in C // must be >= m printMatrix (C, test_n_extra, test_n, test_col_major); } //! blas expects column major order static void testMulColMajor() { printf ("==========================================================\n"); printf ("Test BLAS multiply - column major order\n"); printf ("==========================================================\n\n"); /* MATRIX A[2x3] Col 1 Col 2 Col 3 Row 1: 1.0000 2.0000 3.0000 Row 2: 4.0000 5.0000 6.0000 */ printf ("A\n\n"); double A[test_m*test_k] = { 1, 4, 2, 5, 3, 6 }; printMatrix (A, test_m, test_k, test_col_major); /* MATRIX B[3x4] Col 1 Col 2 Col 3 Col 4 Row 1: 1.0000 2.0000 3.0000 4.0000 Row 2: 0.1000 0.2000 0.3000 0.4000 Row 3: 0.0100 0.0200 0.0300 0.0400 */ printf ("B\n\n"); double B[test_k*test_n] = { 1.0, 0.1, 0.01, 2.0, 0.2, 0.02, 3.0, 0.3, 0.03, 4.0, 0.4, 0.04 }; printMatrix (B, test_k, test_n, test_col_major); /* MATRIX C[2x4] Col 1 Col 2 Col 3 Col 4 Row 1: 1.2300 2.4600 3.6900 4.9200 Row 2: 4.5600 9.1200 13.6800 18.2400 */ double C[test_m*test_n] = {0}; printf ("C\n\n"); // http://www.math.utah.edu/software/lapack/lapack-blas/dgemm.html /* cblas_dgemm( 'N', // TRANSA: N - do not transpose A, T - transpose A 'N', // TRANSB: N - do not transpose A, T - transpose A test_m, // A matrix: m rows, k columns test_n, // B matrix: k rows, n columns test_k, // C matrix: m rows, n columns 1.0, // alpha = 1.0 A, // A source matrix test_m, // true lenght of a column in A // if TRANSA = 'N' then >= m // if TRANSA = 'T' then >= k B, // B source matrix test_k, // true lenght of a column in B // if TRANSB = 'N' then >= k // if TRANSB = 'T' then >= n 0.0, // beta = 0.0 C, // C destination matrix test_m); // true lenght of a row in C // must be >= m */ // C = alpha*A*B+beta*C cblas_dgemm( CblasColMajor, CblasNoTrans, // TRANSA: CblasNoTrans, // TRANSB: test_m, // A matrix: m rows, k columns test_n, // B matrix: k rows, n columns test_k, // C matrix: m rows, n columns 1.0, // alpha = 1.0 A, // A source matrix test_m, // true lenght of a column in A // if TRANSA = 'N' then >= m // if TRANSA = 'T' then >= k B, // B source matrix test_k, // true lenght of a column in B // if TRANSB = 'N' then >= k // if TRANSB = 'T' then >= n 0.0, // beta = 0.0 C, // C destination matrix test_m); // true lenght of a row in C // must be >= m printMatrix (C, test_m, test_n, test_col_major); } //! attempt the trickery static void testMulRowMajor_trickery() { printf ("==========================================================\n"); printf ("Test BLAS multiply - row major order with trickery\n"); printf ("==========================================================\n\n"); /* MATRIX A[2x3] Col 1 Col 2 Col 3 Row 1: 1.0000 2.0000 3.0000 Row 2: 4.0000 5.0000 6.0000 */ printf ("A\n\n"); double A[test_m*test_k] = { 1, 2, 3, 4, 5, 6 }; printMatrix (A, test_m, test_k, test_row_major); /* MATRIX B[3x4] Col 1 Col 2 Col 3 Col 4 Row 1: 1.0000 2.0000 3.0000 4.0000 Row 2: 0.1000 0.2000 0.3000 0.4000 Row 3: 0.0100 0.0200 0.0300 0.0400 */ printf ("B\n\n"); double B[test_k*test_n] = { 1.00, 2.00, 3.00, 4.00, 0.10, 0.20, 0.30, 0.40, 0.01, 0.02, 0.03, 0.04 }; printMatrix (B, test_k, test_n, test_row_major); /* MATRIX C[2x4] Col 1 Col 2 Col 3 Col 4 Row 1: 1.2300 2.4600 3.6900 4.9200 Row 2: 4.5600 9.1200 13.6800 18.2400 */ double C[test_m*test_n] = {0}; printf ("C\n\n"); // C = alpha*A*B+beta*C cblas_dgemm( CblasColMajor, CblasNoTrans, // TRANSA: CblasNoTrans, // TRANSB: test_n, // B matrix: k rows, n columns test_m, // A matrix: m rows, k columns test_k, // C matrix: m rows, n columns 1.0, // alpha = 1.0 B, // B source matrix test_n, // true lenght of a column in B // if TRANSB = 'N' then >= k // if TRANSB = 'T' then >= n A, // A source matrix test_k, // true lenght of a column in A // if TRANSA = 'N' then >= m // if TRANSA = 'T' then >= k 0.0, // beta = 0.0 C, // C destination matrix test_n); // true lenght of a row in C // must be >= m printMatrix (C, test_m, test_n, test_row_major); } //! build in version static void testMulRowMajor() { printf ("==========================================================\n"); printf ("Test BLAS multiply - row major order without trickery\n"); printf ("==========================================================\n\n"); /* MATRIX A[2x3] Col 1 Col 2 Col 3 Row 1: 1.0000 2.0000 3.0000 Row 2: 4.0000 5.0000 6.0000 */ printf ("A\n\n"); double A[test_m*test_k] = { 1, 2, 3, 4, 5, 6 }; printMatrix (A, test_m, test_k, test_row_major); /* MATRIX B[3x4] Col 1 Col 2 Col 3 Col 4 Row 1: 1.0000 2.0000 3.0000 4.0000 Row 2: 0.1000 0.2000 0.3000 0.4000 Row 3: 0.0100 0.0200 0.0300 0.0400 */ printf ("B\n\n"); double B[test_k*test_n] = { 1.00, 2.00, 3.00, 4.00, 0.10, 0.20, 0.30, 0.40, 0.01, 0.02, 0.03, 0.04 }; printMatrix (B, test_k, test_n, test_row_major); /* MATRIX C[2x4] Col 1 Col 2 Col 3 Col 4 Row 1: 1.2300 2.4600 3.6900 4.9200 Row 2: 4.5600 9.1200 13.6800 18.2400 */ double C[test_m*test_n] = {0}; printf ("C\n\n"); // C = alpha*A*B+beta*C cblas_dgemm( CblasRowMajor, CblasNoTrans, // TRANSA: CblasNoTrans, // TRANSB: test_m, // A matrix: m rows, k columns test_n, // B matrix: k rows, n columns test_k, // C matrix: m rows, n columns 1.0, // alpha = 1.0 A, // A source matrix test_k, // true lenght of a column in A // if TRANSA = 'N' then >= m // if TRANSA = 'T' then >= k B, // B source matrix test_n, // true lenght of a column in B // if TRANSB = 'N' then >= k // if TRANSB = 'T' then >= n 0.0, // beta = 0.0 C, // C destination matrix test_n); // true lenght of a row in C // must be >= m printMatrix (C, test_m, test_n, test_col_major); } #undef test_m #undef test_n #undef test_k #define test_m 500 #define test_k 600 #define test_n 700 #define test_spins 5 // --------------------------------------------------------------------- #define IMPLEMENTATION_ROW_MAJOR \ cblas_dgemm( \ CblasRowMajor, CblasNoTrans, CblasNoTrans, test_m, test_n, \ test_k, 1.0, A, test_k, B, test_n, 0.0, C, test_n); \ startTime = getRealTime (); \ for(i=0; i<test_spins;i++) { \ cblas_dgemm( \ CblasRowMajor, CblasNoTrans, CblasNoTrans, test_m, test_n, \ test_k, 1.0, A, test_k, B, test_n, 0.0, C, test_n); \ } \ endTime = getRealTime (); \ printf ("- Build-in implementation - row major (%d) = %lf\n", test_spins, (endTime - startTime) ); // --------------------------------------------------------------------- #define IMPLEMENTATION_TRICKERY \ cblas_dgemm( \ CblasColMajor, CblasNoTrans, CblasNoTrans, test_n, test_m, \ test_k, 1.0, B, test_n, A, test_k, 0.0, C, test_n); \ startTime = getRealTime (); \ for(i=0; i<test_spins;i++) { \ cblas_dgemm( \ CblasColMajor, CblasNoTrans, CblasNoTrans, test_n, test_m, \ test_k, 1.0, B, test_n, A, test_k, 0.0, C, test_n); \ } \ endTime = getRealTime (); \ printf ("- Trickery implementation (%d)= %lf\n", test_spins, (endTime - startTime) ); // --------------------------------------------------------------------- #define IMPLEMENTATION_COL_MAJOR \ cblas_dgemm( \ CblasColMajor, CblasNoTrans, CblasNoTrans, test_m, test_n, \ test_k, 1.0, A, test_m, B, test_k, 0.0, C, test_m); \ startTime = getRealTime (); \ for(i=0; i<test_spins;i++) { \ cblas_dgemm( \ CblasColMajor, CblasNoTrans, CblasNoTrans, test_m, test_n, \ test_k, 1.0, A, test_m, B, test_k, 0.0, C, test_m); \ } \ endTime = getRealTime (); \ printf ("- Build-in implementation - column major (%d) = %lf\n", test_spins, (endTime - startTime) ); // --------------------------------------------------------------------- //! test my undestanding of the parameters void compareBuildInWithTrickery() { printf ("==========================================================\n"); printf ("Compare these two methods\n"); printf ("==========================================================\n\n"); // srand((unsigned)time(NULL)); double startTime, endTime; int i; double *A = (double*)malloc(test_m*test_k*sizeof(double)); int a_tot = test_m*test_k; double *iter = A; for (i = 0; i<a_tot; i++) { *iter = ((double)rand()/(double)RAND_MAX);; iter++; } double *B = (double*)malloc(test_k*test_n*sizeof(double)); int b_tot = test_k*test_n; iter = B; for (i = 0; i<b_tot; i++) { *iter = ((double)rand()/(double)RAND_MAX);; iter++; } double *C = (double*)malloc(test_m*test_n*sizeof(double)); iter = C; int c_tot = test_m*test_n; for (i = 0; i<c_tot; i++) { *iter = 0.0; iter++; } IMPLEMENTATION_ROW_MAJOR; IMPLEMENTATION_TRICKERY; IMPLEMENTATION_COL_MAJOR; IMPLEMENTATION_TRICKERY; IMPLEMENTATION_ROW_MAJOR; IMPLEMENTATION_COL_MAJOR; IMPLEMENTATION_ROW_MAJOR; IMPLEMENTATION_COL_MAJOR; IMPLEMENTATION_TRICKERY; IMPLEMENTATION_COL_MAJOR; IMPLEMENTATION_ROW_MAJOR; IMPLEMENTATION_TRICKERY; IMPLEMENTATION_COL_MAJOR; IMPLEMENTATION_TRICKERY; IMPLEMENTATION_ROW_MAJOR; IMPLEMENTATION_TRICKERY; IMPLEMENTATION_COL_MAJOR; IMPLEMENTATION_ROW_MAJOR; } int main(int argc, char **argv) { testPrintMatrix(); testMulColMajorExtraSpace(); testMulColMajor(); testMulRowMajor_trickery(); testMulRowMajor(); compareBuildInWithTrickery(); return 0; } /* * Author: David Robert Nadeau * Site: http://NadeauSoftware.com/ * License: Creative Commons Attribution 3.0 Unported License * http://creativecommons.org/licenses/by/3.0/deed.en_US * * http://nadeausoftware.com/articles/2012/04/c_c_tip_how_measure_elapsed_real_time_benchmarking */ #if defined(_WIN32) #include <Windows.h> #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) #include <unistd.h> /* POSIX flags */ #include <time.h> /* clock_gettime(), time() */ #include <sys/time.h> /* gethrtime(), gettimeofday() */ #if defined(__MACH__) && defined(__APPLE__) #include <mach/mach.h> #include <mach/mach_time.h> #endif #else #error "Unable to define getRealTime( ) for an unknown OS." #endif /** * Returns the real time, in seconds, or -1.0 if an error occurred. * * Time is measured since an arbitrary and OS-dependent start time. * The returned real time is only useful for computing an elapsed time * between two calls to this function. */ double getRealTime( ) { #if defined(_WIN32) FILETIME tm; ULONGLONG t; #if defined(NTDDI_WIN8) && NTDDI_VERSION >= NTDDI_WIN8 /* Windows 8, Windows Server 2012 and later. ---------------- */ GetSystemTimePreciseAsFileTime( &tm ); #else /* Windows 2000 and later. ---------------------------------- */ GetSystemTimeAsFileTime( &tm ); #endif t = ((ULONGLONG)tm.dwHighDateTime << 32) | (ULONGLONG)tm.dwLowDateTime; return (double)t / 10000000.0; #elif (defined(__hpux) || defined(hpux)) || ((defined(__sun__) || defined(__sun) || defined(sun)) && (defined(__SVR4) || defined(__svr4__))) /* HP-UX, Solaris. ------------------------------------------ */ return (double)gethrtime( ) / 1000000000.0; #elif defined(__MACH__) && defined(__APPLE__) /* OSX. ----------------------------------------------------- */ static double timeConvert = 0.0; if ( timeConvert == 0.0 ) { mach_timebase_info_data_t timeBase; (void)mach_timebase_info( &timeBase ); timeConvert = (double)timeBase.numer / (double)timeBase.denom / 1000000000.0; } return (double)mach_absolute_time( ) * timeConvert; #elif defined(_POSIX_VERSION) /* POSIX. --------------------------------------------------- */ #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) { struct timespec ts; #if defined(CLOCK_MONOTONIC_PRECISE) /* BSD. --------------------------------------------- */ const clockid_t id = CLOCK_MONOTONIC_PRECISE; #elif defined(CLOCK_MONOTONIC_RAW) /* Linux. ------------------------------------------- */ const clockid_t id = CLOCK_MONOTONIC_RAW; #elif defined(CLOCK_HIGHRES) /* Solaris. ----------------------------------------- */ const clockid_t id = CLOCK_HIGHRES; #elif defined(CLOCK_MONOTONIC) /* AIX, BSD, Linux, POSIX, Solaris. ----------------- */ const clockid_t id = CLOCK_MONOTONIC; #elif defined(CLOCK_REALTIME) /* AIX, BSD, HP-UX, Linux, POSIX. ------------------- */ const clockid_t id = CLOCK_REALTIME; #else const clockid_t id = (clockid_t)-1; /* Unknown. */ #endif /* CLOCK_* */ if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 ) return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0; /* Fall thru. */ } #endif /* _POSIX_TIMERS */ /* AIX, BSD, Cygwin, HP-UX, Linux, OSX, POSIX, Solaris. ----- */ struct timeval tm; gettimeofday( &tm, NULL ); return (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0; #else return -1.0; /* Failed. */ #endif }
{ "alphanum_fraction": 0.4827890556, "avg_line_length": 30.5245641838, "ext": "c", "hexsha": "55d6f4817f331696acb7f539b6d720f2e7fedabb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a2752c37c68a073cc1144eb8742303316281fb60", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elsuizo/C_work", "max_forks_repo_path": "cblas_test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a2752c37c68a073cc1144eb8742303316281fb60", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "elsuizo/C_work", "max_issues_repo_path": "cblas_test.c", "max_line_length": 140, "max_stars_count": null, "max_stars_repo_head_hexsha": "a2752c37c68a073cc1144eb8742303316281fb60", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elsuizo/C_work", "max_stars_repo_path": "cblas_test.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6018, "size": 19261 }
/** * * @file testing_sgels.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Bilel Hadri * @author Hatem Ltaief * @date 2010-11-15 * @generated s Tue Jan 7 11:45:18 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_smain.h" #undef COMPLEX #define REAL enum blas_order_type { blas_rowmajor = 101, blas_colmajor = 102 }; enum blas_uplo_type { blas_upper = 121, blas_lower = 122 }; enum blas_cmach_type { blas_base = 151, blas_t = 152, blas_rnd = 153, blas_ieee = 154, blas_emin = 155, blas_emax = 156, blas_eps = 157, blas_prec = 158, blas_underflow = 159, blas_overflow = 160, blas_sfmin = 161}; enum blas_norm_type { blas_one_norm = 171, blas_real_one_norm = 172, blas_two_norm = 173, blas_frobenius_norm = 174, blas_inf_norm = 175, blas_real_inf_norm = 176, blas_max_norm = 177, blas_real_max_norm = 178 }; static void BLAS_error(char *rname, int err, int val, int x) { fprintf( stderr, "%s %d %d %d\n", rname, err, val, x ); abort(); } static void BLAS_ssy_norm(enum blas_order_type order, enum blas_norm_type norm, enum blas_uplo_type uplo, int n, const float *a, int lda, float *res) { int i, j; float anorm, v; char rname[] = "BLAS_ssy_norm"; if (order != blas_colmajor) BLAS_error( rname, -1, order, 0 ); if (norm == blas_inf_norm) { anorm = 0.0; if (blas_upper == uplo) { for (i = 0; i < n; ++i) { v = 0.0; for (j = 0; j < i; ++j) { v += fabsf( a[j + i * lda] ); } for (j = i; j < n; ++j) { v += fabsf( a[i + j * lda] ); } if (v > anorm) anorm = v; } } else { BLAS_error( rname, -3, norm, 0 ); return; } } else { BLAS_error( rname, -2, norm, 0 ); return; } if (res) *res = anorm; } static void BLAS_sge_norm(enum blas_order_type order, enum blas_norm_type norm, int m, int n, const float *a, int lda, float *res) { int i, j; float anorm, v; char rname[] = "BLAS_sge_norm"; if (order != blas_colmajor) BLAS_error( rname, -1, order, 0 ); if (norm == blas_frobenius_norm) { anorm = 0.0f; for (j = n; j; --j) { for (i = m; i; --i) { v = a[0]; anorm += v * v; a++; } a += lda - m; } anorm = sqrt( anorm ); } else if (norm == blas_inf_norm) { anorm = 0.0f; for (i = 0; i < m; ++i) { v = 0.0f; for (j = 0; j < n; ++j) { v += fabsf( a[i + j * lda] ); } if (v > anorm) anorm = v; } } else { BLAS_error( rname, -2, norm, 0 ); return; } if (res) *res = anorm; } static float BLAS_spow_di(float x, int n) { float rv = 1.0; if (n < 0) { n = -n; x = 1.0 / x; } for (; n; n >>= 1, x *= x) { if (n & 1) rv *= x; } return rv; } static float BLAS_sfpinfo(enum blas_cmach_type cmach) { float eps = 1.0, r = 1.0, o = 1.0, b = 2.0; int t = 53, l = 1024, m = -1021; char rname[] = "BLAS_sfpinfo"; if ((sizeof eps) == sizeof(float)) { t = 24; l = 128; m = -125; } else { t = 53; l = 1024; m = -1021; } /* for (i = 0; i < t; ++i) eps *= half; */ eps = BLAS_spow_di( b, -t ); /* for (i = 0; i >= m; --i) r *= half; */ r = BLAS_spow_di( b, m-1 ); o -= eps; /* for (i = 0; i < l; ++i) o *= b; */ o = (o * BLAS_spow_di( b, l-1 )) * b; switch (cmach) { case blas_eps: return eps; case blas_sfmin: return r; default: BLAS_error( rname, -1, cmach, 0 ); break; } return 0.0; } static int check_orthogonality(int, int, int, float*, float); static int check_factorization(int, int, float*, float*, int, float*, float); static int check_solution(int, int, int, float*, int, float*, float*, int, float); int testing_sgels(int argc, char **argv) { int mode = 0; if ( argc < 1 ){ goto usage; } else { mode = atoi(argv[0]); } /* Check for number of arguments*/ if ( ((mode == 0) && (argc != 6)) || ((mode != 0) && (argc != 7)) ){ usage: USAGE("GELS", "MODE M N LDA NRHS LDB [RH]", " - MODE : 0: flat, 1: tree (RH needed)\n" " - M : number of rows of the matrix A\n" " - N : number of columns of the matrix A\n" " - LDA : leading dimension of the matrix A\n" " - NRHS : number of RHS\n" " - LDB : leading dimension of the matrix B\n" " - RH : Size of each subdomains\n"); return -1; } int M = atoi(argv[1]); int N = atoi(argv[2]); int LDA = atoi(argv[3]); int NRHS = atoi(argv[4]); int LDB = atoi(argv[5]); int rh; int K = min(M, N); float eps; int info_ortho, info_solution, info_factorization; int i,j; int LDAxN = LDA*N; int LDBxNRHS = LDB*NRHS; float *A1 = (float *)malloc(LDA*N*sizeof(float)); float *A2 = (float *)malloc(LDA*N*sizeof(float)); float *B1 = (float *)malloc(LDB*NRHS*sizeof(float)); float *B2 = (float *)malloc(LDB*NRHS*sizeof(float)); float *Q = (float *)malloc(LDA*N*sizeof(float)); PLASMA_desc *T; /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!B1)||(!B2)||(!Q)){ printf("Out of Memory \n "); return -2; } if ( mode ) { rh = atoi(argv[6]); PLASMA_Set(PLASMA_HOUSEHOLDER_MODE, PLASMA_TREE_HOUSEHOLDER); PLASMA_Set(PLASMA_HOUSEHOLDER_SIZE, rh); } PLASMA_Alloc_Workspace_sgels(M, N, &T); eps = BLAS_sfpinfo( blas_eps ); /*---------------------------------------------------------- * TESTING SGELS */ /* Initialize A1 and A2 */ LAPACKE_slarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < M; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i] ; /* Initialize B1 and B2 */ LAPACKE_slarnv_work(IONE, ISEED, LDBxNRHS, B1); for (i = 0; i < M; i++) for (j = 0; j < NRHS; j++) B2[LDB*j+i] = B1[LDB*j+i] ; memset((void*)Q, 0, LDA*N*sizeof(float)); for (i = 0; i < K; i++) Q[LDA*i+i] = 1.0; /* PLASMA SGELS */ PLASMA_sgels(PlasmaNoTrans, M, N, NRHS, A2, LDA, T, B2, LDB); /* PLASMA SGELS */ if (M >= N) /* Building the economy-size Q */ PLASMA_sorgqr(M, N, K, A2, LDA, T, Q, LDA); else /* Building the economy-size Q */ PLASMA_sorglq(M, N, K, A2, LDA, T, Q, LDA); printf("\n"); printf("------ TESTS FOR PLASMA SGELS ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q, eps); info_factorization = check_factorization(M, N, A1, A2, LDA, Q, eps); info_solution = check_solution(M, N, NRHS, A1, LDA, B1, B2, LDB, eps); if ((info_solution == 0)&(info_factorization == 0)&(info_ortho == 0)) { printf("***************************************************\n"); printf(" ---- TESTING SGELS ...................... PASSED !\n"); printf("***************************************************\n"); } else { printf("************************************************\n"); printf(" - TESTING SGELS ... FAILED !\n"); printf("************************************************\n"); } /*------------------------------------------------------------- * TESTING SGEQRF + SGEQRS or SGELQF + SGELQS */ /* Initialize A1 and A2 */ LAPACKE_slarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < M; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i]; /* Initialize B1 and B2 */ LAPACKE_slarnv_work(IONE, ISEED, LDBxNRHS, B1); for (i = 0; i < M; i++) for (j = 0; j < NRHS; j++) B2[LDB*j+i] = B1[LDB*j+i]; memset((void*)Q, 0, LDA*N*sizeof(float)); for (i = 0; i < K; i++) Q[LDA*i+i] = 1.0; if (M >= N) { printf("\n"); printf("------ TESTS FOR PLASMA SGEQRF + SGEQRS ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Plasma routines */ PLASMA_sgeqrf(M, N, A2, LDA, T); PLASMA_sorgqr(M, N, K, A2, LDA, T, Q, LDA); PLASMA_sgeqrs(M, N, NRHS, A2, LDA, T, B2, LDB); /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q, eps); info_factorization = check_factorization(M, N, A1, A2, LDA, Q, eps); info_solution = check_solution(M, N, NRHS, A1, LDA, B1, B2, LDB, eps); if ((info_solution == 0)&(info_factorization == 0)&(info_ortho == 0)) { printf("***************************************************\n"); printf(" ---- TESTING SGEQRF + SGEQRS ............ PASSED !\n"); printf("***************************************************\n"); } else{ printf("***************************************************\n"); printf(" - TESTING SGEQRF + SGEQRS ... FAILED !\n"); printf("***************************************************\n"); } } else { printf("\n"); printf("------ TESTS FOR PLASMA SGELQF + SGELQS ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Plasma routines */ PLASMA_sgelqf(M, N, A2, LDA, T); PLASMA_sorglq(M, N, K, A2, LDA, T, Q, LDA); PLASMA_sgelqs(M, N, NRHS, A2, LDA, T, B2, LDB); /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q, eps); info_factorization = check_factorization(M, N, A1, A2, LDA, Q, eps); info_solution = check_solution(M, N, NRHS, A1, LDA, B1, B2, LDB, eps); if ( (info_solution == 0) & (info_factorization == 0) & (info_ortho == 0) ) { printf("***************************************************\n"); printf(" ---- TESTING SGELQF + SGELQS ............ PASSED !\n"); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" - TESTING SGELQF + SGELQS ... FAILED !\n"); printf("***************************************************\n"); } } /*---------------------------------------------------------- * TESTING SGEQRF + ZORMQR + STRSM */ /* Initialize A1 and A2 */ LAPACKE_slarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < M; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i]; /* Initialize B1 and B2 */ memset(B2, 0, LDB*NRHS*sizeof(float)); LAPACKE_slarnv_work(IONE, ISEED, LDBxNRHS, B1); for (i = 0; i < M; i++) for (j = 0; j < NRHS; j++) B2[LDB*j+i] = B1[LDB*j+i]; /* PLASMA SGEQRF+ SORMQR + STRSM */ memset((void*)Q, 0, LDA*N*sizeof(float)); for (i = 0; i < K; i++) Q[LDA*i+i] = 1.0; if (M >= N) { printf("\n"); printf("------ TESTS FOR PLASMA SGEQRF + SORMQR + STRSM ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); PLASMA_sgeqrf(M, N, A2, LDA, T); PLASMA_sorgqr(M, N, K, A2, LDA, T, Q, LDA); PLASMA_sormqr(PlasmaLeft, PlasmaTrans, M, NRHS, N, A2, LDA, T, B2, LDB); PLASMA_strsm(PlasmaLeft, PlasmaUpper, PlasmaNoTrans, PlasmaNonUnit, N, NRHS, 1.0, A2, LDA, B2, LDB); } else { printf("\n"); printf("------ TESTS FOR PLASMA SGELQF + SORMLQ + STRSM ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); PLASMA_sgelqf(M, N, A2, LDA, T); PLASMA_strsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaNonUnit, M, NRHS, 1.0, A2, LDA, B2, LDB); PLASMA_sorglq(M, N, K, A2, LDA, T, Q, LDA); PLASMA_sormlq(PlasmaLeft, PlasmaTrans, N, NRHS, M, A2, LDA, T, B2, LDB); } /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q, eps); info_factorization = check_factorization(M, N, A1, A2, LDA, Q, eps); info_solution = check_solution(M, N, NRHS, A1, LDA, B1, B2, LDB, eps); if ( (info_solution == 0) & (info_factorization == 0) & (info_ortho == 0) ) { if (M >= N) { printf("***************************************************\n"); printf(" ---- TESTING SGEQRF + SORMQR + STRSM .... PASSED !\n"); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" ---- TESTING SGELQF + STRSM + SORMLQ .... PASSED !\n"); printf("***************************************************\n"); } } else { if (M >= N) { printf("***************************************************\n"); printf(" - TESTING SGEQRF + SORMQR + STRSM ... FAILED !\n"); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" - TESTING SGELQF + STRSM + SORMLQ ... FAILED !\n"); printf("***************************************************\n"); } } free(A1); free(A2); free(B1); free(B2); free(Q); PLASMA_Dealloc_Handle_Tile( &T ); return 0; } /*------------------------------------------------------------------- * Check the orthogonality of Q */ static int check_orthogonality(int M, int N, int LDQ, float *Q, float eps) { float alpha, beta; float normQ; int info_ortho; int i; int minMN = min(M, N); float *work = (float *)malloc(minMN*sizeof(float)); alpha = 1.0; beta = -1.0; /* Build the idendity matrix USE DLASET?*/ float *Id = (float *) malloc(minMN*minMN*sizeof(float)); memset((void*)Id, 0, minMN*minMN*sizeof(float)); for (i = 0; i < minMN; i++) Id[i*minMN+i] = (float)1.0; /* Perform Id - Q'Q */ if (M >= N) cblas_ssyrk(CblasColMajor, CblasUpper, CblasTrans, N, M, alpha, Q, LDQ, beta, Id, N); else cblas_ssyrk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M); BLAS_ssy_norm( blas_colmajor, blas_inf_norm, blas_upper, minMN, Id, minMN, &normQ ); printf("============\n"); printf("Checking the orthogonality of Q \n"); printf("||Id-Q'*Q||_oo / (N*eps) = %e \n", normQ/(minMN*eps)); if ( isnan(normQ / (minMN * eps)) || isinf(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 60.0) ) { printf("-- Orthogonality is suspicious ! \n"); info_ortho=1; } else { printf("-- Orthogonality is CORRECT ! \n"); info_ortho=0; } free(work); free(Id); return info_ortho; } /*------------------------------------------------------------ * Check the factorization QR */ static int check_factorization(int M, int N, float *A1, float *A2, int LDA, float *Q, float eps ) { float Anorm, Rnorm; float alpha, beta; int info_factorization; int i,j; float *Ql = (float *)malloc(M*N*sizeof(float)); float *Residual = (float *)malloc(M*N*sizeof(float)); float *work = (float *)malloc(max(M,N)*sizeof(float)); alpha=1.0; beta=0.0; if (M >= N) { /* Extract the R */ float *R = (float *)malloc(N*N*sizeof(float)); memset((void*)R, 0, N*N*sizeof(float)); LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N); /* Perform Ql=Q*R */ memset((void*)Ql, 0, M*N*sizeof(float)); cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, (alpha), Q, LDA, R, N, (beta), Ql, M); free(R); } else { /* Extract the L */ float *L = (float *)malloc(M*M*sizeof(float)); memset((void*)L, 0, M*M*sizeof(float)); LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M); /* Perform Ql=LQ */ memset((void*)Ql, 0, M*N*sizeof(float)); cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, (alpha), L, M, Q, LDA, (beta), Ql, M); free(L); } /* Compute the Residual */ for (i = 0; i < M; i++) for (j = 0 ; j < N; j++) Residual[j*M+i] = A1[j*LDA+i]-Ql[j*M+i]; BLAS_sge_norm( blas_colmajor, blas_inf_norm, M, N, Residual, M, &Rnorm ); BLAS_sge_norm( blas_colmajor, blas_inf_norm, M, N, A2, LDA, &Anorm ); if (M >= N) { printf("============\n"); printf("Checking the QR Factorization \n"); printf("-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } else { printf("============\n"); printf("Checking the LQ Factorization \n"); printf("-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } if (isnan(Rnorm / (Anorm * N *eps)) || isinf(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 60.0) ) { printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else { printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(work); free(Ql); free(Residual); return info_factorization; } /*-------------------------------------------------------------- * Check the solution */ static int check_solution(int M, int N, int NRHS, float *A, int LDA, float *B, float *X, int LDB, float eps) { int info_solution; float Rnorm, Anorm, Xnorm, Bnorm; float zone, mzone, zzero; float result; float *work = (float *)malloc(max(M, N)* sizeof(float)); zone = 1.0; mzone = -1.0; zzero = 0.0; BLAS_sge_norm( blas_colmajor, blas_inf_norm, M, N, A, LDA, &Anorm ); BLAS_sge_norm( blas_colmajor, blas_inf_norm, M, NRHS, B, LDB, &Bnorm ); BLAS_sge_norm( blas_colmajor, blas_inf_norm, N, NRHS, X, LDB, &Xnorm ); /* Compute Ax - b */ cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, (zone), A, LDA, X, LDB, (mzone), B, LDB); /* Compute A' * (Ax - b) */ cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, N, NRHS, M, (zone), A, LDA, B, LDB, (zzero), X, LDB); BLAS_sge_norm( blas_colmajor, blas_inf_norm, N, NRHS, X, LDB, &Rnorm ); if (getenv("PLASMA_TESTING_VERBOSE")) printf( "||A||_oo=%f\n||X||_oo=%f\n||B||_oo=%f\n||A X - B||_oo=%e\n", Anorm, Xnorm, Bnorm, Rnorm ); result = Rnorm / ( (Anorm*Xnorm+Bnorm)*N*eps ) ; printf("============\n"); printf("Checking the Residual of the solution \n"); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n", result); if ( isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } free(work); return info_solution; }
{ "alphanum_fraction": 0.4868564392, "avg_line_length": 32.1354642314, "ext": "c", "hexsha": "d9d21ab934b10a7c2aace5abd2b20c911936cf08", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_sgels.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_sgels.c", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_sgels.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6656, "size": 21113 }
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2008, The GROMACS development team, * check out http://www.gromacs.org for more information. * Copyright (c) 2012,2013, by the GROMACS development team, led by * David van der Spoel, Berk Hess, Erik Lindahl, and including many * others, as listed in the AUTHORS file in the top-level source * directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <math.h> /*#define HAVE_NN_LOOPS*/ #include "gmx_omp.h" #include "statutil.h" #include "copyrite.h" #include "sysstuff.h" #include "txtdump.h" #include "futil.h" #include "tpxio.h" #include "physics.h" #include "macros.h" #include "gmx_fatal.h" #include "index.h" #include "smalloc.h" #include "vec.h" #include "xvgr.h" #include "gstat.h" #include "matio.h" #include "string2.h" #include "pbc.h" #include "correl.h" #include "gmx_ana.h" #include "geminate.h" typedef short int t_E; typedef int t_EEst; #define max_hx 7 typedef int t_hx[max_hx]; #define NRHXTYPES max_hx const char *hxtypenames[NRHXTYPES] = {"n-n", "n-n+1", "n-n+2", "n-n+3", "n-n+4", "n-n+5", "n-n>6"}; #define MAXHH 4 #ifdef GMX_OPENMP #define MASTER_THREAD_ONLY(threadNr) ((threadNr) == 0) #else #define MASTER_THREAD_ONLY(threadNr) ((threadNr) == (threadNr)) #endif /* -----------------------------------------*/ enum { gr0, gr1, grI, grNR }; enum { hbNo, hbDist, hbHB, hbNR, hbR2 }; enum { noDA, ACC, DON, DA, INGROUP }; enum { NN_NULL, NN_NONE, NN_BINARY, NN_1_over_r3, NN_dipole, NN_NR }; static const char *grpnames[grNR] = {"0", "1", "I" }; static gmx_bool bDebug = FALSE; #define HB_NO 0 #define HB_YES 1<<0 #define HB_INS 1<<1 #define HB_YESINS HB_YES|HB_INS #define HB_NR (1<<2) #define MAXHYDRO 4 #define ISHB(h) (((h) & 2) == 2) #define ISDIST(h) (((h) & 1) == 1) #define ISDIST2(h) (((h) & 4) == 4) #define ISACC(h) (((h) & 1) == 1) #define ISDON(h) (((h) & 2) == 2) #define ISINGRP(h) (((h) & 4) == 4) typedef struct { int nr; int maxnr; atom_id *atoms; } t_ncell; typedef struct { t_ncell d[grNR]; t_ncell a[grNR]; } t_gridcell; typedef int t_icell[grNR]; typedef atom_id h_id[MAXHYDRO]; typedef struct { int history[MAXHYDRO]; /* Has this hbond existed ever? If so as hbDist or hbHB or both. * Result is stored as a bitmap (1 = hbDist) || (2 = hbHB) */ /* Bitmask array which tells whether a hbond is present * at a given time. Either of these may be NULL */ int n0; /* First frame a HB was found */ int nframes, maxframes; /* Amount of frames in this hbond */ unsigned int **h; unsigned int **g; /* See Xu and Berne, JPCB 105 (2001), p. 11929. We define the * function g(t) = [1-h(t)] H(t) where H(t) is one when the donor- * acceptor distance is less than the user-specified distance (typically * 0.35 nm). */ } t_hbond; typedef struct { int nra, max_nra; atom_id *acc; /* Atom numbers of the acceptors */ int *grp; /* Group index */ int *aptr; /* Map atom number to acceptor index */ } t_acceptors; typedef struct { int nrd, max_nrd; int *don; /* Atom numbers of the donors */ int *grp; /* Group index */ int *dptr; /* Map atom number to donor index */ int *nhydro; /* Number of hydrogens for each donor */ h_id *hydro; /* The atom numbers of the hydrogens */ h_id *nhbonds; /* The number of HBs per H at current */ } t_donors; /* Tune this to match memory requirements. It should be a signed integer type, e.g. signed char.*/ #define PSTYPE int typedef struct { int len; /* The length of frame and p. */ int *frame; /* The frames at which transitio*/ PSTYPE *p; } t_pShift; typedef struct { /* Periodicity history. Used for the reversible geminate recombination. */ t_pShift **pHist; /* The periodicity of every hbond in t_hbdata->hbmap: * pHist[d][a]. We can safely assume that the same * periodic shift holds for all hydrogens of a da-pair. * * Nowadays it only stores TRANSITIONS, and not the shift at every frame. * That saves a LOT of memory, an hopefully kills a mysterious bug where * pHist gets contaminated. */ PSTYPE nper; /* The length of p2i */ ivec *p2i; /* Maps integer to periodic shift for a pair.*/ matrix P; /* Projection matrix to find the box shifts. */ int gemtype; /* enumerated type */ } t_gemPeriod; typedef struct { int nframes; int *Etot; /* Total energy for each frame */ t_E ****E; /* Energy estimate for [d][a][h][frame-n0] */ } t_hbEmap; typedef struct { gmx_bool bHBmap, bDAnr, bGem; int wordlen; /* The following arrays are nframes long */ int nframes, max_frames, maxhydro; int *nhb, *ndist; h_id *n_bound; real *time; t_icell *danr; t_hx *nhx; /* These structures are initialized from the topology at start up */ t_donors d; t_acceptors a; /* This holds a matrix with all possible hydrogen bonds */ int nrhb, nrdist; t_hbond ***hbmap; #ifdef HAVE_NN_LOOPS t_hbEmap hbE; #endif /* For parallelization reasons this will have to be a pointer. * Otherwise discrepancies may arise between the periodicity data * seen by different threads. */ t_gemPeriod *per; } t_hbdata; static void clearPshift(t_pShift *pShift) { if (pShift->len > 0) { sfree(pShift->p); sfree(pShift->frame); pShift->len = 0; } } static void calcBoxProjection(matrix B, matrix P) { const int vp[] = {XX, YY, ZZ}; int i, j; int m, n; matrix M, N, U; for (i = 0; i < 3; i++) { m = vp[i]; for (j = 0; j < 3; j++) { n = vp[j]; U[m][n] = i == j ? 1 : 0; } } m_inv(B, M); for (i = 0; i < 3; i++) { m = vp[i]; mvmul(M, U[m], P[m]); } transpose(P, N); } static void calcBoxDistance(matrix P, rvec d, ivec ibd) { /* returns integer distance in box coordinates. * P is the projection matrix from cartesian coordinates * obtained with calcBoxProjection(). */ int i; rvec bd; mvmul(P, d, bd); /* extend it by 0.5 in all directions since (int) rounds toward 0.*/ for (i = 0; i < 3; i++) { bd[i] = bd[i] + (bd[i] < 0 ? -0.5 : 0.5); } ibd[XX] = (int)bd[XX]; ibd[YY] = (int)bd[YY]; ibd[ZZ] = (int)bd[ZZ]; } /* Changed argument 'bMerge' into 'oneHB' below, * since -contact should cause maxhydro to be 1, * not just -merge. * - Erik Marklund May 29, 2006 */ static PSTYPE periodicIndex(ivec r, t_gemPeriod *per, gmx_bool daSwap) { /* Try to merge hbonds on the fly. That means that if the * acceptor and donor are mergable, then: * 1) store the hb-info so that acceptor id > donor id, * 2) add the periodic shift in pairs, so that [-x,-y,-z] is * stored in per.p2i[] whenever acceptor id < donor id. * Note that [0,0,0] should already be the first element of per.p2i * by the time this function is called. */ /* daSwap is TRUE if the donor and acceptor were swapped. * If so, then the negative vector should be used. */ PSTYPE i; if (per->p2i == NULL || per->nper == 0) { gmx_fatal(FARGS, "'per' not initialized properly."); } for (i = 0; i < per->nper; i++) { if (r[XX] == per->p2i[i][XX] && r[YY] == per->p2i[i][YY] && r[ZZ] == per->p2i[i][ZZ]) { return i; } } /* Not found apparently. Add it to the list! */ /* printf("New shift found: %i,%i,%i\n",r[XX],r[YY],r[ZZ]); */ #pragma omp critical { if (!per->p2i) { fprintf(stderr, "p2i not initialized. This shouldn't happen!\n"); snew(per->p2i, 1); } else { srenew(per->p2i, per->nper+2); } copy_ivec(r, per->p2i[per->nper]); (per->nper)++; /* Add the mirror too. It's rather likely that it'll be needed. */ per->p2i[per->nper][XX] = -r[XX]; per->p2i[per->nper][YY] = -r[YY]; per->p2i[per->nper][ZZ] = -r[ZZ]; (per->nper)++; } /* omp critical */ return per->nper - 1 - (daSwap ? 0 : 1); } static t_hbdata *mk_hbdata(gmx_bool bHBmap, gmx_bool bDAnr, gmx_bool oneHB, gmx_bool bGem, int gemmode) { t_hbdata *hb; snew(hb, 1); hb->wordlen = 8*sizeof(unsigned int); hb->bHBmap = bHBmap; hb->bDAnr = bDAnr; hb->bGem = bGem; if (oneHB) { hb->maxhydro = 1; } else { hb->maxhydro = MAXHYDRO; } snew(hb->per, 1); hb->per->gemtype = bGem ? gemmode : 0; return hb; } static void mk_hbmap(t_hbdata *hb, gmx_bool bTwo) { int i, j; snew(hb->hbmap, hb->d.nrd); for (i = 0; (i < hb->d.nrd); i++) { snew(hb->hbmap[i], hb->a.nra); if (hb->hbmap[i] == NULL) { gmx_fatal(FARGS, "Could not allocate enough memory for hbmap"); } for (j = 0; (j > hb->a.nra); j++) { hb->hbmap[i][j] = NULL; } } } /* Consider redoing pHist so that is only stores transitions between * periodicities and not the periodicity for all frames. This eats heaps of memory. */ static void mk_per(t_hbdata *hb) { int i, j; if (hb->bGem) { snew(hb->per->pHist, hb->d.nrd); for (i = 0; i < hb->d.nrd; i++) { snew(hb->per->pHist[i], hb->a.nra); if (hb->per->pHist[i] == NULL) { gmx_fatal(FARGS, "Could not allocate enough memory for per->pHist"); } for (j = 0; j < hb->a.nra; j++) { clearPshift(&(hb->per->pHist[i][j])); } } /* add the [0,0,0] shift to element 0 of p2i. */ snew(hb->per->p2i, 1); clear_ivec(hb->per->p2i[0]); hb->per->nper = 1; } } #ifdef HAVE_NN_LOOPS static void mk_hbEmap (t_hbdata *hb, int n0) { int i, j, k; hb->hbE.E = NULL; hb->hbE.nframes = 0; snew(hb->hbE.E, hb->d.nrd); for (i = 0; i < hb->d.nrd; i++) { snew(hb->hbE.E[i], hb->a.nra); for (j = 0; j < hb->a.nra; j++) { snew(hb->hbE.E[i][j], MAXHYDRO); for (k = 0; k < MAXHYDRO; k++) { hb->hbE.E[i][j][k] = NULL; } } } hb->hbE.Etot = NULL; } static void free_hbEmap (t_hbdata *hb) { int i, j, k; for (i = 0; i < hb->d.nrd; i++) { for (j = 0; j < hb->a.nra; j++) { for (k = 0; k < MAXHYDRO; k++) { sfree(hb->hbE.E[i][j][k]); } sfree(hb->hbE.E[i][j]); } sfree(hb->hbE.E[i]); } sfree(hb->hbE.E); sfree(hb->hbE.Etot); } static void addFramesNN(t_hbdata *hb, int frame) { #define DELTAFRAMES_HBE 10 int d, a, h, nframes; if (frame >= hb->hbE.nframes) { nframes = hb->hbE.nframes + DELTAFRAMES_HBE; srenew(hb->hbE.Etot, nframes); for (d = 0; d < hb->d.nrd; d++) { for (a = 0; a < hb->a.nra; a++) { for (h = 0; h < hb->d.nhydro[d]; h++) { srenew(hb->hbE.E[d][a][h], nframes); } } } hb->hbE.nframes += DELTAFRAMES_HBE; } } static t_E calcHbEnergy(int d, int a, int h, rvec x[], t_EEst EEst, matrix box, rvec hbox, t_donors *donors) { /* d - donor atom * a - acceptor atom * h - hydrogen * alpha - angle between dipoles * x[] - atomic positions * EEst - the type of energy estimate (see enum in hbplugin.h) * box - the box vectors \ * hbox - half box lengths _These two are only needed for the pbc correction */ t_E E; rvec dist; rvec dipole[2], xmol[3], xmean[2]; int i; real r, realE; if (d == a) { /* Self-interaction */ return NONSENSE_E; } switch (EEst) { case NN_BINARY: /* This is a simple binary existence function that sets E=1 whenever * the distance between the oxygens is equal too or less than 0.35 nm. */ rvec_sub(x[d], x[a], dist); pbc_correct_gem(dist, box, hbox); if (norm(dist) <= 0.35) { E = 1; } else { E = 0; } break; case NN_1_over_r3: /* Negative potential energy of a dipole. * E = -cos(alpha) * 1/r^3 */ copy_rvec(x[d], xmol[0]); /* donor */ copy_rvec(x[donors->hydro[donors->dptr[d]][0]], xmol[1]); /* hydrogen */ copy_rvec(x[donors->hydro[donors->dptr[d]][1]], xmol[2]); /* hydrogen */ svmul(15.9994*(1/1.008), xmol[0], xmean[0]); rvec_inc(xmean[0], xmol[1]); rvec_inc(xmean[0], xmol[2]); for (i = 0; i < 3; i++) { xmean[0][i] /= (15.9994 + 1.008 + 1.008)/1.008; } /* Assumes that all acceptors are also donors. */ copy_rvec(x[a], xmol[0]); /* acceptor */ copy_rvec(x[donors->hydro[donors->dptr[a]][0]], xmol[1]); /* hydrogen */ copy_rvec(x[donors->hydro[donors->dptr[a]][1]], xmol[2]); /* hydrogen */ svmul(15.9994*(1/1.008), xmol[0], xmean[1]); rvec_inc(xmean[1], xmol[1]); rvec_inc(xmean[1], xmol[2]); for (i = 0; i < 3; i++) { xmean[1][i] /= (15.9994 + 1.008 + 1.008)/1.008; } rvec_sub(xmean[0], xmean[1], dist); pbc_correct_gem(dist, box, hbox); r = norm(dist); realE = pow(r, -3.0); E = (t_E)(SCALEFACTOR_E * realE); break; case NN_dipole: /* Negative potential energy of a (unpolarizable) dipole. * E = -cos(alpha) * 1/r^3 */ clear_rvec(dipole[1]); clear_rvec(dipole[0]); copy_rvec(x[d], xmol[0]); /* donor */ copy_rvec(x[donors->hydro[donors->dptr[d]][0]], xmol[1]); /* hydrogen */ copy_rvec(x[donors->hydro[donors->dptr[d]][1]], xmol[2]); /* hydrogen */ rvec_inc(dipole[0], xmol[1]); rvec_inc(dipole[0], xmol[2]); for (i = 0; i < 3; i++) { dipole[0][i] *= 0.5; } rvec_dec(dipole[0], xmol[0]); svmul(15.9994*(1/1.008), xmol[0], xmean[0]); rvec_inc(xmean[0], xmol[1]); rvec_inc(xmean[0], xmol[2]); for (i = 0; i < 3; i++) { xmean[0][i] /= (15.9994 + 1.008 + 1.008)/1.008; } /* Assumes that all acceptors are also donors. */ copy_rvec(x[a], xmol[0]); /* acceptor */ copy_rvec(x[donors->hydro[donors->dptr[a]][0]], xmol[1]); /* hydrogen */ copy_rvec(x[donors->hydro[donors->dptr[a]][2]], xmol[2]); /* hydrogen */ rvec_inc(dipole[1], xmol[1]); rvec_inc(dipole[1], xmol[2]); for (i = 0; i < 3; i++) { dipole[1][i] *= 0.5; } rvec_dec(dipole[1], xmol[0]); svmul(15.9994*(1/1.008), xmol[0], xmean[1]); rvec_inc(xmean[1], xmol[1]); rvec_inc(xmean[1], xmol[2]); for (i = 0; i < 3; i++) { xmean[1][i] /= (15.9994 + 1.008 + 1.008)/1.008; } rvec_sub(xmean[0], xmean[1], dist); pbc_correct_gem(dist, box, hbox); r = norm(dist); double cosalpha = cos_angle(dipole[0], dipole[1]); realE = cosalpha * pow(r, -3.0); E = (t_E)(SCALEFACTOR_E * realE); break; default: printf("Can't do that type of energy estimate: %i\n.", EEst); E = NONSENSE_E; } return E; } static void storeHbEnergy(t_hbdata *hb, int d, int a, int h, t_E E, int frame) { /* hb - hbond data structure d - donor a - acceptor h - hydrogen E - estimate of the energy frame - the current frame. */ /* Store the estimated energy */ if (E == NONSENSE_E) { E = 0; } hb->hbE.E[d][a][h][frame] = E; #pragma omp critical { hb->hbE.Etot[frame] += E; } } #endif /* HAVE_NN_LOOPS */ /* Finds -v[] in the periodicity index */ static int findMirror(PSTYPE p, ivec v[], PSTYPE nper) { PSTYPE i; ivec u; for (i = 0; i < nper; i++) { if (v[i][XX] == -(v[p][XX]) && v[i][YY] == -(v[p][YY]) && v[i][ZZ] == -(v[p][ZZ])) { return (int)i; } } printf("Couldn't find mirror of [%i, %i, %i], index \n", v[p][XX], v[p][YY], v[p][ZZ]); return -1; } static void add_frames(t_hbdata *hb, int nframes) { int i, j, k, l; if (nframes >= hb->max_frames) { hb->max_frames += 4096; srenew(hb->time, hb->max_frames); srenew(hb->nhb, hb->max_frames); srenew(hb->ndist, hb->max_frames); srenew(hb->n_bound, hb->max_frames); srenew(hb->nhx, hb->max_frames); if (hb->bDAnr) { srenew(hb->danr, hb->max_frames); } } hb->nframes = nframes; } #define OFFSET(frame) (frame / 32) #define MASK(frame) (1 << (frame % 32)) static void _set_hb(unsigned int hbexist[], unsigned int frame, gmx_bool bValue) { if (bValue) { hbexist[OFFSET(frame)] |= MASK(frame); } else { hbexist[OFFSET(frame)] &= ~MASK(frame); } } static gmx_bool is_hb(unsigned int hbexist[], int frame) { return ((hbexist[OFFSET(frame)] & MASK(frame)) != 0) ? 1 : 0; } static void set_hb(t_hbdata *hb, int id, int ih, int ia, int frame, int ihb) { unsigned int *ghptr = NULL; if (ihb == hbHB) { ghptr = hb->hbmap[id][ia]->h[ih]; } else if (ihb == hbDist) { ghptr = hb->hbmap[id][ia]->g[ih]; } else { gmx_fatal(FARGS, "Incomprehensible iValue %d in set_hb", ihb); } _set_hb(ghptr, frame-hb->hbmap[id][ia]->n0, TRUE); } static void addPshift(t_pShift *pHist, PSTYPE p, int frame) { if (pHist->len == 0) { snew(pHist->frame, 1); snew(pHist->p, 1); pHist->len = 1; pHist->frame[0] = frame; pHist->p[0] = p; return; } else if (pHist->p[pHist->len-1] != p) { pHist->len++; srenew(pHist->frame, pHist->len); srenew(pHist->p, pHist->len); pHist->frame[pHist->len-1] = frame; pHist->p[pHist->len-1] = p; } /* Otherwise, there is no transition. */ return; } static PSTYPE getPshift(t_pShift pHist, int frame) { int f, i; if (pHist.len == 0 || (pHist.len > 0 && pHist.frame[0] > frame)) { return -1; } for (i = 0; i < pHist.len; i++) { f = pHist.frame[i]; if (f == frame) { return pHist.p[i]; } if (f > frame) { return pHist.p[i-1]; } } /* It seems that frame is after the last periodic transition. Return the last periodicity. */ return pHist.p[pHist.len-1]; } static void add_ff(t_hbdata *hbd, int id, int h, int ia, int frame, int ihb, PSTYPE p) { int i, j, n; t_hbond *hb = hbd->hbmap[id][ia]; int maxhydro = min(hbd->maxhydro, hbd->d.nhydro[id]); int wlen = hbd->wordlen; int delta = 32*wlen; gmx_bool bGem = hbd->bGem; if (!hb->h[0]) { hb->n0 = frame; hb->maxframes = delta; for (i = 0; (i < maxhydro); i++) { snew(hb->h[i], hb->maxframes/wlen); snew(hb->g[i], hb->maxframes/wlen); } } else { hb->nframes = frame-hb->n0; /* We need a while loop here because hbonds may be returning * after a long time. */ while (hb->nframes >= hb->maxframes) { n = hb->maxframes + delta; for (i = 0; (i < maxhydro); i++) { srenew(hb->h[i], n/wlen); srenew(hb->g[i], n/wlen); for (j = hb->maxframes/wlen; (j < n/wlen); j++) { hb->h[i][j] = 0; hb->g[i][j] = 0; } } hb->maxframes = n; } } if (frame >= 0) { set_hb(hbd, id, h, ia, frame, ihb); if (bGem) { if (p >= hbd->per->nper) { gmx_fatal(FARGS, "invalid shift: p=%u, nper=%u", p, hbd->per->nper); } else { addPshift(&(hbd->per->pHist[id][ia]), p, frame); } } } } static void inc_nhbonds(t_donors *ddd, int d, int h) { int j; int dptr = ddd->dptr[d]; for (j = 0; (j < ddd->nhydro[dptr]); j++) { if (ddd->hydro[dptr][j] == h) { ddd->nhbonds[dptr][j]++; break; } } if (j == ddd->nhydro[dptr]) { gmx_fatal(FARGS, "No such hydrogen %d on donor %d\n", h+1, d+1); } } static int _acceptor_index(t_acceptors *a, int grp, atom_id i, const char *file, int line) { int ai = a->aptr[i]; if (a->grp[ai] != grp) { if (debug && bDebug) { fprintf(debug, "Acc. group inconsist.. grp[%d] = %d, grp = %d (%s, %d)\n", ai, a->grp[ai], grp, file, line); } return NOTSET; } else { return ai; } } #define acceptor_index(a, grp, i) _acceptor_index(a, grp, i, __FILE__, __LINE__) static int _donor_index(t_donors *d, int grp, atom_id i, const char *file, int line) { int di = d->dptr[i]; if (di == NOTSET) { return NOTSET; } if (d->grp[di] != grp) { if (debug && bDebug) { fprintf(debug, "Don. group inconsist.. grp[%d] = %d, grp = %d (%s, %d)\n", di, d->grp[di], grp, file, line); } return NOTSET; } else { return di; } } #define donor_index(d, grp, i) _donor_index(d, grp, i, __FILE__, __LINE__) static gmx_bool isInterchangable(t_hbdata *hb, int d, int a, int grpa, int grpd) { /* g_hbond doesn't allow overlapping groups */ if (grpa != grpd) { return FALSE; } return donor_index(&hb->d, grpd, a) != NOTSET && acceptor_index(&hb->a, grpa, d) != NOTSET; } static void add_hbond(t_hbdata *hb, int d, int a, int h, int grpd, int grpa, int frame, gmx_bool bMerge, int ihb, gmx_bool bContact, PSTYPE p) { int k, id, ia, hh; gmx_bool daSwap = FALSE; if ((id = hb->d.dptr[d]) == NOTSET) { gmx_fatal(FARGS, "No donor atom %d", d+1); } else if (grpd != hb->d.grp[id]) { gmx_fatal(FARGS, "Inconsistent donor groups, %d iso %d, atom %d", grpd, hb->d.grp[id], d+1); } if ((ia = hb->a.aptr[a]) == NOTSET) { gmx_fatal(FARGS, "No acceptor atom %d", a+1); } else if (grpa != hb->a.grp[ia]) { gmx_fatal(FARGS, "Inconsistent acceptor groups, %d iso %d, atom %d", grpa, hb->a.grp[ia], a+1); } if (bMerge) { if (isInterchangable(hb, d, a, grpd, grpa) && d > a) /* Then swap identity so that the id of d is lower then that of a. * * This should really be redundant by now, as is_hbond() now ought to return * hbNo in the cases where this conditional is TRUE. */ { daSwap = TRUE; k = d; d = a; a = k; /* Now repeat donor/acc check. */ if ((id = hb->d.dptr[d]) == NOTSET) { gmx_fatal(FARGS, "No donor atom %d", d+1); } else if (grpd != hb->d.grp[id]) { gmx_fatal(FARGS, "Inconsistent donor groups, %d iso %d, atom %d", grpd, hb->d.grp[id], d+1); } if ((ia = hb->a.aptr[a]) == NOTSET) { gmx_fatal(FARGS, "No acceptor atom %d", a+1); } else if (grpa != hb->a.grp[ia]) { gmx_fatal(FARGS, "Inconsistent acceptor groups, %d iso %d, atom %d", grpa, hb->a.grp[ia], a+1); } } } if (hb->hbmap) { /* Loop over hydrogens to find which hydrogen is in this particular HB */ if ((ihb == hbHB) && !bMerge && !bContact) { for (k = 0; (k < hb->d.nhydro[id]); k++) { if (hb->d.hydro[id][k] == h) { break; } } if (k == hb->d.nhydro[id]) { gmx_fatal(FARGS, "Donor %d does not have hydrogen %d (a = %d)", d+1, h+1, a+1); } } else { k = 0; } if (hb->bHBmap) { #pragma omp critical { if (hb->hbmap[id][ia] == NULL) { snew(hb->hbmap[id][ia], 1); snew(hb->hbmap[id][ia]->h, hb->maxhydro); snew(hb->hbmap[id][ia]->g, hb->maxhydro); } add_ff(hb, id, k, ia, frame, ihb, p); } } /* Strange construction with frame >=0 is a relic from old code * for selected hbond analysis. It may be necessary again if that * is made to work again. */ if (frame >= 0) { hh = hb->hbmap[id][ia]->history[k]; if (ihb == hbHB) { hb->nhb[frame]++; if (!(ISHB(hh))) { hb->hbmap[id][ia]->history[k] = hh | 2; hb->nrhb++; } } else { if (ihb == hbDist) { hb->ndist[frame]++; if (!(ISDIST(hh))) { hb->hbmap[id][ia]->history[k] = hh | 1; hb->nrdist++; } } } } } else { if (frame >= 0) { if (ihb == hbHB) { hb->nhb[frame]++; } else { if (ihb == hbDist) { hb->ndist[frame]++; } } } } if (bMerge && daSwap) { h = hb->d.hydro[id][0]; } /* Increment number if HBonds per H */ if (ihb == hbHB && !bContact) { inc_nhbonds(&(hb->d), d, h); } } static char *mkatomname(t_atoms *atoms, int i) { static char buf[32]; int rnr; rnr = atoms->atom[i].resind; sprintf(buf, "%4s%d%-4s", *atoms->resinfo[rnr].name, atoms->resinfo[rnr].nr, *atoms->atomname[i]); return buf; } static void gen_datable(atom_id *index, int isize, unsigned char *datable, int natoms) { /* Generates table of all atoms and sets the ingroup bit for atoms in index[] */ int i; for (i = 0; i < isize; i++) { if (index[i] >= natoms) { gmx_fatal(FARGS, "Atom has index %d larger than number of atoms %d.", index[i], natoms); } datable[index[i]] |= INGROUP; } } static void clear_datable_grp(unsigned char *datable, int size) { /* Clears group information from the table */ int i; const char mask = !(char)INGROUP; if (size > 0) { for (i = 0; i < size; i++) { datable[i] &= mask; } } } static void add_acc(t_acceptors *a, int ia, int grp) { if (a->nra >= a->max_nra) { a->max_nra += 16; srenew(a->acc, a->max_nra); srenew(a->grp, a->max_nra); } a->grp[a->nra] = grp; a->acc[a->nra++] = ia; } static void search_acceptors(t_topology *top, int isize, atom_id *index, t_acceptors *a, int grp, gmx_bool bNitAcc, gmx_bool bContact, gmx_bool bDoIt, unsigned char *datable) { int i, n; if (bDoIt) { for (i = 0; (i < isize); i++) { n = index[i]; if ((bContact || (((*top->atoms.atomname[n])[0] == 'O') || (bNitAcc && ((*top->atoms.atomname[n])[0] == 'N')))) && ISINGRP(datable[n])) { datable[n] |= ACC; /* set the atom's acceptor flag in datable. */ add_acc(a, n, grp); } } } snew(a->aptr, top->atoms.nr); for (i = 0; (i < top->atoms.nr); i++) { a->aptr[i] = NOTSET; } for (i = 0; (i < a->nra); i++) { a->aptr[a->acc[i]] = i; } } static void add_h2d(int id, int ih, t_donors *ddd) { int i; for (i = 0; (i < ddd->nhydro[id]); i++) { if (ddd->hydro[id][i] == ih) { printf("Hm. This isn't the first time I found this donor (%d,%d)\n", ddd->don[id], ih); break; } } if (i == ddd->nhydro[id]) { if (ddd->nhydro[id] >= MAXHYDRO) { gmx_fatal(FARGS, "Donor %d has more than %d hydrogens!", ddd->don[id], MAXHYDRO); } ddd->hydro[id][i] = ih; ddd->nhydro[id]++; } } static void add_dh(t_donors *ddd, int id, int ih, int grp, unsigned char *datable) { int i; if (ISDON(datable[id]) || !datable) { if (ddd->dptr[id] == NOTSET) /* New donor */ { i = ddd->nrd; ddd->dptr[id] = i; } else { i = ddd->dptr[id]; } if (i == ddd->nrd) { if (ddd->nrd >= ddd->max_nrd) { ddd->max_nrd += 128; srenew(ddd->don, ddd->max_nrd); srenew(ddd->nhydro, ddd->max_nrd); srenew(ddd->hydro, ddd->max_nrd); srenew(ddd->nhbonds, ddd->max_nrd); srenew(ddd->grp, ddd->max_nrd); } ddd->don[ddd->nrd] = id; ddd->nhydro[ddd->nrd] = 0; ddd->grp[ddd->nrd] = grp; ddd->nrd++; } else { ddd->don[i] = id; } add_h2d(i, ih, ddd); } else if (datable) { printf("Warning: Atom %d is not in the d/a-table!\n", id); } } static void search_donors(t_topology *top, int isize, atom_id *index, t_donors *ddd, int grp, gmx_bool bContact, gmx_bool bDoIt, unsigned char *datable) { int i, j, nra, n; t_functype func_type; t_ilist *interaction; atom_id nr1, nr2, nr3; gmx_bool stop; if (!ddd->dptr) { snew(ddd->dptr, top->atoms.nr); for (i = 0; (i < top->atoms.nr); i++) { ddd->dptr[i] = NOTSET; } } if (bContact) { if (bDoIt) { for (i = 0; (i < isize); i++) { datable[index[i]] |= DON; add_dh(ddd, index[i], -1, grp, datable); } } } else { for (func_type = 0; (func_type < F_NRE); func_type++) { interaction = &(top->idef.il[func_type]); if (func_type == F_POSRES) { /* The ilist looks strange for posre. Bug in grompp? * We don't need posre interactions for hbonds anyway.*/ continue; } for (i = 0; i < interaction->nr; i += interaction_function[top->idef.functype[interaction->iatoms[i]]].nratoms+1) { /* next function */ if (func_type != top->idef.functype[interaction->iatoms[i]]) { fprintf(stderr, "Error in func_type %s", interaction_function[func_type].longname); continue; } /* check out this functype */ if (func_type == F_SETTLE) { nr1 = interaction->iatoms[i+1]; nr2 = interaction->iatoms[i+2]; nr3 = interaction->iatoms[i+3]; if (ISINGRP(datable[nr1])) { if (ISINGRP(datable[nr2])) { datable[nr1] |= DON; add_dh(ddd, nr1, nr1+1, grp, datable); } if (ISINGRP(datable[nr3])) { datable[nr1] |= DON; add_dh(ddd, nr1, nr1+2, grp, datable); } } } else if (IS_CHEMBOND(func_type)) { for (j = 0; j < 2; j++) { nr1 = interaction->iatoms[i+1+j]; nr2 = interaction->iatoms[i+2-j]; if ((*top->atoms.atomname[nr1][0] == 'H') && ((*top->atoms.atomname[nr2][0] == 'O') || (*top->atoms.atomname[nr2][0] == 'N')) && ISINGRP(datable[nr1]) && ISINGRP(datable[nr2])) { datable[nr2] |= DON; add_dh(ddd, nr2, nr1, grp, datable); } } } } } #ifdef SAFEVSITES for (func_type = 0; func_type < F_NRE; func_type++) { interaction = &top->idef.il[func_type]; for (i = 0; i < interaction->nr; i += interaction_function[top->idef.functype[interaction->iatoms[i]]].nratoms+1) { /* next function */ if (func_type != top->idef.functype[interaction->iatoms[i]]) { gmx_incons("function type in search_donors"); } if (interaction_function[func_type].flags & IF_VSITE) { nr1 = interaction->iatoms[i+1]; if (*top->atoms.atomname[nr1][0] == 'H') { nr2 = nr1-1; stop = FALSE; while (!stop && ( *top->atoms.atomname[nr2][0] == 'H')) { if (nr2) { nr2--; } else { stop = TRUE; } } if (!stop && ( ( *top->atoms.atomname[nr2][0] == 'O') || ( *top->atoms.atomname[nr2][0] == 'N') ) && ISINGRP(datable[nr1]) && ISINGRP(datable[nr2])) { datable[nr2] |= DON; add_dh(ddd, nr2, nr1, grp, datable); } } } } } #endif } } static t_gridcell ***init_grid(gmx_bool bBox, rvec box[], real rcut, ivec ngrid) { t_gridcell ***grid; int i, y, z; if (bBox) { for (i = 0; i < DIM; i++) { ngrid[i] = (box[i][i]/(1.2*rcut)); } } if (!bBox || (ngrid[XX] < 3) || (ngrid[YY] < 3) || (ngrid[ZZ] < 3) ) { for (i = 0; i < DIM; i++) { ngrid[i] = 1; } } else { printf("\nWill do grid-seach on %dx%dx%d grid, rcut=%g\n", ngrid[XX], ngrid[YY], ngrid[ZZ], rcut); } snew(grid, ngrid[ZZ]); for (z = 0; z < ngrid[ZZ]; z++) { snew((grid)[z], ngrid[YY]); for (y = 0; y < ngrid[YY]; y++) { snew((grid)[z][y], ngrid[XX]); } } return grid; } static void reset_nhbonds(t_donors *ddd) { int i, j; for (i = 0; (i < ddd->nrd); i++) { for (j = 0; (j < MAXHH); j++) { ddd->nhbonds[i][j] = 0; } } } void pbc_correct_gem(rvec dx, matrix box, rvec hbox); static void build_grid(t_hbdata *hb, rvec x[], rvec xshell, gmx_bool bBox, matrix box, rvec hbox, real rcut, real rshell, ivec ngrid, t_gridcell ***grid) { int i, m, gr, xi, yi, zi, nr; atom_id *ad; ivec grididx; rvec invdelta, dshell, xtemp = {0, 0, 0}; t_ncell *newgrid; gmx_bool bDoRshell, bInShell, bAcc; real rshell2 = 0; int gx, gy, gz; int dum = -1; bDoRshell = (rshell > 0); rshell2 = sqr(rshell); bInShell = TRUE; #define DBB(x) if (debug && bDebug) fprintf(debug, "build_grid, line %d, %s = %d\n", __LINE__,#x, x) DBB(dum); for (m = 0; m < DIM; m++) { hbox[m] = box[m][m]*0.5; if (bBox) { invdelta[m] = ngrid[m]/box[m][m]; if (1/invdelta[m] < rcut) { gmx_fatal(FARGS, "Your computational box has shrunk too much.\n" "%s can not handle this situation, sorry.\n", ShortProgram()); } } else { invdelta[m] = 0; } } grididx[XX] = 0; grididx[YY] = 0; grididx[ZZ] = 0; DBB(dum); /* resetting atom counts */ for (gr = 0; (gr < grNR); gr++) { for (zi = 0; zi < ngrid[ZZ]; zi++) { for (yi = 0; yi < ngrid[YY]; yi++) { for (xi = 0; xi < ngrid[XX]; xi++) { grid[zi][yi][xi].d[gr].nr = 0; grid[zi][yi][xi].a[gr].nr = 0; } } } DBB(dum); /* put atoms in grid cells */ for (bAcc = FALSE; (bAcc <= TRUE); bAcc++) { if (bAcc) { nr = hb->a.nra; ad = hb->a.acc; } else { nr = hb->d.nrd; ad = hb->d.don; } DBB(bAcc); for (i = 0; (i < nr); i++) { /* check if we are inside the shell */ /* if bDoRshell=FALSE then bInShell=TRUE always */ DBB(i); if (bDoRshell) { bInShell = TRUE; rvec_sub(x[ad[i]], xshell, dshell); if (bBox) { if (FALSE && !hb->bGem) { for (m = DIM-1; m >= 0 && bInShell; m--) { if (dshell[m] < -hbox[m]) { rvec_inc(dshell, box[m]); } else if (dshell[m] >= hbox[m]) { dshell[m] -= 2*hbox[m]; } /* if we're outside the cube, we're outside the sphere also! */ if ( (dshell[m] > rshell) || (-dshell[m] > rshell) ) { bInShell = FALSE; } } } else { gmx_bool bDone = FALSE; while (!bDone) { bDone = TRUE; for (m = DIM-1; m >= 0 && bInShell; m--) { if (dshell[m] < -hbox[m]) { bDone = FALSE; rvec_inc(dshell, box[m]); } if (dshell[m] >= hbox[m]) { bDone = FALSE; dshell[m] -= 2*hbox[m]; } } } for (m = DIM-1; m >= 0 && bInShell; m--) { /* if we're outside the cube, we're outside the sphere also! */ if ( (dshell[m] > rshell) || (-dshell[m] > rshell) ) { bInShell = FALSE; } } } } /* if we're inside the cube, check if we're inside the sphere */ if (bInShell) { bInShell = norm2(dshell) < rshell2; } } DBB(i); if (bInShell) { if (bBox) { if (hb->bGem) { copy_rvec(x[ad[i]], xtemp); } pbc_correct_gem(x[ad[i]], box, hbox); } for (m = DIM-1; m >= 0; m--) { if (TRUE || !hb->bGem) { /* put atom in the box */ while (x[ad[i]][m] < 0) { rvec_inc(x[ad[i]], box[m]); } while (x[ad[i]][m] >= box[m][m]) { rvec_dec(x[ad[i]], box[m]); } } /* determine grid index of atom */ grididx[m] = x[ad[i]][m]*invdelta[m]; grididx[m] = (grididx[m]+ngrid[m]) % ngrid[m]; } if (hb->bGem) { copy_rvec(xtemp, x[ad[i]]); /* copy back */ } gx = grididx[XX]; gy = grididx[YY]; gz = grididx[ZZ]; range_check(gx, 0, ngrid[XX]); range_check(gy, 0, ngrid[YY]); range_check(gz, 0, ngrid[ZZ]); DBB(gx); DBB(gy); DBB(gz); /* add atom to grid cell */ if (bAcc) { newgrid = &(grid[gz][gy][gx].a[gr]); } else { newgrid = &(grid[gz][gy][gx].d[gr]); } if (newgrid->nr >= newgrid->maxnr) { newgrid->maxnr += 10; DBB(newgrid->maxnr); srenew(newgrid->atoms, newgrid->maxnr); } DBB(newgrid->nr); newgrid->atoms[newgrid->nr] = ad[i]; newgrid->nr++; } } } } } static void count_da_grid(ivec ngrid, t_gridcell ***grid, t_icell danr) { int gr, xi, yi, zi; for (gr = 0; (gr < grNR); gr++) { danr[gr] = 0; for (zi = 0; zi < ngrid[ZZ]; zi++) { for (yi = 0; yi < ngrid[YY]; yi++) { for (xi = 0; xi < ngrid[XX]; xi++) { danr[gr] += grid[zi][yi][xi].d[gr].nr; } } } } } /* The grid loop. * Without a box, the grid is 1x1x1, so all loops are 1 long. * With a rectangular box (bTric==FALSE) all loops are 3 long. * With a triclinic box all loops are 3 long, except when a cell is * located next to one of the box edges which is not parallel to the * x/y-plane, in that case all cells in a line or layer are searched. * This could be implemented slightly more efficient, but the code * would get much more complicated. */ static inline gmx_bool grid_loop_begin(int n, int x, gmx_bool bTric, gmx_bool bEdge) { return ((n == 1) ? x : bTric && bEdge ? 0 : (x-1)); } static inline gmx_bool grid_loop_end(int n, int x, gmx_bool bTric, gmx_bool bEdge) { return ((n == 1) ? x : bTric && bEdge ? (n-1) : (x+1)); } static inline int grid_mod(int j, int n) { return (j+n) % (n); } static void dump_grid(FILE *fp, ivec ngrid, t_gridcell ***grid) { int gr, x, y, z, sum[grNR]; fprintf(fp, "grid %dx%dx%d\n", ngrid[XX], ngrid[YY], ngrid[ZZ]); for (gr = 0; gr < grNR; gr++) { sum[gr] = 0; fprintf(fp, "GROUP %d (%s)\n", gr, grpnames[gr]); for (z = 0; z < ngrid[ZZ]; z += 2) { fprintf(fp, "Z=%d,%d\n", z, z+1); for (y = 0; y < ngrid[YY]; y++) { for (x = 0; x < ngrid[XX]; x++) { fprintf(fp, "%3d", grid[x][y][z].d[gr].nr); sum[gr] += grid[z][y][x].d[gr].nr; fprintf(fp, "%3d", grid[x][y][z].a[gr].nr); sum[gr] += grid[z][y][x].a[gr].nr; } fprintf(fp, " | "); if ( (z+1) < ngrid[ZZ]) { for (x = 0; x < ngrid[XX]; x++) { fprintf(fp, "%3d", grid[z+1][y][x].d[gr].nr); sum[gr] += grid[z+1][y][x].d[gr].nr; fprintf(fp, "%3d", grid[z+1][y][x].a[gr].nr); sum[gr] += grid[z+1][y][x].a[gr].nr; } } fprintf(fp, "\n"); } } } fprintf(fp, "TOTALS:"); for (gr = 0; gr < grNR; gr++) { fprintf(fp, " %d=%d", gr, sum[gr]); } fprintf(fp, "\n"); } /* New GMX record! 5 * in a row. Congratulations! * Sorry, only four left. */ static void free_grid(ivec ngrid, t_gridcell ****grid) { int y, z; t_gridcell ***g = *grid; for (z = 0; z < ngrid[ZZ]; z++) { for (y = 0; y < ngrid[YY]; y++) { sfree(g[z][y]); } sfree(g[z]); } sfree(g); g = NULL; } void pbc_correct_gem(rvec dx, matrix box, rvec hbox) { int m; gmx_bool bDone = FALSE; while (!bDone) { bDone = TRUE; for (m = DIM-1; m >= 0; m--) { if (dx[m] < -hbox[m]) { bDone = FALSE; rvec_inc(dx, box[m]); } if (dx[m] >= hbox[m]) { bDone = FALSE; rvec_dec(dx, box[m]); } } } } /* Added argument r2cut, changed contact and implemented * use of second cut-off. * - Erik Marklund, June 29, 2006 */ static int is_hbond(t_hbdata *hb, int grpd, int grpa, int d, int a, real rcut, real r2cut, real ccut, rvec x[], gmx_bool bBox, matrix box, rvec hbox, real *d_ha, real *ang, gmx_bool bDA, int *hhh, gmx_bool bContact, gmx_bool bMerge, PSTYPE *p) { int h, hh, id, ja, ihb; rvec r_da, r_ha, r_dh, r = {0, 0, 0}; ivec ri; real rc2, r2c2, rda2, rha2, ca; gmx_bool HAinrange = FALSE; /* If !bDA. Needed for returning hbDist in a correct way. */ gmx_bool daSwap = FALSE; if (d == a) { return hbNo; } if (((id = donor_index(&hb->d, grpd, d)) == NOTSET) || ((ja = acceptor_index(&hb->a, grpa, a)) == NOTSET)) { return hbNo; } rc2 = rcut*rcut; r2c2 = r2cut*r2cut; rvec_sub(x[d], x[a], r_da); /* Insert projection code here */ if (bMerge && d > a && isInterchangable(hb, d, a, grpd, grpa)) { /* Then this hbond/contact will be found again, or it has already been found. */ /*return hbNo;*/ } if (bBox) { if (d > a && bMerge && isInterchangable(hb, d, a, grpd, grpa)) /* acceptor is also a donor and vice versa? */ { /* return hbNo; */ daSwap = TRUE; /* If so, then their history should be filed with donor and acceptor swapped. */ } if (hb->bGem) { copy_rvec(r_da, r); /* Save this for later */ pbc_correct_gem(r_da, box, hbox); } else { pbc_correct_gem(r_da, box, hbox); } } rda2 = iprod(r_da, r_da); if (bContact) { if (daSwap && grpa == grpd) { return hbNo; } if (rda2 <= rc2) { if (hb->bGem) { calcBoxDistance(hb->per->P, r, ri); *p = periodicIndex(ri, hb->per, daSwap); /* find (or add) periodicity index. */ } return hbHB; } else if (rda2 < r2c2) { return hbDist; } else { return hbNo; } } *hhh = NOTSET; if (bDA && (rda2 > rc2)) { return hbNo; } for (h = 0; (h < hb->d.nhydro[id]); h++) { hh = hb->d.hydro[id][h]; rha2 = rc2+1; if (!bDA) { rvec_sub(x[hh], x[a], r_ha); if (bBox) { pbc_correct_gem(r_ha, box, hbox); } rha2 = iprod(r_ha, r_ha); } if (hb->bGem) { calcBoxDistance(hb->per->P, r, ri); *p = periodicIndex(ri, hb->per, daSwap); /* find periodicity index. */ } if (bDA || (!bDA && (rha2 <= rc2))) { rvec_sub(x[d], x[hh], r_dh); if (bBox) { pbc_correct_gem(r_dh, box, hbox); } if (!bDA) { HAinrange = TRUE; } ca = cos_angle(r_dh, r_da); /* if angle is smaller, cos is larger */ if (ca >= ccut) { *hhh = hh; *d_ha = sqrt(bDA ? rda2 : rha2); *ang = acos(ca); return hbHB; } } } if (bDA || (!bDA && HAinrange)) { return hbDist; } else { return hbNo; } } /* Fixed previously undiscovered bug in the merge code, where the last frame of each hbond disappears. - Erik Marklund, June 1, 2006 */ /* Added the following arguments: * ptmp[] - temporary periodicity hisory * a1 - identity of first acceptor/donor * a2 - identity of second acceptor/donor * - Erik Marklund, FEB 20 2010 */ /* Merging is now done on the fly, so do_merge is most likely obsolete now. * Will do some more testing before removing the function entirely. * - Erik Marklund, MAY 10 2010 */ static void do_merge(t_hbdata *hb, int ntmp, unsigned int htmp[], unsigned int gtmp[], PSTYPE ptmp[], t_hbond *hb0, t_hbond *hb1, int a1, int a2) { /* Here we need to make sure we're treating periodicity in * the right way for the geminate recombination kinetics. */ int m, mm, n00, n01, nn0, nnframes; PSTYPE pm; t_pShift *pShift; /* Decide where to start from when merging */ n00 = hb0->n0; n01 = hb1->n0; nn0 = min(n00, n01); nnframes = max(n00 + hb0->nframes, n01 + hb1->nframes) - nn0; /* Initiate tmp arrays */ for (m = 0; (m < ntmp); m++) { htmp[m] = 0; gtmp[m] = 0; ptmp[m] = 0; } /* Fill tmp arrays with values due to first HB */ /* Once again '<' had to be replaced with '<=' to catch the last frame in which the hbond appears. - Erik Marklund, June 1, 2006 */ for (m = 0; (m <= hb0->nframes); m++) { mm = m+n00-nn0; htmp[mm] = is_hb(hb0->h[0], m); if (hb->bGem) { pm = getPshift(hb->per->pHist[a1][a2], m+hb0->n0); if (pm > hb->per->nper) { gmx_fatal(FARGS, "Illegal shift!"); } else { ptmp[mm] = pm; /*hb->per->pHist[a1][a2][m];*/ } } } /* If we're doing geminate recompbination we usually don't need the distances. * Let's save some memory and time. */ if (TRUE || !hb->bGem || hb->per->gemtype == gemAD) { for (m = 0; (m <= hb0->nframes); m++) { mm = m+n00-nn0; gtmp[mm] = is_hb(hb0->g[0], m); } } /* Next HB */ for (m = 0; (m <= hb1->nframes); m++) { mm = m+n01-nn0; htmp[mm] = htmp[mm] || is_hb(hb1->h[0], m); gtmp[mm] = gtmp[mm] || is_hb(hb1->g[0], m); if (hb->bGem /* && ptmp[mm] != 0 */) { /* If this hbond has been seen before with donor and acceptor swapped, * then we need to find the mirrored (*-1) periodicity vector to truely * merge the hbond history. */ pm = findMirror(getPshift(hb->per->pHist[a2][a1], m+hb1->n0), hb->per->p2i, hb->per->nper); /* Store index of mirror */ if (pm > hb->per->nper) { gmx_fatal(FARGS, "Illegal shift!"); } ptmp[mm] = pm; } } /* Reallocate target array */ if (nnframes > hb0->maxframes) { srenew(hb0->h[0], 4+nnframes/hb->wordlen); srenew(hb0->g[0], 4+nnframes/hb->wordlen); } if (NULL != hb->per->pHist) { clearPshift(&(hb->per->pHist[a1][a2])); } /* Copy temp array to target array */ for (m = 0; (m <= nnframes); m++) { _set_hb(hb0->h[0], m, htmp[m]); _set_hb(hb0->g[0], m, gtmp[m]); if (hb->bGem) { addPshift(&(hb->per->pHist[a1][a2]), ptmp[m], m+nn0); } } /* Set scalar variables */ hb0->n0 = nn0; hb0->maxframes = nnframes; } /* Added argument bContact for nicer output. * Erik Marklund, June 29, 2006 */ static void merge_hb(t_hbdata *hb, gmx_bool bTwo, gmx_bool bContact) { int i, inrnew, indnew, j, ii, jj, m, id, ia, grp, ogrp, ntmp; unsigned int *htmp, *gtmp; PSTYPE *ptmp; t_hbond *hb0, *hb1; inrnew = hb->nrhb; indnew = hb->nrdist; /* Check whether donors are also acceptors */ printf("Merging hbonds with Acceptor and Donor swapped\n"); ntmp = 2*hb->max_frames; snew(gtmp, ntmp); snew(htmp, ntmp); snew(ptmp, ntmp); for (i = 0; (i < hb->d.nrd); i++) { fprintf(stderr, "\r%d/%d", i+1, hb->d.nrd); id = hb->d.don[i]; ii = hb->a.aptr[id]; for (j = 0; (j < hb->a.nra); j++) { ia = hb->a.acc[j]; jj = hb->d.dptr[ia]; if ((id != ia) && (ii != NOTSET) && (jj != NOTSET) && (!bTwo || (bTwo && (hb->d.grp[i] != hb->a.grp[j])))) { hb0 = hb->hbmap[i][j]; hb1 = hb->hbmap[jj][ii]; if (hb0 && hb1 && ISHB(hb0->history[0]) && ISHB(hb1->history[0])) { do_merge(hb, ntmp, htmp, gtmp, ptmp, hb0, hb1, i, j); if (ISHB(hb1->history[0])) { inrnew--; } else if (ISDIST(hb1->history[0])) { indnew--; } else if (bContact) { gmx_incons("No contact history"); } else { gmx_incons("Neither hydrogen bond nor distance"); } sfree(hb1->h[0]); sfree(hb1->g[0]); if (hb->bGem) { clearPshift(&(hb->per->pHist[jj][ii])); } hb1->h[0] = NULL; hb1->g[0] = NULL; hb1->history[0] = hbNo; } } } } fprintf(stderr, "\n"); printf("- Reduced number of hbonds from %d to %d\n", hb->nrhb, inrnew); printf("- Reduced number of distances from %d to %d\n", hb->nrdist, indnew); hb->nrhb = inrnew; hb->nrdist = indnew; sfree(gtmp); sfree(htmp); sfree(ptmp); } static void do_nhb_dist(FILE *fp, t_hbdata *hb, real t) { int i, j, k, n_bound[MAXHH], nbtot; h_id nhb; /* Set array to 0 */ for (k = 0; (k < MAXHH); k++) { n_bound[k] = 0; } /* Loop over possible donors */ for (i = 0; (i < hb->d.nrd); i++) { for (j = 0; (j < hb->d.nhydro[i]); j++) { n_bound[hb->d.nhbonds[i][j]]++; } } fprintf(fp, "%12.5e", t); nbtot = 0; for (k = 0; (k < MAXHH); k++) { fprintf(fp, " %8d", n_bound[k]); nbtot += n_bound[k]*k; } fprintf(fp, " %8d\n", nbtot); } /* Added argument bContact in do_hblife(...). Also * added support for -contact in function body. * - Erik Marklund, May 31, 2006 */ /* Changed the contact code slightly. * - Erik Marklund, June 29, 2006 */ static void do_hblife(const char *fn, t_hbdata *hb, gmx_bool bMerge, gmx_bool bContact, const output_env_t oenv) { FILE *fp; const char *leg[] = { "p(t)", "t p(t)" }; int *histo; int i, j, j0, k, m, nh, ihb, ohb, nhydro, ndump = 0; int nframes = hb->nframes; unsigned int **h; real t, x1, dt; double sum, integral; t_hbond *hbh; snew(h, hb->maxhydro); snew(histo, nframes+1); /* Total number of hbonds analyzed here */ for (i = 0; (i < hb->d.nrd); i++) { for (k = 0; (k < hb->a.nra); k++) { hbh = hb->hbmap[i][k]; if (hbh) { if (bMerge) { if (hbh->h[0]) { h[0] = hbh->h[0]; nhydro = 1; } else { nhydro = 0; } } else { nhydro = 0; for (m = 0; (m < hb->maxhydro); m++) { if (hbh->h[m]) { h[nhydro++] = bContact ? hbh->g[m] : hbh->h[m]; } } } for (nh = 0; (nh < nhydro); nh++) { ohb = 0; j0 = 0; /* Changed '<' into '<=' below, just like I did in the hbm-output-loop in the main code. - Erik Marklund, May 31, 2006 */ for (j = 0; (j <= hbh->nframes); j++) { ihb = is_hb(h[nh], j); if (debug && (ndump < 10)) { fprintf(debug, "%5d %5d\n", j, ihb); } if (ihb != ohb) { if (ihb) { j0 = j; } else { histo[j-j0]++; } ohb = ihb; } } ndump++; } } } } fprintf(stderr, "\n"); if (bContact) { fp = xvgropen(fn, "Uninterrupted contact lifetime", output_env_get_xvgr_tlabel(oenv), "()", oenv); } else { fp = xvgropen(fn, "Uninterrupted hydrogen bond lifetime", output_env_get_xvgr_tlabel(oenv), "()", oenv); } xvgr_legend(fp, asize(leg), leg, oenv); j0 = nframes-1; while ((j0 > 0) && (histo[j0] == 0)) { j0--; } sum = 0; for (i = 0; (i <= j0); i++) { sum += histo[i]; } dt = hb->time[1]-hb->time[0]; sum = dt*sum; integral = 0; for (i = 1; (i <= j0); i++) { t = hb->time[i] - hb->time[0] - 0.5*dt; x1 = t*histo[i]/sum; fprintf(fp, "%8.3f %10.3e %10.3e\n", t, histo[i]/sum, x1); integral += x1; } integral *= dt; ffclose(fp); printf("%s lifetime = %.2f ps\n", bContact ? "Contact" : "HB", integral); printf("Note that the lifetime obtained in this manner is close to useless\n"); printf("Use the -ac option instead and check the Forward lifetime\n"); please_cite(stdout, "Spoel2006b"); sfree(h); sfree(histo); } /* Changed argument bMerge into oneHB to handle contacts properly. * - Erik Marklund, June 29, 2006 */ static void dump_ac(t_hbdata *hb, gmx_bool oneHB, int nDump) { FILE *fp; int i, j, k, m, nd, ihb, idist; int nframes = hb->nframes; gmx_bool bPrint; t_hbond *hbh; if (nDump <= 0) { return; } fp = ffopen("debug-ac.xvg", "w"); for (j = 0; (j < nframes); j++) { fprintf(fp, "%10.3f", hb->time[j]); for (i = nd = 0; (i < hb->d.nrd) && (nd < nDump); i++) { for (k = 0; (k < hb->a.nra) && (nd < nDump); k++) { bPrint = FALSE; ihb = idist = 0; hbh = hb->hbmap[i][k]; if (oneHB) { if (hbh->h[0]) { ihb = is_hb(hbh->h[0], j); idist = is_hb(hbh->g[0], j); bPrint = TRUE; } } else { for (m = 0; (m < hb->maxhydro) && !ihb; m++) { ihb = ihb || ((hbh->h[m]) && is_hb(hbh->h[m], j)); idist = idist || ((hbh->g[m]) && is_hb(hbh->g[m], j)); } /* This is not correct! */ /* What isn't correct? -Erik M */ bPrint = TRUE; } if (bPrint) { fprintf(fp, " %1d-%1d", ihb, idist); nd++; } } } fprintf(fp, "\n"); } ffclose(fp); } static real calc_dg(real tau, real temp) { real kbt; kbt = BOLTZ*temp; if (tau <= 0) { return -666; } else { return kbt*log(kbt*tau/PLANCK); } } typedef struct { int n0, n1, nparams, ndelta; real kkk[2]; real *t, *ct, *nt, *kt, *sigma_ct, *sigma_nt, *sigma_kt; } t_luzar; #ifdef HAVE_LIBGSL #include <gsl/gsl_multimin.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_version.h> static double my_f(const gsl_vector *v, void *params) { t_luzar *tl = (t_luzar *)params; int i; double tol = 1e-16, chi2 = 0; double di; real k, kp; for (i = 0; (i < tl->nparams); i++) { tl->kkk[i] = gsl_vector_get(v, i); } k = tl->kkk[0]; kp = tl->kkk[1]; for (i = tl->n0; (i < tl->n1); i += tl->ndelta) { di = sqr(k*tl->sigma_ct[i]) + sqr(kp*tl->sigma_nt[i]) + sqr(tl->sigma_kt[i]); /*di = 1;*/ if (di > tol) { chi2 += sqr(k*tl->ct[i]-kp*tl->nt[i]-tl->kt[i])/di; } else { fprintf(stderr, "WARNING: sigma_ct = %g, sigma_nt = %g, sigma_kt = %g\n" "di = %g k = %g kp = %g\n", tl->sigma_ct[i], tl->sigma_nt[i], tl->sigma_kt[i], di, k, kp); } } #ifdef DEBUG chi2 = 0.3*sqr(k-0.6)+0.7*sqr(kp-1.3); #endif return chi2; } static real optimize_luzar_parameters(FILE *fp, t_luzar *tl, int maxiter, real tol) { real size, d2; int iter = 0; int status = 0; int i; const gsl_multimin_fminimizer_type *T; gsl_multimin_fminimizer *s; gsl_vector *x, *dx; gsl_multimin_function my_func; my_func.f = &my_f; my_func.n = tl->nparams; my_func.params = (void *) tl; /* Starting point */ x = gsl_vector_alloc (my_func.n); for (i = 0; (i < my_func.n); i++) { gsl_vector_set (x, i, tl->kkk[i]); } /* Step size, different for each of the parameters */ dx = gsl_vector_alloc (my_func.n); for (i = 0; (i < my_func.n); i++) { gsl_vector_set (dx, i, 0.01*tl->kkk[i]); } T = gsl_multimin_fminimizer_nmsimplex; s = gsl_multimin_fminimizer_alloc (T, my_func.n); gsl_multimin_fminimizer_set (s, &my_func, x, dx); gsl_vector_free (x); gsl_vector_free (dx); if (fp) { fprintf(fp, "%5s %12s %12s %12s %12s\n", "Iter", "k", "kp", "NM Size", "Chi2"); } do { iter++; status = gsl_multimin_fminimizer_iterate (s); if (status != 0) { gmx_fatal(FARGS, "Something went wrong in the iteration in minimizer %s", gsl_multimin_fminimizer_name(s)); } d2 = gsl_multimin_fminimizer_minimum(s); size = gsl_multimin_fminimizer_size(s); status = gsl_multimin_test_size(size, tol); if (status == GSL_SUCCESS) { if (fp) { fprintf(fp, "Minimum found using %s at:\n", gsl_multimin_fminimizer_name(s)); } } if (fp) { fprintf(fp, "%5d", iter); for (i = 0; (i < my_func.n); i++) { fprintf(fp, " %12.4e", gsl_vector_get (s->x, i)); } fprintf (fp, " %12.4e %12.4e\n", size, d2); } } while ((status == GSL_CONTINUE) && (iter < maxiter)); gsl_multimin_fminimizer_free (s); return d2; } static real quality_of_fit(real chi2, int N) { return gsl_sf_gamma_inc_Q((N-2)/2.0, chi2/2.0); } #else static real optimize_luzar_parameters(FILE *fp, t_luzar *tl, int maxiter, real tol) { fprintf(stderr, "This program needs the GNU scientific library to work.\n"); return -1; } static real quality_of_fit(real chi2, int N) { fprintf(stderr, "This program needs the GNU scientific library to work.\n"); return -1; } #endif static real compute_weighted_rates(int n, real t[], real ct[], real nt[], real kt[], real sigma_ct[], real sigma_nt[], real sigma_kt[], real *k, real *kp, real *sigma_k, real *sigma_kp, real fit_start) { #define NK 10 int i, j; t_luzar tl; real kkk = 0, kkp = 0, kk2 = 0, kp2 = 0, chi2; *sigma_k = 0; *sigma_kp = 0; for (i = 0; (i < n); i++) { if (t[i] >= fit_start) { break; } } tl.n0 = i; tl.n1 = n; tl.nparams = 2; tl.ndelta = 1; tl.t = t; tl.ct = ct; tl.nt = nt; tl.kt = kt; tl.sigma_ct = sigma_ct; tl.sigma_nt = sigma_nt; tl.sigma_kt = sigma_kt; tl.kkk[0] = *k; tl.kkk[1] = *kp; chi2 = optimize_luzar_parameters(debug, &tl, 1000, 1e-3); *k = tl.kkk[0]; *kp = tl.kkk[1] = *kp; tl.ndelta = NK; for (j = 0; (j < NK); j++) { (void) optimize_luzar_parameters(debug, &tl, 1000, 1e-3); kkk += tl.kkk[0]; kkp += tl.kkk[1]; kk2 += sqr(tl.kkk[0]); kp2 += sqr(tl.kkk[1]); tl.n0++; } *sigma_k = sqrt(kk2/NK - sqr(kkk/NK)); *sigma_kp = sqrt(kp2/NK - sqr(kkp/NK)); return chi2; } static void smooth_tail(int n, real t[], real c[], real sigma_c[], real start, const output_env_t oenv) { FILE *fp; real e_1, fitparm[4]; int i; e_1 = exp(-1); for (i = 0; (i < n); i++) { if (c[i] < e_1) { break; } } if (i < n) { fitparm[0] = t[i]; } else { fitparm[0] = 10; } fitparm[1] = 0.95; do_lmfit(n, c, sigma_c, 0, t, start, t[n-1], oenv, bDebugMode(), effnEXP2, fitparm, 0); } void analyse_corr(int n, real t[], real ct[], real nt[], real kt[], real sigma_ct[], real sigma_nt[], real sigma_kt[], real fit_start, real temp, real smooth_tail_start, const output_env_t oenv) { int i0, i; real k = 1, kp = 1, kow = 1; real Q = 0, chi22, chi2, dg, dgp, tau_hb, dtau, tau_rlx, e_1, dt, sigma_k, sigma_kp, ddg; double tmp, sn2 = 0, sc2 = 0, sk2 = 0, scn = 0, sck = 0, snk = 0; gmx_bool bError = (sigma_ct != NULL) && (sigma_nt != NULL) && (sigma_kt != NULL); if (smooth_tail_start >= 0) { smooth_tail(n, t, ct, sigma_ct, smooth_tail_start, oenv); smooth_tail(n, t, nt, sigma_nt, smooth_tail_start, oenv); smooth_tail(n, t, kt, sigma_kt, smooth_tail_start, oenv); } for (i0 = 0; (i0 < n-2) && ((t[i0]-t[0]) < fit_start); i0++) { ; } if (i0 < n-2) { for (i = i0; (i < n); i++) { sc2 += sqr(ct[i]); sn2 += sqr(nt[i]); sk2 += sqr(kt[i]); sck += ct[i]*kt[i]; snk += nt[i]*kt[i]; scn += ct[i]*nt[i]; } printf("Hydrogen bond thermodynamics at T = %g K\n", temp); tmp = (sn2*sc2-sqr(scn)); if ((tmp > 0) && (sn2 > 0)) { k = (sn2*sck-scn*snk)/tmp; kp = (k*scn-snk)/sn2; if (bError) { chi2 = 0; for (i = i0; (i < n); i++) { chi2 += sqr(k*ct[i]-kp*nt[i]-kt[i]); } chi22 = compute_weighted_rates(n, t, ct, nt, kt, sigma_ct, sigma_nt, sigma_kt, &k, &kp, &sigma_k, &sigma_kp, fit_start); Q = quality_of_fit(chi2, 2); ddg = BOLTZ*temp*sigma_k/k; printf("Fitting paramaters chi^2 = %10g, Quality of fit = %10g\n", chi2, Q); printf("The Rate and Delta G are followed by an error estimate\n"); printf("----------------------------------------------------------\n" "Type Rate (1/ps) Sigma Time (ps) DG (kJ/mol) Sigma\n"); printf("Forward %10.3f %6.2f %8.3f %10.3f %6.2f\n", k, sigma_k, 1/k, calc_dg(1/k, temp), ddg); ddg = BOLTZ*temp*sigma_kp/kp; printf("Backward %10.3f %6.2f %8.3f %10.3f %6.2f\n", kp, sigma_kp, 1/kp, calc_dg(1/kp, temp), ddg); } else { chi2 = 0; for (i = i0; (i < n); i++) { chi2 += sqr(k*ct[i]-kp*nt[i]-kt[i]); } printf("Fitting parameters chi^2 = %10g\nQ = %10g\n", chi2, Q); printf("--------------------------------------------------\n" "Type Rate (1/ps) Time (ps) DG (kJ/mol) Chi^2\n"); printf("Forward %10.3f %8.3f %10.3f %10g\n", k, 1/k, calc_dg(1/k, temp), chi2); printf("Backward %10.3f %8.3f %10.3f\n", kp, 1/kp, calc_dg(1/kp, temp)); } } if (sc2 > 0) { kow = 2*sck/sc2; printf("One-way %10.3f %s%8.3f %10.3f\n", kow, bError ? " " : "", 1/kow, calc_dg(1/kow, temp)); } else { printf(" - Numerical problems computing HB thermodynamics:\n" "sc2 = %g sn2 = %g sk2 = %g sck = %g snk = %g scn = %g\n", sc2, sn2, sk2, sck, snk, scn); } /* Determine integral of the correlation function */ tau_hb = evaluate_integral(n, t, ct, NULL, (t[n-1]-t[0])/2, &dtau); printf("Integral %10.3f %s%8.3f %10.3f\n", 1/tau_hb, bError ? " " : "", tau_hb, calc_dg(tau_hb, temp)); e_1 = exp(-1); for (i = 0; (i < n-2); i++) { if ((ct[i] > e_1) && (ct[i+1] <= e_1)) { break; } } if (i < n-2) { /* Determine tau_relax from linear interpolation */ tau_rlx = t[i]-t[0] + (e_1-ct[i])*(t[i+1]-t[i])/(ct[i+1]-ct[i]); printf("Relaxation %10.3f %8.3f %s%10.3f\n", 1/tau_rlx, tau_rlx, bError ? " " : "", calc_dg(tau_rlx, temp)); } } else { printf("Correlation functions too short to compute thermodynamics\n"); } } void compute_derivative(int nn, real x[], real y[], real dydx[]) { int j; /* Compute k(t) = dc(t)/dt */ for (j = 1; (j < nn-1); j++) { dydx[j] = (y[j+1]-y[j-1])/(x[j+1]-x[j-1]); } /* Extrapolate endpoints */ dydx[0] = 2*dydx[1] - dydx[2]; dydx[nn-1] = 2*dydx[nn-2] - dydx[nn-3]; } static void parallel_print(int *data, int nThreads) { /* This prints the donors on which each tread is currently working. */ int i; fprintf(stderr, "\r"); for (i = 0; i < nThreads; i++) { fprintf(stderr, "%-7i", data[i]); } } static void normalizeACF(real *ct, real *gt, int nhb, int len) { real ct_fac, gt_fac; int i; /* Xu and Berne use the same normalization constant */ ct_fac = 1.0/ct[0]; gt_fac = (nhb == 0) ? 0 : 1.0/(real)nhb; printf("Normalization for c(t) = %g for gh(t) = %g\n", ct_fac, gt_fac); for (i = 0; i < len; i++) { ct[i] *= ct_fac; if (gt != NULL) { gt[i] *= gt_fac; } } } /* Added argument bContact in do_hbac(...). Also * added support for -contact in the actual code. * - Erik Marklund, May 31, 2006 */ /* Changed contact code and added argument R2 * - Erik Marklund, June 29, 2006 */ static void do_hbac(const char *fn, t_hbdata *hb, int nDump, gmx_bool bMerge, gmx_bool bContact, real fit_start, real temp, gmx_bool R2, real smooth_tail_start, const output_env_t oenv, t_gemParams *params, const char *gemType, int nThreads, const int NN, const gmx_bool bBallistic, const gmx_bool bGemFit) { FILE *fp; int i, j, k, m, n, o, nd, ihb, idist, n2, nn, iter, nSets; const char *legNN[] = { "Ac(t)", "Ac'(t)" }; static char **legGem; const char *legLuzar[] = { "Ac\\sfin sys\\v{}\\z{}(t)", "Ac(t)", "Cc\\scontact,hb\\v{}\\z{}(t)", "-dAc\\sfs\\v{}\\z{}/dt" }; gmx_bool bNorm = FALSE, bOMP = FALSE; double nhb = 0; int nhbi = 0; real *rhbex = NULL, *ht, *gt, *ght, *dght, *kt; real *ct, *p_ct, tail, tail2, dtail, ct_fac, ght_fac, *cct; const real tol = 1e-3; int nframes = hb->nframes, nf; unsigned int **h = NULL, **g = NULL; int nh, nhbonds, nhydro, ngh; t_hbond *hbh; PSTYPE p, *pfound = NULL, np; t_pShift *pHist; int *ptimes = NULL, *poff = NULL, anhb, n0, mMax = INT_MIN; real **rHbExGem = NULL; gmx_bool c; int acType; t_E *E; double *ctdouble, *timedouble, *fittedct; double fittolerance = 0.1; int *dondata = NULL, thisThread; enum { AC_NONE, AC_NN, AC_GEM, AC_LUZAR }; #ifdef GMX_OPENMP bOMP = TRUE; #else bOMP = FALSE; #endif printf("Doing autocorrelation "); /* Decide what kind of ACF calculations to do. */ if (NN > NN_NONE && NN < NN_NR) { #ifdef HAVE_NN_LOOPS acType = AC_NN; printf("using the energy estimate.\n"); #else acType = AC_NONE; printf("Can't do the NN-loop. Yet.\n"); #endif } else if (hb->bGem) { acType = AC_GEM; printf("according to the reversible geminate recombination model by Omer Markowitch.\n"); nSets = 1 + (bBallistic ? 1 : 0) + (bGemFit ? 1 : 0); snew(legGem, nSets); for (i = 0; i < nSets; i++) { snew(legGem[i], 128); } sprintf(legGem[0], "Ac\\s%s\\v{}\\z{}(t)", gemType); if (bBallistic) { sprintf(legGem[1], "Ac'(t)"); } if (bGemFit) { sprintf(legGem[(bBallistic ? 3 : 2)], "Ac\\s%s,fit\\v{}\\z{}(t)", gemType); } } else { acType = AC_LUZAR; printf("according to the theory of Luzar and Chandler.\n"); } fflush(stdout); /* build hbexist matrix in reals for autocorr */ /* Allocate memory for computing ACF (rhbex) and aggregating the ACF (ct) */ n2 = 1; while (n2 < nframes) { n2 *= 2; } nn = nframes/2; if (acType != AC_NN || bOMP) { snew(h, hb->maxhydro); snew(g, hb->maxhydro); } /* Dump hbonds for debugging */ dump_ac(hb, bMerge || bContact, nDump); /* Total number of hbonds analyzed here */ nhbonds = 0; ngh = 0; anhb = 0; if (acType != AC_LUZAR && bOMP) { nThreads = min((nThreads <= 0) ? INT_MAX : nThreads, gmx_omp_get_max_threads()); gmx_omp_set_num_threads(nThreads); snew(dondata, nThreads); for (i = 0; i < nThreads; i++) { dondata[i] = -1; } printf("ACF calculations parallelized with OpenMP using %i threads.\n" "Expect close to linear scaling over this donor-loop.\n", nThreads); fflush(stdout); fprintf(stderr, "Donors: [thread no]\n"); { char tmpstr[7]; for (i = 0; i < nThreads; i++) { snprintf(tmpstr, 7, "[%i]", i); fprintf(stderr, "%-7s", tmpstr); } } fprintf(stderr, "\n"); } /* Build the ACF according to acType */ switch (acType) { case AC_NN: #ifdef HAVE_NN_LOOPS /* Here we're using the estimated energy for the hydrogen bonds. */ snew(ct, nn); #pragma omp parallel \ private(i, j, k, nh, E, rhbex, thisThread) \ default(shared) { #pragma omp barrier thisThread = gmx_omp_get_thread_num(); rhbex = NULL; snew(rhbex, n2); memset(rhbex, 0, n2*sizeof(real)); /* Trust no-one, not even malloc()! */ #pragma omp barrier #pragma omp for schedule (dynamic) for (i = 0; i < hb->d.nrd; i++) /* loop over donors */ { if (bOMP) { #pragma omp critical { dondata[thisThread] = i; parallel_print(dondata, nThreads); } } else { fprintf(stderr, "\r %i", i); } for (j = 0; j < hb->a.nra; j++) /* loop over acceptors */ { for (nh = 0; nh < hb->d.nhydro[i]; nh++) /* loop over donors' hydrogens */ { E = hb->hbE.E[i][j][nh]; if (E != NULL) { for (k = 0; k < nframes; k++) { if (E[k] != NONSENSE_E) { rhbex[k] = (real)E[k]; } } low_do_autocorr(NULL, oenv, NULL, nframes, 1, -1, &(rhbex), hb->time[1]-hb->time[0], eacNormal, 1, FALSE, bNorm, FALSE, 0, -1, 0, 1); #pragma omp critical { for (k = 0; (k < nn); k++) { ct[k] += rhbex[k]; } } } } /* k loop */ } /* j loop */ } /* i loop */ sfree(rhbex); #pragma omp barrier } if (bOMP) { sfree(dondata); } normalizeACF(ct, NULL, 0, nn); snew(ctdouble, nn); snew(timedouble, nn); for (j = 0; j < nn; j++) { timedouble[j] = (double)(hb->time[j]); ctdouble[j] = (double)(ct[j]); } /* Remove ballistic term */ /* Ballistic component removal and fitting to the reversible geminate recombination model * will be taken out for the time being. First of all, one can remove the ballistic * component with g_analyze afterwards. Secondly, and more importantly, there are still * problems with the robustness of the fitting to the model. More work is needed. * A third reason is that we're currently using gsl for this and wish to reduce dependence * on external libraries. There are Levenberg-Marquardt and nsimplex solvers that come with * a BSD-licence that can do the job. * * - Erik Marklund, June 18 2010. */ /* if (params->ballistic/params->tDelta >= params->nExpFit*2+1) */ /* takeAwayBallistic(ctdouble, timedouble, nn, params->ballistic, params->nExpFit, params->bDt); */ /* else */ /* printf("\nNumber of data points is less than the number of parameters to fit\n." */ /* "The system is underdetermined, hence no ballistic term can be found.\n\n"); */ fp = xvgropen(fn, "Hydrogen Bond Autocorrelation", output_env_get_xvgr_tlabel(oenv), "C(t)"); xvgr_legend(fp, asize(legNN), legNN); for (j = 0; (j < nn); j++) { fprintf(fp, "%10g %10g %10g\n", hb->time[j]-hb->time[0], ct[j], ctdouble[j]); } xvgrclose(fp); sfree(ct); sfree(ctdouble); sfree(timedouble); #endif /* HAVE_NN_LOOPS */ break; /* case AC_NN */ case AC_GEM: snew(ct, 2*n2); memset(ct, 0, 2*n2*sizeof(real)); #ifndef GMX_OPENMP fprintf(stderr, "Donor:\n"); #define __ACDATA ct #else #define __ACDATA p_ct #endif #pragma omp parallel \ private(i, k, nh, hbh, pHist, h, g, n0, nf, np, j, m, \ pfound, poff, rHbExGem, p, ihb, mMax, \ thisThread, p_ct) \ default(shared) { /* ########## THE START OF THE ENORMOUS PARALLELIZED BLOCK! ########## */ h = NULL; g = NULL; thisThread = gmx_omp_get_thread_num(); snew(h, hb->maxhydro); snew(g, hb->maxhydro); mMax = INT_MIN; rHbExGem = NULL; poff = NULL; pfound = NULL; p_ct = NULL; snew(p_ct, 2*n2); memset(p_ct, 0, 2*n2*sizeof(real)); /* I'm using a chunk size of 1, since I expect \ * the overhead to be really small compared \ * to the actual calculations \ */ #pragma omp for schedule(dynamic,1) nowait for (i = 0; i < hb->d.nrd; i++) { if (bOMP) { #pragma omp critical { dondata[thisThread] = i; parallel_print(dondata, nThreads); } } else { fprintf(stderr, "\r %i", i); } for (k = 0; k < hb->a.nra; k++) { for (nh = 0; nh < ((bMerge || bContact) ? 1 : hb->d.nhydro[i]); nh++) { hbh = hb->hbmap[i][k]; if (hbh) { /* Note that if hb->per->gemtype==gemDD, then distances will be stored in * hb->hbmap[d][a].h array anyway, because the contact flag will be set. * hence, it's only with the gemAD mode that hb->hbmap[d][a].g will be used. */ pHist = &(hb->per->pHist[i][k]); if (ISHB(hbh->history[nh]) && pHist->len != 0) { { h[nh] = hbh->h[nh]; g[nh] = hb->per->gemtype == gemAD ? hbh->g[nh] : NULL; } n0 = hbh->n0; nf = hbh->nframes; /* count the number of periodic shifts encountered and store * them in separate arrays. */ np = 0; for (j = 0; j < pHist->len; j++) { p = pHist->p[j]; for (m = 0; m <= np; m++) { if (m == np) /* p not recognized in list. Add it and set up new array. */ { np++; if (np > hb->per->nper) { gmx_fatal(FARGS, "Too many pshifts. Something's utterly wrong here."); } if (m >= mMax) /* Extend the arrays. * Doing it like this, using mMax to keep track of the sizes, * eleviates the need for freeing and re-allocating the arrays * when taking on the next donor-acceptor pair */ { mMax = m; srenew(pfound, np); /* The list of found periodic shifts. */ srenew(rHbExGem, np); /* The hb existence functions (-aver_hb). */ snew(rHbExGem[m], 2*n2); srenew(poff, np); } { if (rHbExGem != NULL && rHbExGem[m] != NULL) { /* This must be done, as this array was most likey * used to store stuff in some previous iteration. */ memset(rHbExGem[m], 0, (sizeof(real)) * (2*n2)); } else { fprintf(stderr, "rHbExGem not initialized! m = %i\n", m); } } pfound[m] = p; poff[m] = -1; break; } /* m==np */ if (p == pfound[m]) { break; } } /* m: Loop over found shifts */ } /* j: Loop over shifts */ /* Now unpack and disentangle the existence funtions. */ for (j = 0; j < nf; j++) { /* i: donor, * k: acceptor * nh: hydrogen * j: time * p: periodic shift * pfound: list of periodic shifts found for this pair. * poff: list of frame offsets; that is, the first * frame a hbond has a particular periodic shift. */ p = getPshift(*pHist, j+n0); if (p != -1) { for (m = 0; m < np; m++) { if (pfound[m] == p) { break; } if (m == (np-1)) { gmx_fatal(FARGS, "Shift not found, but must be there."); } } ihb = is_hb(h[nh], j) || ((hb->per->gemtype != gemAD || j == 0) ? FALSE : is_hb(g[nh], j)); if (ihb) { if (poff[m] == -1) { poff[m] = j; /* Here's where the first hbond with shift p is, * relative to the start of h[0].*/ } if (j < poff[m]) { gmx_fatal(FARGS, "j<poff[m]"); } rHbExGem[m][j-poff[m]] += 1; } } } /* Now, build ac. */ for (m = 0; m < np; m++) { if (rHbExGem[m][0] > 0 && n0+poff[m] < nn /* && m==0 */) { low_do_autocorr(NULL, oenv, NULL, nframes, 1, -1, &(rHbExGem[m]), hb->time[1]-hb->time[0], eacNormal, 1, FALSE, bNorm, FALSE, 0, -1, 0, 1); for (j = 0; (j < nn); j++) { __ACDATA[j] += rHbExGem[m][j]; } } } /* Building of ac. */ } /* if (ISHB(...*/ } /* if (hbh) */ } /* hydrogen loop */ } /* acceptor loop */ } /* donor loop */ for (m = 0; m <= mMax; m++) { sfree(rHbExGem[m]); } sfree(pfound); sfree(poff); sfree(rHbExGem); sfree(h); sfree(g); if (bOMP) { #pragma omp critical { for (i = 0; i < nn; i++) { ct[i] += p_ct[i]; } } sfree(p_ct); } } /* ########## THE END OF THE ENORMOUS PARALLELIZED BLOCK ########## */ if (bOMP) { sfree(dondata); } normalizeACF(ct, NULL, 0, nn); fprintf(stderr, "\n\nACF successfully calculated.\n"); /* Use this part to fit to geminate recombination - JCP 129, 84505 (2008) */ snew(ctdouble, nn); snew(timedouble, nn); snew(fittedct, nn); for (j = 0; j < nn; j++) { timedouble[j] = (double)(hb->time[j]); ctdouble[j] = (double)(ct[j]); } /* Remove ballistic term */ /* Ballistic component removal and fitting to the reversible geminate recombination model * will be taken out for the time being. First of all, one can remove the ballistic * component with g_analyze afterwards. Secondly, and more importantly, there are still * problems with the robustness of the fitting to the model. More work is needed. * A third reason is that we're currently using gsl for this and wish to reduce dependence * on external libraries. There are Levenberg-Marquardt and nsimplex solvers that come with * a BSD-licence that can do the job. * * - Erik Marklund, June 18 2010. */ /* if (bBallistic) { */ /* if (params->ballistic/params->tDelta >= params->nExpFit*2+1) */ /* takeAwayBallistic(ctdouble, timedouble, nn, params->ballistic, params->nExpFit, params->bDt); */ /* else */ /* printf("\nNumber of data points is less than the number of parameters to fit\n." */ /* "The system is underdetermined, hence no ballistic term can be found.\n\n"); */ /* } */ /* if (bGemFit) */ /* fitGemRecomb(ctdouble, timedouble, &fittedct, nn, params); */ if (bContact) { fp = xvgropen(fn, "Contact Autocorrelation", output_env_get_xvgr_tlabel(oenv), "C(t)", oenv); } else { fp = xvgropen(fn, "Hydrogen Bond Autocorrelation", output_env_get_xvgr_tlabel(oenv), "C(t)", oenv); } xvgr_legend(fp, asize(legGem), (const char**)legGem, oenv); for (j = 0; (j < nn); j++) { fprintf(fp, "%10g %10g", hb->time[j]-hb->time[0], ct[j]); if (bBallistic) { fprintf(fp, " %10g", ctdouble[j]); } if (bGemFit) { fprintf(fp, " %10g", fittedct[j]); } fprintf(fp, "\n"); } xvgrclose(fp); sfree(ctdouble); sfree(timedouble); sfree(fittedct); sfree(ct); break; /* case AC_GEM */ case AC_LUZAR: snew(rhbex, 2*n2); snew(ct, 2*n2); snew(gt, 2*n2); snew(ht, 2*n2); snew(ght, 2*n2); snew(dght, 2*n2); snew(kt, nn); snew(cct, nn); for (i = 0; (i < hb->d.nrd); i++) { for (k = 0; (k < hb->a.nra); k++) { nhydro = 0; hbh = hb->hbmap[i][k]; if (hbh) { if (bMerge || bContact) { if (ISHB(hbh->history[0])) { h[0] = hbh->h[0]; g[0] = hbh->g[0]; nhydro = 1; } } else { for (m = 0; (m < hb->maxhydro); m++) { if (bContact ? ISDIST(hbh->history[m]) : ISHB(hbh->history[m])) { g[nhydro] = hbh->g[m]; h[nhydro] = hbh->h[m]; nhydro++; } } } nf = hbh->nframes; for (nh = 0; (nh < nhydro); nh++) { int nrint = bContact ? hb->nrdist : hb->nrhb; if ((((nhbonds+1) % 10) == 0) || (nhbonds+1 == nrint)) { fprintf(stderr, "\rACF %d/%d", nhbonds+1, nrint); } nhbonds++; for (j = 0; (j < nframes); j++) { /* Changed '<' into '<=' below, just like I did in the hbm-output-loop in the gmx_hbond() block. - Erik Marklund, May 31, 2006 */ if (j <= nf) { ihb = is_hb(h[nh], j); idist = is_hb(g[nh], j); } else { ihb = idist = 0; } rhbex[j] = ihb; /* For contacts: if a second cut-off is provided, use it, * otherwise use g(t) = 1-h(t) */ if (!R2 && bContact) { gt[j] = 1-ihb; } else { gt[j] = idist*(1-ihb); } ht[j] = rhbex[j]; nhb += ihb; } /* The autocorrelation function is normalized after summation only */ low_do_autocorr(NULL, oenv, NULL, nframes, 1, -1, &rhbex, hb->time[1]-hb->time[0], eacNormal, 1, FALSE, bNorm, FALSE, 0, -1, 0, 1); /* Cross correlation analysis for thermodynamics */ for (j = nframes; (j < n2); j++) { ht[j] = 0; gt[j] = 0; } cross_corr(n2, ht, gt, dght); for (j = 0; (j < nn); j++) { ct[j] += rhbex[j]; ght[j] += dght[j]; } } } } } fprintf(stderr, "\n"); sfree(h); sfree(g); normalizeACF(ct, ght, nhb, nn); /* Determine tail value for statistics */ tail = 0; tail2 = 0; for (j = nn/2; (j < nn); j++) { tail += ct[j]; tail2 += ct[j]*ct[j]; } tail /= (nn - nn/2); tail2 /= (nn - nn/2); dtail = sqrt(tail2-tail*tail); /* Check whether the ACF is long enough */ if (dtail > tol) { printf("\nWARNING: Correlation function is probably not long enough\n" "because the standard deviation in the tail of C(t) > %g\n" "Tail value (average C(t) over second half of acf): %g +/- %g\n", tol, tail, dtail); } for (j = 0; (j < nn); j++) { cct[j] = ct[j]; ct[j] = (cct[j]-tail)/(1-tail); } /* Compute negative derivative k(t) = -dc(t)/dt */ compute_derivative(nn, hb->time, ct, kt); for (j = 0; (j < nn); j++) { kt[j] = -kt[j]; } if (bContact) { fp = xvgropen(fn, "Contact Autocorrelation", output_env_get_xvgr_tlabel(oenv), "C(t)", oenv); } else { fp = xvgropen(fn, "Hydrogen Bond Autocorrelation", output_env_get_xvgr_tlabel(oenv), "C(t)", oenv); } xvgr_legend(fp, asize(legLuzar), legLuzar, oenv); for (j = 0; (j < nn); j++) { fprintf(fp, "%10g %10g %10g %10g %10g\n", hb->time[j]-hb->time[0], ct[j], cct[j], ght[j], kt[j]); } ffclose(fp); analyse_corr(nn, hb->time, ct, ght, kt, NULL, NULL, NULL, fit_start, temp, smooth_tail_start, oenv); do_view(oenv, fn, NULL); sfree(rhbex); sfree(ct); sfree(gt); sfree(ht); sfree(ght); sfree(dght); sfree(cct); sfree(kt); /* sfree(h); */ /* sfree(g); */ break; /* case AC_LUZAR */ default: gmx_fatal(FARGS, "Unrecognized type of ACF-calulation. acType = %i.", acType); } /* switch (acType) */ } static void init_hbframe(t_hbdata *hb, int nframes, real t) { int i, j, m; hb->time[nframes] = t; hb->nhb[nframes] = 0; hb->ndist[nframes] = 0; for (i = 0; (i < max_hx); i++) { hb->nhx[nframes][i] = 0; } /* Loop invalidated */ if (hb->bHBmap && 0) { for (i = 0; (i < hb->d.nrd); i++) { for (j = 0; (j < hb->a.nra); j++) { for (m = 0; (m < hb->maxhydro); m++) { if (hb->hbmap[i][j] && hb->hbmap[i][j]->h[m]) { set_hb(hb, i, m, j, nframes, HB_NO); } } } } } /*set_hb(hb->hbmap[i][j]->h[m],nframes-hb->hbmap[i][j]->n0,HB_NO);*/ } static void analyse_donor_props(const char *fn, t_hbdata *hb, int nframes, real t, const output_env_t oenv) { static FILE *fp = NULL; const char *leg[] = { "Nbound", "Nfree" }; int i, j, k, nbound, nb, nhtot; if (!fn) { return; } if (!fp) { fp = xvgropen(fn, "Donor properties", output_env_get_xvgr_tlabel(oenv), "Number", oenv); xvgr_legend(fp, asize(leg), leg, oenv); } nbound = 0; nhtot = 0; for (i = 0; (i < hb->d.nrd); i++) { for (k = 0; (k < hb->d.nhydro[i]); k++) { nb = 0; nhtot++; for (j = 0; (j < hb->a.nra) && (nb == 0); j++) { if (hb->hbmap[i][j] && hb->hbmap[i][j]->h[k] && is_hb(hb->hbmap[i][j]->h[k], nframes)) { nb = 1; } } nbound += nb; } } fprintf(fp, "%10.3e %6d %6d\n", t, nbound, nhtot-nbound); } static void dump_hbmap(t_hbdata *hb, int nfile, t_filenm fnm[], gmx_bool bTwo, gmx_bool bContact, int isize[], int *index[], char *grpnames[], t_atoms *atoms) { FILE *fp, *fplog; int ddd, hhh, aaa, i, j, k, m, grp; char ds[32], hs[32], as[32]; gmx_bool first; fp = opt2FILE("-hbn", nfile, fnm, "w"); if (opt2bSet("-g", nfile, fnm)) { fplog = ffopen(opt2fn("-g", nfile, fnm), "w"); fprintf(fplog, "# %10s %12s %12s\n", "Donor", "Hydrogen", "Acceptor"); } else { fplog = NULL; } for (grp = gr0; grp <= (bTwo ? gr1 : gr0); grp++) { fprintf(fp, "[ %s ]", grpnames[grp]); for (i = 0; i < isize[grp]; i++) { fprintf(fp, (i%15) ? " " : "\n"); fprintf(fp, " %4u", index[grp][i]+1); } fprintf(fp, "\n"); /* Added -contact support below. - Erik Marklund, May 29, 2006 */ if (!bContact) { fprintf(fp, "[ donors_hydrogens_%s ]\n", grpnames[grp]); for (i = 0; (i < hb->d.nrd); i++) { if (hb->d.grp[i] == grp) { for (j = 0; (j < hb->d.nhydro[i]); j++) { fprintf(fp, " %4u %4u", hb->d.don[i]+1, hb->d.hydro[i][j]+1); } fprintf(fp, "\n"); } } first = TRUE; fprintf(fp, "[ acceptors_%s ]", grpnames[grp]); for (i = 0; (i < hb->a.nra); i++) { if (hb->a.grp[i] == grp) { fprintf(fp, (i%15 && !first) ? " " : "\n"); fprintf(fp, " %4u", hb->a.acc[i]+1); first = FALSE; } } fprintf(fp, "\n"); } } if (bTwo) { fprintf(fp, bContact ? "[ contacts_%s-%s ]\n" : "[ hbonds_%s-%s ]\n", grpnames[0], grpnames[1]); } else { fprintf(fp, bContact ? "[ contacts_%s ]" : "[ hbonds_%s ]\n", grpnames[0]); } for (i = 0; (i < hb->d.nrd); i++) { ddd = hb->d.don[i]; for (k = 0; (k < hb->a.nra); k++) { aaa = hb->a.acc[k]; for (m = 0; (m < hb->d.nhydro[i]); m++) { if (hb->hbmap[i][k] && ISHB(hb->hbmap[i][k]->history[m])) { sprintf(ds, "%s", mkatomname(atoms, ddd)); sprintf(as, "%s", mkatomname(atoms, aaa)); if (bContact) { fprintf(fp, " %6u %6u\n", ddd+1, aaa+1); if (fplog) { fprintf(fplog, "%12s %12s\n", ds, as); } } else { hhh = hb->d.hydro[i][m]; sprintf(hs, "%s", mkatomname(atoms, hhh)); fprintf(fp, " %6u %6u %6u\n", ddd+1, hhh+1, aaa+1); if (fplog) { fprintf(fplog, "%12s %12s %12s\n", ds, hs, as); } } } } } } ffclose(fp); if (fplog) { ffclose(fplog); } } /* sync_hbdata() updates the parallel t_hbdata p_hb using hb as template. * It mimics add_frames() and init_frame() to some extent. */ static void sync_hbdata(t_hbdata *hb, t_hbdata *p_hb, int nframes, real t) { int i; if (nframes >= p_hb->max_frames) { p_hb->max_frames += 4096; srenew(p_hb->nhb, p_hb->max_frames); srenew(p_hb->ndist, p_hb->max_frames); srenew(p_hb->n_bound, p_hb->max_frames); srenew(p_hb->nhx, p_hb->max_frames); if (p_hb->bDAnr) { srenew(p_hb->danr, p_hb->max_frames); } memset(&(p_hb->nhb[nframes]), 0, sizeof(int) * (p_hb->max_frames-nframes)); memset(&(p_hb->ndist[nframes]), 0, sizeof(int) * (p_hb->max_frames-nframes)); p_hb->nhb[nframes] = 0; p_hb->ndist[nframes] = 0; } p_hb->nframes = nframes; /* for (i=0;) */ /* { */ /* p_hb->nhx[nframes][i] */ /* } */ memset(&(p_hb->nhx[nframes]), 0, sizeof(int)*max_hx); /* zero the helix count for this frame */ /* hb->per will remain constant througout the frame loop, * even though the data its members point to will change, * hence no need for re-syncing. */ } int gmx_hbond(int argc, char *argv[]) { const char *desc[] = { "[TT]g_hbond[tt] computes and analyzes hydrogen bonds. Hydrogen bonds are", "determined based on cutoffs for the angle Hydrogen - Donor - Acceptor", "(zero is extended) and the distance Donor - Acceptor", "(or Hydrogen - Acceptor using [TT]-noda[tt]).", "OH and NH groups are regarded as donors, O is an acceptor always,", "N is an acceptor by default, but this can be switched using", "[TT]-nitacc[tt]. Dummy hydrogen atoms are assumed to be connected", "to the first preceding non-hydrogen atom.[PAR]", "You need to specify two groups for analysis, which must be either", "identical or non-overlapping. All hydrogen bonds between the two", "groups are analyzed.[PAR]", "If you set [TT]-shell[tt], you will be asked for an additional index group", "which should contain exactly one atom. In this case, only hydrogen", "bonds between atoms within the shell distance from the one atom are", "considered.[PAR]", "With option -ac, rate constants for hydrogen bonding can be derived with the model of Luzar and Chandler", "(Nature 394, 1996; J. Chem. Phys. 113:23, 2000) or that of Markovitz and Agmon (J. Chem. Phys 129, 2008).", "If contact kinetics are analyzed by using the -contact option, then", "n(t) can be defined as either all pairs that are not within contact distance r at time t", "(corresponding to leaving the -r2 option at the default value 0) or all pairs that", "are within distance r2 (corresponding to setting a second cut-off value with option -r2).", "See mentioned literature for more details and definitions." "[PAR]", /* "It is also possible to analyse specific hydrogen bonds with", "[TT]-sel[tt]. This index file must contain a group of atom triplets", "Donor Hydrogen Acceptor, in the following way:[PAR]", */ "[TT]", "[ selected ][BR]", " 20 21 24[BR]", " 25 26 29[BR]", " 1 3 6[BR]", "[tt][BR]", "Note that the triplets need not be on separate lines.", "Each atom triplet specifies a hydrogen bond to be analyzed,", "note also that no check is made for the types of atoms.[PAR]", "[BB]Output:[bb][BR]", "[TT]-num[tt]: number of hydrogen bonds as a function of time.[BR]", "[TT]-ac[tt]: average over all autocorrelations of the existence", "functions (either 0 or 1) of all hydrogen bonds.[BR]", "[TT]-dist[tt]: distance distribution of all hydrogen bonds.[BR]", "[TT]-ang[tt]: angle distribution of all hydrogen bonds.[BR]", "[TT]-hx[tt]: the number of n-n+i hydrogen bonds as a function of time", "where n and n+i stand for residue numbers and i ranges from 0 to 6.", "This includes the n-n+3, n-n+4 and n-n+5 hydrogen bonds associated", "with helices in proteins.[BR]", "[TT]-hbn[tt]: all selected groups, donors, hydrogens and acceptors", "for selected groups, all hydrogen bonded atoms from all groups and", "all solvent atoms involved in insertion.[BR]", "[TT]-hbm[tt]: existence matrix for all hydrogen bonds over all", "frames, this also contains information on solvent insertion", "into hydrogen bonds. Ordering is identical to that in [TT]-hbn[tt]", "index file.[BR]", "[TT]-dan[tt]: write out the number of donors and acceptors analyzed for", "each timeframe. This is especially useful when using [TT]-shell[tt].[BR]", "[TT]-nhbdist[tt]: compute the number of HBonds per hydrogen in order to", "compare results to Raman Spectroscopy.", "[PAR]", "Note: options [TT]-ac[tt], [TT]-life[tt], [TT]-hbn[tt] and [TT]-hbm[tt]", "require an amount of memory proportional to the total numbers of donors", "times the total number of acceptors in the selected group(s)." }; static real acut = 30, abin = 1, rcut = 0.35, r2cut = 0, rbin = 0.005, rshell = -1; static real maxnhb = 0, fit_start = 1, fit_end = 60, temp = 298.15, smooth_tail_start = -1, D = -1; static gmx_bool bNitAcc = TRUE, bDA = TRUE, bMerge = TRUE; static int nDump = 0, nFitPoints = 100; static int nThreads = 0, nBalExp = 4; static gmx_bool bContact = FALSE, bBallistic = FALSE, bBallisticDt = FALSE, bGemFit = FALSE; static real logAfterTime = 10, gemBallistic = 0.2; /* ps */ static const char *NNtype[] = {NULL, "none", "binary", "oneOverR3", "dipole", NULL}; /* options */ t_pargs pa [] = { { "-a", FALSE, etREAL, {&acut}, "Cutoff angle (degrees, Hydrogen - Donor - Acceptor)" }, { "-r", FALSE, etREAL, {&rcut}, "Cutoff radius (nm, X - Acceptor, see next option)" }, { "-da", FALSE, etBOOL, {&bDA}, "Use distance Donor-Acceptor (if TRUE) or Hydrogen-Acceptor (FALSE)" }, { "-r2", FALSE, etREAL, {&r2cut}, "Second cutoff radius. Mainly useful with [TT]-contact[tt] and [TT]-ac[tt]"}, { "-abin", FALSE, etREAL, {&abin}, "Binwidth angle distribution (degrees)" }, { "-rbin", FALSE, etREAL, {&rbin}, "Binwidth distance distribution (nm)" }, { "-nitacc", FALSE, etBOOL, {&bNitAcc}, "Regard nitrogen atoms as acceptors" }, { "-contact", FALSE, etBOOL, {&bContact}, "Do not look for hydrogen bonds, but merely for contacts within the cut-off distance" }, { "-shell", FALSE, etREAL, {&rshell}, "when > 0, only calculate hydrogen bonds within # nm shell around " "one particle" }, { "-fitstart", FALSE, etREAL, {&fit_start}, "Time (ps) from which to start fitting the correlation functions in order to obtain the forward and backward rate constants for HB breaking and formation. With [TT]-gemfit[tt] we suggest [TT]-fitstart 0[tt]" }, { "-fitstart", FALSE, etREAL, {&fit_start}, "Time (ps) to which to stop fitting the correlation functions in order to obtain the forward and backward rate constants for HB breaking and formation (only with [TT]-gemfit[tt])" }, { "-temp", FALSE, etREAL, {&temp}, "Temperature (K) for computing the Gibbs energy corresponding to HB breaking and reforming" }, { "-smooth", FALSE, etREAL, {&smooth_tail_start}, "If >= 0, the tail of the ACF will be smoothed by fitting it to an exponential function: y = A exp(-x/[GRK]tau[grk])" }, { "-dump", FALSE, etINT, {&nDump}, "Dump the first N hydrogen bond ACFs in a single [TT].xvg[tt] file for debugging" }, { "-max_hb", FALSE, etREAL, {&maxnhb}, "Theoretical maximum number of hydrogen bonds used for normalizing HB autocorrelation function. Can be useful in case the program estimates it wrongly" }, { "-merge", FALSE, etBOOL, {&bMerge}, "H-bonds between the same donor and acceptor, but with different hydrogen are treated as a single H-bond. Mainly important for the ACF." }, { "-geminate", FALSE, etENUM, {gemType}, "Use reversible geminate recombination for the kinetics/thermodynamics calclations. See Markovitch et al., J. Chem. Phys 129, 084505 (2008) for details."}, { "-diff", FALSE, etREAL, {&D}, "Dffusion coefficient to use in the reversible geminate recombination kinetic model. If negative, then it will be fitted to the ACF along with ka and kd."}, #ifdef GMX_OPENMP { "-nthreads", FALSE, etINT, {&nThreads}, "Number of threads used for the parallel loop over autocorrelations. nThreads <= 0 means maximum number of threads. Requires linking with OpenMP. The number of threads is limited by the number of processors (before OpenMP v.3 ) or environment variable OMP_THREAD_LIMIT (OpenMP v.3)"}, #endif }; const char *bugs[] = { "The option [TT]-sel[tt] that used to work on selected hbonds is out of order, and therefore not available for the time being." }; t_filenm fnm[] = { { efTRX, "-f", NULL, ffREAD }, { efTPX, NULL, NULL, ffREAD }, { efNDX, NULL, NULL, ffOPTRD }, /* { efNDX, "-sel", "select", ffOPTRD },*/ { efXVG, "-num", "hbnum", ffWRITE }, { efLOG, "-g", "hbond", ffOPTWR }, { efXVG, "-ac", "hbac", ffOPTWR }, { efXVG, "-dist", "hbdist", ffOPTWR }, { efXVG, "-ang", "hbang", ffOPTWR }, { efXVG, "-hx", "hbhelix", ffOPTWR }, { efNDX, "-hbn", "hbond", ffOPTWR }, { efXPM, "-hbm", "hbmap", ffOPTWR }, { efXVG, "-don", "donor", ffOPTWR }, { efXVG, "-dan", "danum", ffOPTWR }, { efXVG, "-life", "hblife", ffOPTWR }, { efXVG, "-nhbdist", "nhbdist", ffOPTWR } }; #define NFILE asize(fnm) char hbmap [HB_NR] = { ' ', 'o', '-', '*' }; const char *hbdesc[HB_NR] = { "None", "Present", "Inserted", "Present & Inserted" }; t_rgb hbrgb [HB_NR] = { {1, 1, 1}, {1, 0, 0}, {0, 0, 1}, {1, 0, 1} }; t_trxstatus *status; int trrStatus = 1; t_topology top; t_inputrec ir; t_pargs *ppa; int npargs, natoms, nframes = 0, shatom; int *isize; char **grpnames; atom_id **index; rvec *x, hbox; matrix box; real t, ccut, dist = 0.0, ang = 0.0; double max_nhb, aver_nhb, aver_dist; int h = 0, i = 0, j, k = 0, l, start, end, id, ja, ogrp, nsel; int xi, yi, zi, ai; int xj, yj, zj, aj, xjj, yjj, zjj; int xk, yk, zk, ak, xkk, ykk, zkk; gmx_bool bSelected, bHBmap, bStop, bTwo, was, bBox, bTric; int *adist, *rdist, *aptr, *rprt; int grp, nabin, nrbin, bin, resdist, ihb; char **leg; t_hbdata *hb, *hbptr; FILE *fp, *fpins = NULL, *fpnhb = NULL; t_gridcell ***grid; t_ncell *icell, *jcell, *kcell; ivec ngrid; unsigned char *datable; output_env_t oenv; int gemmode, NN; PSTYPE peri = 0; t_E E; int ii, jj, hh, actual_nThreads; int threadNr = 0; gmx_bool bGem, bNN, bParallel; t_gemParams *params = NULL; gmx_bool bEdge_yjj, bEdge_xjj, bOMP; t_hbdata **p_hb = NULL; /* one per thread, then merge after the frame loop */ int **p_adist = NULL, **p_rdist = NULL; /* a histogram for each thread. */ #ifdef GMX_OPENMP bOMP = TRUE; #else bOMP = FALSE; #endif CopyRight(stderr, argv[0]); npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT | PCA_BE_NICE, NFILE, fnm, npargs, ppa, asize(desc), desc, asize(bugs), bugs, &oenv); /* NN-loop? If so, what estimator to use ?*/ NN = 1; /* Outcommented for now DvdS 2010-07-13 while (NN < NN_NR && gmx_strcasecmp(NNtype[0], NNtype[NN])!=0) NN++; if (NN == NN_NR) gmx_fatal(FARGS, "Invalid NN-loop type."); */ bNN = FALSE; for (i = 2; bNN == FALSE && i < NN_NR; i++) { bNN = bNN || NN == i; } if (NN > NN_NONE && bMerge) { bMerge = FALSE; } /* geminate recombination? If so, which flavor? */ gemmode = 1; while (gemmode < gemNR && gmx_strcasecmp(gemType[0], gemType[gemmode]) != 0) { gemmode++; } if (gemmode == gemNR) { gmx_fatal(FARGS, "Invalid recombination type."); } bGem = FALSE; for (i = 2; bGem == FALSE && i < gemNR; i++) { bGem = bGem || gemmode == i; } if (bGem) { printf("Geminate recombination: %s\n", gemType[gemmode]); #ifndef HAVE_LIBGSL printf("Note that some aspects of reversible geminate recombination won't work without gsl.\n"); #endif if (bContact) { if (gemmode != gemDD) { printf("Turning off -contact option...\n"); bContact = FALSE; } } else { if (gemmode == gemDD) { printf("Turning on -contact option...\n"); bContact = TRUE; } } if (bMerge) { if (gemmode == gemAA) { printf("Turning off -merge option...\n"); bMerge = FALSE; } } else { if (gemmode != gemAA) { printf("Turning on -merge option...\n"); bMerge = TRUE; } } } /* process input */ bSelected = FALSE; ccut = cos(acut*DEG2RAD); if (bContact) { if (bSelected) { gmx_fatal(FARGS, "Can not analyze selected contacts."); } if (!bDA) { gmx_fatal(FARGS, "Can not analyze contact between H and A: turn off -noda"); } } /* Initiate main data structure! */ bHBmap = (opt2bSet("-ac", NFILE, fnm) || opt2bSet("-life", NFILE, fnm) || opt2bSet("-hbn", NFILE, fnm) || opt2bSet("-hbm", NFILE, fnm) || bGem); if (opt2bSet("-nhbdist", NFILE, fnm)) { const char *leg[MAXHH+1] = { "0 HBs", "1 HB", "2 HBs", "3 HBs", "Total" }; fpnhb = xvgropen(opt2fn("-nhbdist", NFILE, fnm), "Number of donor-H with N HBs", output_env_get_xvgr_tlabel(oenv), "N", oenv); xvgr_legend(fpnhb, asize(leg), leg, oenv); } hb = mk_hbdata(bHBmap, opt2bSet("-dan", NFILE, fnm), bMerge || bContact, bGem, gemmode); /* get topology */ read_tpx_top(ftp2fn(efTPX, NFILE, fnm), &ir, box, &natoms, NULL, NULL, NULL, &top); snew(grpnames, grNR); snew(index, grNR); snew(isize, grNR); /* Make Donor-Acceptor table */ snew(datable, top.atoms.nr); gen_datable(index[0], isize[0], datable, top.atoms.nr); if (bSelected) { /* analyze selected hydrogen bonds */ printf("Select group with selected atoms:\n"); get_index(&(top.atoms), opt2fn("-sel", NFILE, fnm), 1, &nsel, index, grpnames); if (nsel % 3) { gmx_fatal(FARGS, "Number of atoms in group '%s' not a multiple of 3\n" "and therefore cannot contain triplets of " "Donor-Hydrogen-Acceptor", grpnames[0]); } bTwo = FALSE; for (i = 0; (i < nsel); i += 3) { int dd = index[0][i]; int aa = index[0][i+2]; /* int */ hh = index[0][i+1]; add_dh (&hb->d, dd, hh, i, datable); add_acc(&hb->a, aa, i); /* Should this be here ? */ snew(hb->d.dptr, top.atoms.nr); snew(hb->a.aptr, top.atoms.nr); add_hbond(hb, dd, aa, hh, gr0, gr0, 0, bMerge, 0, bContact, peri); } printf("Analyzing %d selected hydrogen bonds from '%s'\n", isize[0], grpnames[0]); } else { /* analyze all hydrogen bonds: get group(s) */ printf("Specify 2 groups to analyze:\n"); get_index(&(top.atoms), ftp2fn_null(efNDX, NFILE, fnm), 2, isize, index, grpnames); /* check if we have two identical or two non-overlapping groups */ bTwo = isize[0] != isize[1]; for (i = 0; (i < isize[0]) && !bTwo; i++) { bTwo = index[0][i] != index[1][i]; } if (bTwo) { printf("Checking for overlap in atoms between %s and %s\n", grpnames[0], grpnames[1]); for (i = 0; i < isize[1]; i++) { if (ISINGRP(datable[index[1][i]])) { gmx_fatal(FARGS, "Partial overlap between groups '%s' and '%s'", grpnames[0], grpnames[1]); } } /* printf("Checking for overlap in atoms between %s and %s\n", grpnames[0],grpnames[1]); for (i=0; i<isize[0]; i++) for (j=0; j<isize[1]; j++) if (index[0][i] == index[1][j]) gmx_fatal(FARGS,"Partial overlap between groups '%s' and '%s'", grpnames[0],grpnames[1]); */ } if (bTwo) { printf("Calculating %s " "between %s (%d atoms) and %s (%d atoms)\n", bContact ? "contacts" : "hydrogen bonds", grpnames[0], isize[0], grpnames[1], isize[1]); } else { fprintf(stderr, "Calculating %s in %s (%d atoms)\n", bContact ? "contacts" : "hydrogen bonds", grpnames[0], isize[0]); } } sfree(datable); /* search donors and acceptors in groups */ snew(datable, top.atoms.nr); for (i = 0; (i < grNR); i++) { if ( ((i == gr0) && !bSelected ) || ((i == gr1) && bTwo )) { gen_datable(index[i], isize[i], datable, top.atoms.nr); if (bContact) { search_acceptors(&top, isize[i], index[i], &hb->a, i, bNitAcc, TRUE, (bTwo && (i == gr0)) || !bTwo, datable); search_donors (&top, isize[i], index[i], &hb->d, i, TRUE, (bTwo && (i == gr1)) || !bTwo, datable); } else { search_acceptors(&top, isize[i], index[i], &hb->a, i, bNitAcc, FALSE, TRUE, datable); search_donors (&top, isize[i], index[i], &hb->d, i, FALSE, TRUE, datable); } if (bTwo) { clear_datable_grp(datable, top.atoms.nr); } } } sfree(datable); printf("Found %d donors and %d acceptors\n", hb->d.nrd, hb->a.nra); /*if (bSelected) snew(donors[gr0D], dons[gr0D].nrd);*/ if (bHBmap) { printf("Making hbmap structure..."); /* Generate hbond data structure */ mk_hbmap(hb, bTwo); printf("done.\n"); } #ifdef HAVE_NN_LOOPS if (bNN) { mk_hbEmap(hb, 0); } #endif if (bGem) { printf("Making per structure..."); /* Generate hbond data structure */ mk_per(hb); printf("done.\n"); } /* check input */ bStop = FALSE; if (hb->d.nrd + hb->a.nra == 0) { printf("No Donors or Acceptors found\n"); bStop = TRUE; } if (!bStop) { if (hb->d.nrd == 0) { printf("No Donors found\n"); bStop = TRUE; } if (hb->a.nra == 0) { printf("No Acceptors found\n"); bStop = TRUE; } } if (bStop) { gmx_fatal(FARGS, "Nothing to be done"); } shatom = 0; if (rshell > 0) { int shisz; atom_id *shidx; char *shgrpnm; /* get index group with atom for shell */ do { printf("Select atom for shell (1 atom):\n"); get_index(&(top.atoms), ftp2fn_null(efNDX, NFILE, fnm), 1, &shisz, &shidx, &shgrpnm); if (shisz != 1) { printf("group contains %d atoms, should be 1 (one)\n", shisz); } } while (shisz != 1); shatom = shidx[0]; printf("Will calculate hydrogen bonds within a shell " "of %g nm around atom %i\n", rshell, shatom+1); } /* Analyze trajectory */ natoms = read_first_x(oenv, &status, ftp2fn(efTRX, NFILE, fnm), &t, &x, box); if (natoms > top.atoms.nr) { gmx_fatal(FARGS, "Topology (%d atoms) does not match trajectory (%d atoms)", top.atoms.nr, natoms); } bBox = ir.ePBC != epbcNONE; grid = init_grid(bBox, box, (rcut > r2cut) ? rcut : r2cut, ngrid); nabin = acut/abin; nrbin = rcut/rbin; snew(adist, nabin+1); snew(rdist, nrbin+1); if (bGem && !bBox) { gmx_fatal(FARGS, "Can't do geminate recombination without periodic box."); } bParallel = FALSE; #ifndef GMX_OPENMP #define __ADIST adist #define __RDIST rdist #define __HBDATA hb #else /* GMX_OPENMP ================================================== \ * Set up the OpenMP stuff, | * like the number of threads and such | * Also start the parallel loop. | */ #define __ADIST p_adist[threadNr] #define __RDIST p_rdist[threadNr] #define __HBDATA p_hb[threadNr] #endif if (bOMP) { bParallel = !bSelected; if (bParallel) { actual_nThreads = min((nThreads <= 0) ? INT_MAX : nThreads, gmx_omp_get_max_threads()); gmx_omp_set_num_threads(actual_nThreads); printf("Frame loop parallelized with OpenMP using %i threads.\n", actual_nThreads); fflush(stdout); } else { actual_nThreads = 1; } snew(p_hb, actual_nThreads); snew(p_adist, actual_nThreads); snew(p_rdist, actual_nThreads); for (i = 0; i < actual_nThreads; i++) { snew(p_hb[i], 1); snew(p_adist[i], nabin+1); snew(p_rdist[i], nrbin+1); p_hb[i]->max_frames = 0; p_hb[i]->nhb = NULL; p_hb[i]->ndist = NULL; p_hb[i]->n_bound = NULL; p_hb[i]->time = NULL; p_hb[i]->nhx = NULL; p_hb[i]->bHBmap = hb->bHBmap; p_hb[i]->bDAnr = hb->bDAnr; p_hb[i]->bGem = hb->bGem; p_hb[i]->wordlen = hb->wordlen; p_hb[i]->nframes = hb->nframes; p_hb[i]->maxhydro = hb->maxhydro; p_hb[i]->danr = hb->danr; p_hb[i]->d = hb->d; p_hb[i]->a = hb->a; p_hb[i]->hbmap = hb->hbmap; p_hb[i]->time = hb->time; /* This may need re-syncing at every frame. */ p_hb[i]->per = hb->per; #ifdef HAVE_NN_LOOPS p_hb[i]->hbE = hb->hbE; #endif p_hb[i]->nrhb = 0; p_hb[i]->nrdist = 0; } } /* Make a thread pool here, * instead of forking anew at every frame. */ #pragma omp parallel \ firstprivate(i) \ private(j, h, ii, jj, hh, E, \ xi, yi, zi, xj, yj, zj, threadNr, \ dist, ang, peri, icell, jcell, \ grp, ogrp, ai, aj, xjj, yjj, zjj, \ xk, yk, zk, ihb, id, resdist, \ xkk, ykk, zkk, kcell, ak, k, bTric, \ bEdge_xjj, bEdge_yjj) \ default(shared) { /* Start of parallel region */ threadNr = gmx_omp_get_thread_num(); do { bTric = bBox && TRICLINIC(box); if (bOMP) { sync_hbdata(hb, p_hb[threadNr], nframes, t); } #pragma omp single { build_grid(hb, x, x[shatom], bBox, box, hbox, (rcut > r2cut) ? rcut : r2cut, rshell, ngrid, grid); reset_nhbonds(&(hb->d)); if (debug && bDebug) { dump_grid(debug, ngrid, grid); } add_frames(hb, nframes); init_hbframe(hb, nframes, output_env_conv_time(oenv, t)); if (hb->bDAnr) { count_da_grid(ngrid, grid, hb->danr[nframes]); } } /* omp single */ if (bOMP) { p_hb[threadNr]->time = hb->time; /* This pointer may have changed. */ } if (bNN) { #ifdef HAVE_NN_LOOPS /* Unlock this feature when testing */ /* Loop over all atom pairs and estimate interaction energy */ #pragma omp single { addFramesNN(hb, nframes); } #pragma omp barrier #pragma omp for schedule(dynamic) for (i = 0; i < hb->d.nrd; i++) { for (j = 0; j < hb->a.nra; j++) { for (h = 0; h < (bContact ? 1 : hb->d.nhydro[i]); h++) { if (i == hb->d.nrd || j == hb->a.nra) { gmx_fatal(FARGS, "out of bounds"); } /* Get the real atom ids */ ii = hb->d.don[i]; jj = hb->a.acc[j]; hh = hb->d.hydro[i][h]; /* Estimate the energy from the geometry */ E = calcHbEnergy(ii, jj, hh, x, NN, box, hbox, &(hb->d)); /* Store the energy */ storeHbEnergy(hb, i, j, h, E, nframes); } } } #endif /* HAVE_NN_LOOPS */ } /* if (bNN)*/ else { if (bSelected) { #pragma omp single { /* Do not parallelize this just yet. */ /* int ii; */ for (ii = 0; (ii < nsel); ii++) { int dd = index[0][i]; int aa = index[0][i+2]; /* int */ hh = index[0][i+1]; ihb = is_hbond(hb, ii, ii, dd, aa, rcut, r2cut, ccut, x, bBox, box, hbox, &dist, &ang, bDA, &h, bContact, bMerge, &peri); if (ihb) { /* add to index if not already there */ /* Add a hbond */ add_hbond(hb, dd, aa, hh, ii, ii, nframes, bMerge, ihb, bContact, peri); } } } /* omp single */ } /* if (bSelected) */ else { #pragma omp single { if (bGem) { calcBoxProjection(box, hb->per->P); } /* loop over all gridcells (xi,yi,zi) */ /* Removed confusing macro, DvdS 27/12/98 */ } /* The outer grid loop will have to do for now. */ #pragma omp for schedule(dynamic) for (xi = 0; xi < ngrid[XX]; xi++) { for (yi = 0; (yi < ngrid[YY]); yi++) { for (zi = 0; (zi < ngrid[ZZ]); zi++) { /* loop over donor groups gr0 (always) and gr1 (if necessary) */ for (grp = gr0; (grp <= (bTwo ? gr1 : gr0)); grp++) { icell = &(grid[zi][yi][xi].d[grp]); if (bTwo) { ogrp = 1-grp; } else { ogrp = grp; } /* loop over all hydrogen atoms from group (grp) * in this gridcell (icell) */ for (ai = 0; (ai < icell->nr); ai++) { i = icell->atoms[ai]; /* loop over all adjacent gridcells (xj,yj,zj) */ for (zjj = grid_loop_begin(ngrid[ZZ], zi, bTric, FALSE); zjj <= grid_loop_end(ngrid[ZZ], zi, bTric, FALSE); zjj++) { zj = grid_mod(zjj, ngrid[ZZ]); bEdge_yjj = (zj == 0) || (zj == ngrid[ZZ] - 1); for (yjj = grid_loop_begin(ngrid[YY], yi, bTric, bEdge_yjj); yjj <= grid_loop_end(ngrid[YY], yi, bTric, bEdge_yjj); yjj++) { yj = grid_mod(yjj, ngrid[YY]); bEdge_xjj = (yj == 0) || (yj == ngrid[YY] - 1) || (zj == 0) || (zj == ngrid[ZZ] - 1); for (xjj = grid_loop_begin(ngrid[XX], xi, bTric, bEdge_xjj); xjj <= grid_loop_end(ngrid[XX], xi, bTric, bEdge_xjj); xjj++) { xj = grid_mod(xjj, ngrid[XX]); jcell = &(grid[zj][yj][xj].a[ogrp]); /* loop over acceptor atoms from other group (ogrp) * in this adjacent gridcell (jcell) */ for (aj = 0; (aj < jcell->nr); aj++) { j = jcell->atoms[aj]; /* check if this once was a h-bond */ peri = -1; ihb = is_hbond(__HBDATA, grp, ogrp, i, j, rcut, r2cut, ccut, x, bBox, box, hbox, &dist, &ang, bDA, &h, bContact, bMerge, &peri); if (ihb) { /* add to index if not already there */ /* Add a hbond */ add_hbond(__HBDATA, i, j, h, grp, ogrp, nframes, bMerge, ihb, bContact, peri); /* make angle and distance distributions */ if (ihb == hbHB && !bContact) { if (dist > rcut) { gmx_fatal(FARGS, "distance is higher than what is allowed for an hbond: %f", dist); } ang *= RAD2DEG; __ADIST[(int)( ang/abin)]++; __RDIST[(int)(dist/rbin)]++; if (!bTwo) { int id, ia; if ((id = donor_index(&hb->d, grp, i)) == NOTSET) { gmx_fatal(FARGS, "Invalid donor %d", i); } if ((ia = acceptor_index(&hb->a, ogrp, j)) == NOTSET) { gmx_fatal(FARGS, "Invalid acceptor %d", j); } resdist = abs(top.atoms.atom[i].resind- top.atoms.atom[j].resind); if (resdist >= max_hx) { resdist = max_hx-1; } __HBDATA->nhx[nframes][resdist]++; } } } } /* for aj */ } /* for xjj */ } /* for yjj */ } /* for zjj */ } /* for ai */ } /* for grp */ } /* for xi,yi,zi */ } } } /* if (bSelected) {...} else */ /* Better wait for all threads to finnish using x[] before updating it. */ k = nframes; #pragma omp barrier #pragma omp critical { /* Sum up histograms and counts from p_hb[] into hb */ if (bOMP) { hb->nhb[k] += p_hb[threadNr]->nhb[k]; hb->ndist[k] += p_hb[threadNr]->ndist[k]; for (j = 0; j < max_hx; j++) { hb->nhx[k][j] += p_hb[threadNr]->nhx[k][j]; } } } /* Here are a handful of single constructs * to share the workload a bit. The most * important one is of course the last one, * where there's a potential bottleneck in form * of slow I/O. */ #pragma omp barrier #pragma omp single { if (hb != NULL) { analyse_donor_props(opt2fn_null("-don", NFILE, fnm), hb, k, t, oenv); } } #pragma omp single { if (fpnhb) { do_nhb_dist(fpnhb, hb, t); } } } /* if (bNN) {...} else + */ #pragma omp single { trrStatus = (read_next_x(oenv, status, &t, natoms, x, box)); nframes++; } #pragma omp barrier } while (trrStatus); if (bOMP) { #pragma omp critical { hb->nrhb += p_hb[threadNr]->nrhb; hb->nrdist += p_hb[threadNr]->nrdist; } /* Free parallel datastructures */ sfree(p_hb[threadNr]->nhb); sfree(p_hb[threadNr]->ndist); sfree(p_hb[threadNr]->nhx); #pragma omp for for (i = 0; i < nabin; i++) { for (j = 0; j < actual_nThreads; j++) { adist[i] += p_adist[j][i]; } } #pragma omp for for (i = 0; i <= nrbin; i++) { for (j = 0; j < actual_nThreads; j++) { rdist[i] += p_rdist[j][i]; } } sfree(p_adist[threadNr]); sfree(p_rdist[threadNr]); } } /* End of parallel region */ if (bOMP) { sfree(p_adist); sfree(p_rdist); } if (nframes < 2 && (opt2bSet("-ac", NFILE, fnm) || opt2bSet("-life", NFILE, fnm))) { gmx_fatal(FARGS, "Cannot calculate autocorrelation of life times with less than two frames"); } free_grid(ngrid, &grid); close_trj(status); if (fpnhb) { ffclose(fpnhb); } /* Compute maximum possible number of different hbonds */ if (maxnhb > 0) { max_nhb = maxnhb; } else { max_nhb = 0.5*(hb->d.nrd*hb->a.nra); } /* Added support for -contact below. * - Erik Marklund, May 29-31, 2006 */ /* Changed contact code. * - Erik Marklund, June 29, 2006 */ if (bHBmap && !bNN) { if (hb->nrhb == 0) { printf("No %s found!!\n", bContact ? "contacts" : "hydrogen bonds"); } else { printf("Found %d different %s in trajectory\n" "Found %d different atom-pairs within %s distance\n", hb->nrhb, bContact ? "contacts" : "hydrogen bonds", hb->nrdist, (r2cut > 0) ? "second cut-off" : "hydrogen bonding"); /*Control the pHist.*/ if (bMerge) { merge_hb(hb, bTwo, bContact); } if (opt2bSet("-hbn", NFILE, fnm)) { dump_hbmap(hb, NFILE, fnm, bTwo, bContact, isize, index, grpnames, &top.atoms); } /* Moved the call to merge_hb() to a line BEFORE dump_hbmap * to make the -hbn and -hmb output match eachother. * - Erik Marklund, May 30, 2006 */ } } /* Print out number of hbonds and distances */ aver_nhb = 0; aver_dist = 0; fp = xvgropen(opt2fn("-num", NFILE, fnm), bContact ? "Contacts" : "Hydrogen Bonds", output_env_get_xvgr_tlabel(oenv), "Number", oenv); snew(leg, 2); snew(leg[0], STRLEN); snew(leg[1], STRLEN); sprintf(leg[0], "%s", bContact ? "Contacts" : "Hydrogen bonds"); sprintf(leg[1], "Pairs within %g nm", (r2cut > 0) ? r2cut : rcut); xvgr_legend(fp, 2, (const char**)leg, oenv); sfree(leg[1]); sfree(leg[0]); sfree(leg); for (i = 0; (i < nframes); i++) { fprintf(fp, "%10g %10d %10d\n", hb->time[i], hb->nhb[i], hb->ndist[i]); aver_nhb += hb->nhb[i]; aver_dist += hb->ndist[i]; } ffclose(fp); aver_nhb /= nframes; aver_dist /= nframes; /* Print HB distance distribution */ if (opt2bSet("-dist", NFILE, fnm)) { long sum; sum = 0; for (i = 0; i < nrbin; i++) { sum += rdist[i]; } fp = xvgropen(opt2fn("-dist", NFILE, fnm), "Hydrogen Bond Distribution", bDA ? "Donor - Acceptor Distance (nm)" : "Hydrogen - Acceptor Distance (nm)", "", oenv); for (i = 0; i < nrbin; i++) { fprintf(fp, "%10g %10g\n", (i+0.5)*rbin, rdist[i]/(rbin*(real)sum)); } ffclose(fp); } /* Print HB angle distribution */ if (opt2bSet("-ang", NFILE, fnm)) { long sum; sum = 0; for (i = 0; i < nabin; i++) { sum += adist[i]; } fp = xvgropen(opt2fn("-ang", NFILE, fnm), "Hydrogen Bond Distribution", "Hydrogen - Donor - Acceptor Angle (\\SO\\N)", "", oenv); for (i = 0; i < nabin; i++) { fprintf(fp, "%10g %10g\n", (i+0.5)*abin, adist[i]/(abin*(real)sum)); } ffclose(fp); } /* Print HB in alpha-helix */ if (opt2bSet("-hx", NFILE, fnm)) { fp = xvgropen(opt2fn("-hx", NFILE, fnm), "Hydrogen Bonds", output_env_get_xvgr_tlabel(oenv), "Count", oenv); xvgr_legend(fp, NRHXTYPES, hxtypenames, oenv); for (i = 0; i < nframes; i++) { fprintf(fp, "%10g", hb->time[i]); for (j = 0; j < max_hx; j++) { fprintf(fp, " %6d", hb->nhx[i][j]); } fprintf(fp, "\n"); } ffclose(fp); } if (!bNN) { printf("Average number of %s per timeframe %.3f out of %g possible\n", bContact ? "contacts" : "hbonds", bContact ? aver_dist : aver_nhb, max_nhb); } /* Do Autocorrelation etc. */ if (hb->bHBmap) { /* Added support for -contact in ac and hbm calculations below. - Erik Marklund, May 29, 2006 */ ivec itmp; rvec rtmp; if (opt2bSet("-ac", NFILE, fnm) || opt2bSet("-life", NFILE, fnm)) { please_cite(stdout, "Spoel2006b"); } if (opt2bSet("-ac", NFILE, fnm)) { char *gemstring = NULL; if (bGem || bNN) { params = init_gemParams(rcut, D, hb->time, hb->nframes/2, nFitPoints, fit_start, fit_end, gemBallistic, nBalExp, bBallisticDt); if (params == NULL) { gmx_fatal(FARGS, "Could not initiate t_gemParams params."); } } gemstring = strdup(gemType[hb->per->gemtype]); do_hbac(opt2fn("-ac", NFILE, fnm), hb, nDump, bMerge, bContact, fit_start, temp, r2cut > 0, smooth_tail_start, oenv, params, gemstring, nThreads, NN, bBallistic, bGemFit); } if (opt2bSet("-life", NFILE, fnm)) { do_hblife(opt2fn("-life", NFILE, fnm), hb, bMerge, bContact, oenv); } if (opt2bSet("-hbm", NFILE, fnm)) { t_matrix mat; int id, ia, hh, x, y; if ((nframes > 0) && (hb->nrhb > 0)) { mat.nx = nframes; mat.ny = hb->nrhb; snew(mat.matrix, mat.nx); for (x = 0; (x < mat.nx); x++) { snew(mat.matrix[x], mat.ny); } y = 0; for (id = 0; (id < hb->d.nrd); id++) { for (ia = 0; (ia < hb->a.nra); ia++) { for (hh = 0; (hh < hb->maxhydro); hh++) { if (hb->hbmap[id][ia]) { if (ISHB(hb->hbmap[id][ia]->history[hh])) { /* Changed '<' into '<=' in the for-statement below. * It fixed the previously undiscovered bug that caused * the last occurance of an hbond/contact to not be * set in mat.matrix. Have a look at any old -hbm-output * and you will notice that the last column is allways empty. * - Erik Marklund May 30, 2006 */ for (x = 0; (x <= hb->hbmap[id][ia]->nframes); x++) { int nn0 = hb->hbmap[id][ia]->n0; range_check(y, 0, mat.ny); mat.matrix[x+nn0][y] = is_hb(hb->hbmap[id][ia]->h[hh], x); } y++; } } } } } mat.axis_x = hb->time; snew(mat.axis_y, mat.ny); for (j = 0; j < mat.ny; j++) { mat.axis_y[j] = j; } sprintf(mat.title, bContact ? "Contact Existence Map" : "Hydrogen Bond Existence Map"); sprintf(mat.legend, bContact ? "Contacts" : "Hydrogen Bonds"); sprintf(mat.label_x, "%s", output_env_get_xvgr_tlabel(oenv)); sprintf(mat.label_y, bContact ? "Contact Index" : "Hydrogen Bond Index"); mat.bDiscrete = TRUE; mat.nmap = 2; snew(mat.map, mat.nmap); for (i = 0; i < mat.nmap; i++) { mat.map[i].code.c1 = hbmap[i]; mat.map[i].desc = hbdesc[i]; mat.map[i].rgb = hbrgb[i]; } fp = opt2FILE("-hbm", NFILE, fnm, "w"); write_xpm_m(fp, mat); ffclose(fp); for (x = 0; x < mat.nx; x++) { sfree(mat.matrix[x]); } sfree(mat.axis_y); sfree(mat.matrix); sfree(mat.map); } else { fprintf(stderr, "No hydrogen bonds/contacts found. No hydrogen bond map will be printed.\n"); } } } if (bGem) { fprintf(stderr, "There were %i periodic shifts\n", hb->per->nper); fprintf(stderr, "Freeing pHist for all donors...\n"); for (i = 0; i < hb->d.nrd; i++) { fprintf(stderr, "\r%i", i); if (hb->per->pHist[i] != NULL) { for (j = 0; j < hb->a.nra; j++) { clearPshift(&(hb->per->pHist[i][j])); } sfree(hb->per->pHist[i]); } } sfree(hb->per->pHist); sfree(hb->per->p2i); sfree(hb->per); fprintf(stderr, "...done.\n"); } #ifdef HAVE_NN_LOOPS if (bNN) { free_hbEmap(hb); } #endif if (hb->bDAnr) { int i, j, nleg; char **legnames; char buf[STRLEN]; #define USE_THIS_GROUP(j) ( (j == gr0) || (bTwo && (j == gr1)) ) fp = xvgropen(opt2fn("-dan", NFILE, fnm), "Donors and Acceptors", output_env_get_xvgr_tlabel(oenv), "Count", oenv); nleg = (bTwo ? 2 : 1)*2; snew(legnames, nleg); i = 0; for (j = 0; j < grNR; j++) { if (USE_THIS_GROUP(j) ) { sprintf(buf, "Donors %s", grpnames[j]); legnames[i++] = strdup(buf); sprintf(buf, "Acceptors %s", grpnames[j]); legnames[i++] = strdup(buf); } } if (i != nleg) { gmx_incons("number of legend entries"); } xvgr_legend(fp, nleg, (const char**)legnames, oenv); for (i = 0; i < nframes; i++) { fprintf(fp, "%10g", hb->time[i]); for (j = 0; (j < grNR); j++) { if (USE_THIS_GROUP(j) ) { fprintf(fp, " %6d", hb->danr[i][j]); } } fprintf(fp, "\n"); } ffclose(fp); } thanx(stdout); return 0; }
{ "alphanum_fraction": 0.4067673879, "avg_line_length": 33.0744875178, "ext": "c", "hexsha": "378a03f3866742b7f244094ee66d7a35a92db141", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_path": "gromacs-4.6.5/src/tools/gmx_hbond.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_path": "gromacs-4.6.5/src/tools/gmx_hbond.c", "max_line_length": 294, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_path": "gromacs-4.6.5/src/tools/gmx_hbond.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "num_tokens": 43244, "size": 162958 }
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_STRING_SPAN_H #define GSL_STRING_SPAN_H #include <gsl/gsl_assert> // for Ensures, Expects #include <gsl/gsl_util> // for narrow_cast #include <gsl/span> // for operator!=, operator==, dynamic_extent #include <gsl/pointers> // for not_null #include <algorithm> // for equal, lexicographical_compare #include <array> // for array #include <cstddef> // for ptrdiff_t, size_t, nullptr_t #include <cstdint> // for PTRDIFF_MAX #include <cstring> #include <string> // for basic_string, allocator, char_traits #include <type_traits> // for declval, is_convertible, enable_if_t, add_... #ifdef _MSC_VER #pragma warning(push) // Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool. #pragma warning(disable : 26446) // TODO: bug in parser - attributes and templates #pragma warning(disable : 26481) // TODO: suppress does not work inside templates sometimes #if _MSC_VER < 1910 #pragma push_macro("constexpr") #define constexpr /*constexpr*/ #endif // _MSC_VER < 1910 #endif // _MSC_VER namespace gsl { // // czstring and wzstring // // These are "tag" typedefs for C-style strings (i.e. null-terminated character arrays) // that allow static analysis to help find bugs. // // There are no additional features/semantics that we can find a way to add inside the // type system for these types that will not either incur significant runtime costs or // (sometimes needlessly) break existing programs when introduced. // template <typename CharT, std::ptrdiff_t Extent = dynamic_extent> using basic_zstring = CharT*; template <std::ptrdiff_t Extent = dynamic_extent> using czstring = basic_zstring<const char, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using cwzstring = basic_zstring<const wchar_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using cu16zstring = basic_zstring<const char16_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using cu32zstring = basic_zstring<const char32_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using zstring = basic_zstring<char, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using wzstring = basic_zstring<wchar_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using u16zstring = basic_zstring<char16_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using u32zstring = basic_zstring<char32_t, Extent>; namespace details { template <class CharT> std::ptrdiff_t string_length(const CharT* str, std::ptrdiff_t n) { if (str == nullptr || n <= 0) return 0; const span<const CharT> str_span{str, n}; std::ptrdiff_t len = 0; while (len < n && str_span[len]) len++; return len; } } // namespace details // // ensure_sentinel() // // Provides a way to obtain an span from a contiguous sequence // that ends with a (non-inclusive) sentinel value. // // Will fail-fast if sentinel cannot be found before max elements are examined. // template <typename T, const T Sentinel> span<T, dynamic_extent> ensure_sentinel(T* seq, std::ptrdiff_t max = PTRDIFF_MAX) { Ensures(seq != nullptr); GSL_SUPPRESS(f.23) // NO-FORMAT: attribute // TODO: false positive // TODO: suppress does not work auto cur = seq; Ensures(cur != nullptr); // workaround for removing the warning GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute // TODO: suppress does not work while ((cur - seq) < max && *cur != Sentinel) ++cur; Ensures(*cur == Sentinel); return {seq, cur - seq}; } // // ensure_z - creates a span for a zero terminated strings. // Will fail fast if a null-terminator cannot be found before // the limit of size_type. // template <typename CharT> span<CharT, dynamic_extent> ensure_z(CharT* const& sz, std::ptrdiff_t max = PTRDIFF_MAX) { return ensure_sentinel<CharT, CharT(0)>(sz, max); } template <typename CharT, std::size_t N> span<CharT, dynamic_extent> ensure_z(CharT (&sz)[N]) { return ensure_z(&sz[0], narrow_cast<std::ptrdiff_t>(N)); } template <class Cont> span<typename std::remove_pointer<typename Cont::pointer>::type, dynamic_extent> ensure_z(Cont& cont) { return ensure_z(cont.data(), narrow_cast<std::ptrdiff_t>(cont.size())); } template <typename CharT, std::ptrdiff_t> class basic_string_span; namespace details { template <typename T> struct is_basic_string_span_oracle : std::false_type { }; template <typename CharT, std::ptrdiff_t Extent> struct is_basic_string_span_oracle<basic_string_span<CharT, Extent>> : std::true_type { }; template <typename T> struct is_basic_string_span : is_basic_string_span_oracle<std::remove_cv_t<T>> { }; } // namespace details // // string_span and relatives // template <typename CharT, std::ptrdiff_t Extent = dynamic_extent> class basic_string_span { public: using element_type = CharT; using pointer = std::add_pointer_t<element_type>; using reference = std::add_lvalue_reference_t<element_type>; using const_reference = std::add_lvalue_reference_t<std::add_const_t<element_type>>; using impl_type = span<element_type, Extent>; using index_type = typename impl_type::index_type; using iterator = typename impl_type::iterator; using const_iterator = typename impl_type::const_iterator; using reverse_iterator = typename impl_type::reverse_iterator; using const_reverse_iterator = typename impl_type::const_reverse_iterator; // default (empty) constexpr basic_string_span() noexcept = default; // copy constexpr basic_string_span(const basic_string_span& other) noexcept = default; // assign constexpr basic_string_span& operator=(const basic_string_span& other) noexcept = default; constexpr basic_string_span(pointer ptr, index_type length) : span_(ptr, length) {} constexpr basic_string_span(pointer firstElem, pointer lastElem) : span_(firstElem, lastElem) {} // From static arrays - if 0-terminated, remove 0 from the view // All other containers allow 0s within the length, so we do not remove them template <std::size_t N> constexpr basic_string_span(element_type (&arr)[N]) : span_(remove_z(arr)) {} template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>> constexpr basic_string_span(std::array<ArrayElementType, N>& arr) noexcept : span_(arr) {} template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>> constexpr basic_string_span(const std::array<ArrayElementType, N>& arr) noexcept : span_(arr) {} // Container signature should work for basic_string after C++17 version exists template <class Traits, class Allocator> // GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute // TODO: parser bug constexpr basic_string_span(std::basic_string<element_type, Traits, Allocator>& str) : span_(&str[0], narrow_cast<std::ptrdiff_t>(str.length())) {} template <class Traits, class Allocator> constexpr basic_string_span(const std::basic_string<element_type, Traits, Allocator>& str) : span_(&str[0], str.length()) {} // from containers. Containers must have a pointer type and data() function signatures template <class Container, class = std::enable_if_t< !details::is_basic_string_span<Container>::value && std::is_convertible<typename Container::pointer, pointer>::value && std::is_convertible<typename Container::pointer, decltype(std::declval<Container>().data())>::value>> constexpr basic_string_span(Container& cont) : span_(cont) {} template <class Container, class = std::enable_if_t< !details::is_basic_string_span<Container>::value && std::is_convertible<typename Container::pointer, pointer>::value && std::is_convertible<typename Container::pointer, decltype(std::declval<Container>().data())>::value>> constexpr basic_string_span(const Container& cont) : span_(cont) {} // from string_span template < class OtherValueType, std::ptrdiff_t OtherExtent, class = std::enable_if_t<std::is_convertible< typename basic_string_span<OtherValueType, OtherExtent>::impl_type, impl_type>::value>> constexpr basic_string_span(basic_string_span<OtherValueType, OtherExtent> other) : span_(other.data(), other.length()) {} template <index_type Count> constexpr basic_string_span<element_type, Count> first() const { return {span_.template first<Count>()}; } constexpr basic_string_span<element_type, dynamic_extent> first(index_type count) const { return {span_.first(count)}; } template <index_type Count> constexpr basic_string_span<element_type, Count> last() const { return {span_.template last<Count>()}; } constexpr basic_string_span<element_type, dynamic_extent> last(index_type count) const { return {span_.last(count)}; } template <index_type Offset, index_type Count> constexpr basic_string_span<element_type, Count> subspan() const { return {span_.template subspan<Offset, Count>()}; } constexpr basic_string_span<element_type, dynamic_extent> subspan(index_type offset, index_type count = dynamic_extent) const { return {span_.subspan(offset, count)}; } constexpr reference operator[](index_type idx) const { return span_[idx]; } constexpr reference operator()(index_type idx) const { return span_[idx]; } constexpr pointer data() const { return span_.data(); } constexpr index_type length() const noexcept { return span_.size(); } constexpr index_type size() const noexcept { return span_.size(); } constexpr index_type size_bytes() const noexcept { return span_.size_bytes(); } constexpr index_type length_bytes() const noexcept { return span_.length_bytes(); } constexpr bool empty() const noexcept { return size() == 0; } constexpr iterator begin() const noexcept { return span_.begin(); } constexpr iterator end() const noexcept { return span_.end(); } constexpr const_iterator cbegin() const noexcept { return span_.cbegin(); } constexpr const_iterator cend() const noexcept { return span_.cend(); } constexpr reverse_iterator rbegin() const noexcept { return span_.rbegin(); } constexpr reverse_iterator rend() const noexcept { return span_.rend(); } constexpr const_reverse_iterator crbegin() const noexcept { return span_.crbegin(); } constexpr const_reverse_iterator crend() const noexcept { return span_.crend(); } private: static impl_type remove_z(pointer const& sz, std::ptrdiff_t max) { return {sz, details::string_length(sz, max)}; } template <std::size_t N> static impl_type remove_z(element_type (&sz)[N]) { return remove_z(&sz[0], narrow_cast<std::ptrdiff_t>(N)); } impl_type span_; }; template <std::ptrdiff_t Extent = dynamic_extent> using string_span = basic_string_span<char, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using cstring_span = basic_string_span<const char, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using wstring_span = basic_string_span<wchar_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using cwstring_span = basic_string_span<const wchar_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using u16string_span = basic_string_span<char16_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using cu16string_span = basic_string_span<const char16_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using u32string_span = basic_string_span<char32_t, Extent>; template <std::ptrdiff_t Extent = dynamic_extent> using cu32string_span = basic_string_span<const char32_t, Extent>; // // to_string() allow (explicit) conversions from string_span to string // template <typename CharT, std::ptrdiff_t Extent> std::basic_string<typename std::remove_const<CharT>::type> to_string(basic_string_span<CharT, Extent> view) { return {view.data(), narrow_cast<std::size_t>(view.length())}; } template <typename CharT, typename Traits = typename std::char_traits<CharT>, typename Allocator = std::allocator<CharT>, typename gCharT, std::ptrdiff_t Extent> std::basic_string<CharT, Traits, Allocator> to_basic_string(basic_string_span<gCharT, Extent> view) { return {view.data(), narrow_cast<std::size_t>(view.length())}; } template <class ElementType, std::ptrdiff_t Extent> basic_string_span<const byte, details::calculate_byte_size<ElementType, Extent>::value> as_bytes(basic_string_span<ElementType, Extent> s) noexcept { GSL_SUPPRESS(type.1) // NO-FORMAT: attribute return {reinterpret_cast<const byte*>(s.data()), s.size_bytes()}; } template <class ElementType, std::ptrdiff_t Extent, class = std::enable_if_t<!std::is_const<ElementType>::value>> basic_string_span<byte, details::calculate_byte_size<ElementType, Extent>::value> as_writeable_bytes(basic_string_span<ElementType, Extent> s) noexcept { GSL_SUPPRESS(type.1) // NO-FORMAT: attribute return {reinterpret_cast<byte*>(s.data()), s.size_bytes()}; } // zero-terminated string span, used to convert // zero-terminated spans to legacy strings template <typename CharT, std::ptrdiff_t Extent = dynamic_extent> class basic_zstring_span { public: using value_type = CharT; using const_value_type = std::add_const_t<CharT>; using pointer = std::add_pointer_t<value_type>; using const_pointer = std::add_pointer_t<const_value_type>; using zstring_type = basic_zstring<value_type, Extent>; using const_zstring_type = basic_zstring<const_value_type, Extent>; using impl_type = span<value_type, Extent>; using string_span_type = basic_string_span<value_type, Extent>; constexpr basic_zstring_span(impl_type s) : span_(s) { // expects a zero-terminated span Expects(s[s.size() - 1] == '\0'); } // copy constexpr basic_zstring_span(const basic_zstring_span& other) = default; // move constexpr basic_zstring_span(basic_zstring_span&& other) = default; // assign constexpr basic_zstring_span& operator=(const basic_zstring_span& other) = default; // move assign constexpr basic_zstring_span& operator=(basic_zstring_span&& other) = default; constexpr bool empty() const noexcept { return span_.size() == 0; } constexpr string_span_type as_string_span() const noexcept { const auto sz = span_.size(); return {span_.data(), sz > 1 ? sz - 1 : 0}; } constexpr string_span_type ensure_z() const { return gsl::ensure_z(span_); } constexpr const_zstring_type assume_z() const noexcept { return span_.data(); } private: impl_type span_; }; template <std::ptrdiff_t Max = dynamic_extent> using zstring_span = basic_zstring_span<char, Max>; template <std::ptrdiff_t Max = dynamic_extent> using wzstring_span = basic_zstring_span<wchar_t, Max>; template <std::ptrdiff_t Max = dynamic_extent> using u16zstring_span = basic_zstring_span<char16_t, Max>; template <std::ptrdiff_t Max = dynamic_extent> using u32zstring_span = basic_zstring_span<char32_t, Max>; template <std::ptrdiff_t Max = dynamic_extent> using czstring_span = basic_zstring_span<const char, Max>; template <std::ptrdiff_t Max = dynamic_extent> using cwzstring_span = basic_zstring_span<const wchar_t, Max>; template <std::ptrdiff_t Max = dynamic_extent> using cu16zstring_span = basic_zstring_span<const char16_t, Max>; template <std::ptrdiff_t Max = dynamic_extent> using cu32zstring_span = basic_zstring_span<const char32_t, Max>; // operator == template <class CharT, std::ptrdiff_t Extent, class T, class = std::enable_if_t< details::is_basic_string_span<T>::value || std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>>>::value>> bool operator==(const gsl::basic_string_span<CharT, Extent>& one, const T& other) { const gsl::basic_string_span<std::add_const_t<CharT>> tmp(other); return std::equal(one.begin(), one.end(), tmp.begin(), tmp.end()); } template <class CharT, std::ptrdiff_t Extent, class T, class = std::enable_if_t< !details::is_basic_string_span<T>::value && std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>>>::value>> bool operator==(const T& one, const gsl::basic_string_span<CharT, Extent>& other) { const gsl::basic_string_span<std::add_const_t<CharT>> tmp(one); return std::equal(tmp.begin(), tmp.end(), other.begin(), other.end()); } // operator != template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t<std::is_convertible< T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>> bool operator!=(gsl::basic_string_span<CharT, Extent> one, const T& other) { return !(one == other); } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t< std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value && !gsl::details::is_basic_string_span<T>::value>> bool operator!=(const T& one, gsl::basic_string_span<CharT, Extent> other) { return !(one == other); } // operator< template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t<std::is_convertible< T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>> bool operator<(gsl::basic_string_span<CharT, Extent> one, const T& other) { const gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(other); return std::lexicographical_compare(one.begin(), one.end(), tmp.begin(), tmp.end()); } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t< std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value && !gsl::details::is_basic_string_span<T>::value>> bool operator<(const T& one, gsl::basic_string_span<CharT, Extent> other) { gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(one); return std::lexicographical_compare(tmp.begin(), tmp.end(), other.begin(), other.end()); } #ifndef _MSC_VER // VS treats temp and const containers as convertible to basic_string_span, // so the cases below are already covered by the previous operators template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename DataType = typename T::value_type, typename = std::enable_if_t< !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value && std::is_convertible<DataType*, CharT*>::value && std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>, DataType>::value>> bool operator<(gsl::basic_string_span<CharT, Extent> one, const T& other) { gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(other); return std::lexicographical_compare(one.begin(), one.end(), tmp.begin(), tmp.end()); } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename DataType = typename T::value_type, typename = std::enable_if_t< !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value && std::is_convertible<DataType*, CharT*>::value && std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>, DataType>::value>> bool operator<(const T& one, gsl::basic_string_span<CharT, Extent> other) { gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(one); return std::lexicographical_compare(tmp.begin(), tmp.end(), other.begin(), other.end()); } #endif // operator <= template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t<std::is_convertible< T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>> bool operator<=(gsl::basic_string_span<CharT, Extent> one, const T& other) { return !(other < one); } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t< std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value && !gsl::details::is_basic_string_span<T>::value>> bool operator<=(const T& one, gsl::basic_string_span<CharT, Extent> other) { return !(other < one); } #ifndef _MSC_VER // VS treats temp and const containers as convertible to basic_string_span, // so the cases below are already covered by the previous operators template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename DataType = typename T::value_type, typename = std::enable_if_t< !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value && std::is_convertible<DataType*, CharT*>::value && std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>, DataType>::value>> bool operator<=(gsl::basic_string_span<CharT, Extent> one, const T& other) { return !(other < one); } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename DataType = typename T::value_type, typename = std::enable_if_t< !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value && std::is_convertible<DataType*, CharT*>::value && std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>, DataType>::value>> bool operator<=(const T& one, gsl::basic_string_span<CharT, Extent> other) { return !(other < one); } #endif // operator> template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t<std::is_convertible< T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>> bool operator>(gsl::basic_string_span<CharT, Extent> one, const T& other) { return other < one; } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t< std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value && !gsl::details::is_basic_string_span<T>::value>> bool operator>(const T& one, gsl::basic_string_span<CharT, Extent> other) { return other < one; } #ifndef _MSC_VER // VS treats temp and const containers as convertible to basic_string_span, // so the cases below are already covered by the previous operators template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename DataType = typename T::value_type, typename = std::enable_if_t< !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value && std::is_convertible<DataType*, CharT*>::value && std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>, DataType>::value>> bool operator>(gsl::basic_string_span<CharT, Extent> one, const T& other) { return other < one; } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename DataType = typename T::value_type, typename = std::enable_if_t< !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value && std::is_convertible<DataType*, CharT*>::value && std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>, DataType>::value>> bool operator>(const T& one, gsl::basic_string_span<CharT, Extent> other) { return other < one; } #endif // operator >= template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t<std::is_convertible< T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>> bool operator>=(gsl::basic_string_span<CharT, Extent> one, const T& other) { return !(one < other); } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename = std::enable_if_t< std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value && !gsl::details::is_basic_string_span<T>::value>> bool operator>=(const T& one, gsl::basic_string_span<CharT, Extent> other) { return !(one < other); } #ifndef _MSC_VER // VS treats temp and const containers as convertible to basic_string_span, // so the cases below are already covered by the previous operators template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename DataType = typename T::value_type, typename = std::enable_if_t< !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value && std::is_convertible<DataType*, CharT*>::value && std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>, DataType>::value>> bool operator>=(gsl::basic_string_span<CharT, Extent> one, const T& other) { return !(one < other); } template < typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T, typename DataType = typename T::value_type, typename = std::enable_if_t< !gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value && std::is_convertible<DataType*, CharT*>::value && std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>, DataType>::value>> bool operator>=(const T& one, gsl::basic_string_span<CharT, Extent> other) { return !(one < other); } #endif } // namespace gsl #ifdef _MSC_VER #pragma warning(pop) #if _MSC_VER < 1910 #undef constexpr #pragma pop_macro("constexpr") #endif // _MSC_VER < 1910 #endif // _MSC_VER #endif // GSL_STRING_SPAN_H
{ "alphanum_fraction": 0.6972767808, "avg_line_length": 37.6902777778, "ext": "h", "hexsha": "d298039c0ab8d05af26f5546d7405acd6bd75203", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z", "max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Redchards/CVRP", "max_forks_repo_path": "include/gsl/string_span.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Redchards/CVRP", "max_issues_repo_path": "include/gsl/string_span.h", "max_line_length": 102, "max_stars_count": 2, "max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Redchards/CVRP", "max_stars_repo_path": "include/gsl/string_span.h", "max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z", "num_tokens": 6637, "size": 27137 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" #include "DirectionalLight.h" namespace Library { class ProxyModel; } namespace Rendering { class BlinnPhongMaterial; class BlinnPhongDemo final : public Library::DrawableGameComponent { public: BlinnPhongDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); BlinnPhongDemo(const BlinnPhongDemo&) = delete; BlinnPhongDemo(BlinnPhongDemo&&) = default; BlinnPhongDemo& operator=(const BlinnPhongDemo&) = default; BlinnPhongDemo& operator=(BlinnPhongDemo&&) = default; ~BlinnPhongDemo(); bool AnimationEnabled() const; void SetAnimationEnabled(bool enabled); void ToggleAnimation(); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); float DirectionalLightIntensity() const; void SetDirectionalLightIntensity(float intensity); const DirectX::XMFLOAT3& LightDirection() const; void RotateDirectionalLight(const DirectX::XMFLOAT2& amount); float SpecularIntensity() const; void SetSpecularIntensity(float intensity); float SpecularPower() const; void SetSpecularPower(float power); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: inline static const float RotationRate{ DirectX::XM_PI }; std::shared_ptr<BlinnPhongMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; winrt::com_ptr<ID3D11Buffer> mIndexBuffer; std::uint32_t mIndexCount{ 0 }; Library::DirectionalLight mDirectionalLight; std::unique_ptr<Library::ProxyModel> mProxyModel; float mModelRotationAngle{ 0.0f }; bool mAnimationEnabled{ true }; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.7738095238, "avg_line_length": 29.2727272727, "ext": "h", "hexsha": "356e99c1cbef0bfbc3b0bb53312dc5115f741af1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/3.3_Specular_Highlights/BlinnPhongDemo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/3.3_Specular_Highlights/BlinnPhongDemo.h", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/3.3_Specular_Highlights/BlinnPhongDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 508, "size": 1932 }
/* * Copyright (c) 2016-2020 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef basis_40d2b174_3729_49b6_a8d6_5b7ac75a2483_h #define basis_40d2b174_3729_49b6_a8d6_5b7ac75a2483_h #include <gslib/std.h> #include <gslib/string.h> #include <gslib/tree.h> #include <ariel/widget.h> namespace ui_editor { using gs::rect; using gs::rectf; using gs::point; using gs::pointf; using gs::string; using gs::list; using gs::unordered_map; using gs::gchar; using gs::uint; using gs::real; using gs::real32; using gs::ariel::painter; using gs::ariel::wsys_manager; using gs::ariel::unikey; typedef gs::ariel::widget core_widget; struct ui_proc_node; typedef unordered_map<string, string> ui_prop_map; typedef unordered_map<string, ui_proc_node> ui_proc_map; struct ui_proc_node { string args; string injection; }; // class ui_editor_configs // { // // }; struct ui_macro { string name; string definition; public: ui_macro(const string& n): name(n) {} ui_macro(const string& n, const string& d): name(n), definition(d) {} }; typedef list<string> ui_includes; typedef list<ui_macro> ui_macros; class ui_src_entry { public: void add_include(const string& str); void add_include_group(const string& strgroup); void add_macro(const string& name) { _macro_list.push_back(ui_macro(name)); } void add_macro(const string& name, const string& def) { _macro_list.push_back(ui_macro(name, def)); } void set_preproc(const string& preproc) { _preproc_injections = preproc; } void set_postproc(const string& postproc) { _postproc_injections = postproc; } void set_output(const string& str) { _output_name = str; } void set_export(const string& str) { _export_name = str; } const ui_includes& get_includes() const { return _include_list; } const ui_macros& get_macros() const { return _macro_list; } const string& get_preproc() const { return _preproc_injections; } const string& get_postproc() const { return _postproc_injections; } const string& get_output() const { return _output_name; } const string& get_export() const { return _export_name; } protected: ui_includes _include_list; ui_macros _macro_list; string _preproc_injections; string _postproc_injections; string _output_name; /* for output file name */ string _export_name; /* for export class name */ }; class ui_editor_context { public: typedef unordered_map<string, int> var_index_map; public: ui_src_entry& get_src_entry() { return _src_entry; } const ui_src_entry& const_src_entry() const { return _src_entry; } int acquire_variable_index(const string& vartype); int query_variable_index(const string& vartype) const; int acquire_variable_name(string& name, const string& vartype); protected: ui_src_entry _src_entry; var_index_map _index_map; }; class ui_node { public: rect position; string type; string name; string variable; bool is_instance; ui_prop_map prop_map; ui_proc_map proc_map; core_widget* assoc_widget; public: ui_node(): is_instance(false), assoc_widget(nullptr) {} }; typedef gs::_treenode_cpy_wrapper<ui_node> ui_node_wrapper; typedef gs::tree<ui_node, ui_node_wrapper> ui_tree; typedef core_widget* (__stdcall *pfn_create_widget)(wsys_manager* wsys, core_widget* parent, ui_node& uinode); class ui_transparent_layer: public core_widget { public: ui_transparent_layer(wsys_manager* m); void install_reflection_widget(core_widget* refw); core_widget* get_reflection_widget() const { return _reflection_widget; } public: virtual ~ui_transparent_layer(); virtual void on_reflection_close(); virtual void on_reflection_show(bool b); virtual void on_reflection_enable(bool b); virtual void on_reflection_move(const rect& rc); virtual void on_reflection_char(uint um, uint ch) {} virtual void on_reflection_caret() {} virtual void on_reflection_capture(bool b) {} virtual void on_reflection_focus(bool b) {} virtual void on_reflection_scroll(const point& pt, real32 scr, bool vert) {} virtual void on_reflection_accelerator(unikey key, uint mask) {} protected: core_widget* _reflection_widget; protected: void sync_size_with_reflection(); }; class ui_edit_control; class ui_editor_layer: public ui_transparent_layer { public: enum size_orient { so_none, so_n, so_s, so_e, so_w, so_ne, so_nw, so_se, so_sw, }; public: ui_editor_layer(wsys_manager* m); void initialize(ui_node& uinode); void install_reflection_widget(core_widget* refw); ui_node* get_ui_node() const { return _assoc_ui_node; } public: virtual void on_reflection_press(uint um, unikey uk, const point& pt); virtual void on_reflection_click(uint um, unikey uk, const point& pt); virtual void on_reflection_hover(uint um, const point& pt); virtual void on_reflection_leave(uint um, const point& pt); virtual void on_reflection_keydown(uint um, unikey uk); virtual void on_reflection_keyup(uint um, unikey uk); protected: ui_node* _assoc_ui_node; ui_edit_control* _edit_ctl; protected: void refresh_cursor(const point& pt); size_orient get_size_orient(const point& pt, int accuracy = 3) const; void try_install_edit_control(const point& pt); void try_uninstall_edit_control(); void refresh_edit_control(uint um, const point& pt); }; extern bool ui_create_widgets(wsys_manager* wsys, core_widget* root_layer, ui_tree& uicore); //extern bool ui_; } #endif
{ "alphanum_fraction": 0.7088499359, "avg_line_length": 31.0486725664, "ext": "h", "hexsha": "ad2513839fa0711a0e2cbb507cf621699eb03e43", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "proj/uieditor/basis.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "proj/uieditor/basis.h", "max_line_length": 110, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "proj/uieditor/basis.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 1701, "size": 7017 }
/** * @file tracker.h * @brief Beamforming and speaker tracking with a spherical microphone array. * @author John McDonough */ #ifndef TRACKER_H #define TRACKER_H #include <stdio.h> #include <assert.h> #include <float.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_complex_math.h> #include "common/refcount.h" #include "common/jexception.h" #include "stream/stream.h" #include "beamformer/spectralinfoarray.h" #include "modulated/modulated.h" #include "aec/aec.h" // ----- definition of class 'BaseDecomposition' ----- // class BaseDecomposition : public Countable { public: class SubbandEntry { public: SubbandEntry(unsigned subbandX, const gsl_complex& Bkl); unsigned subbandX() const { return subbandX_; } gsl_complex bkl() const { return bkl_; } void* operator new(size_t sz) { return memoryManager().new_elem(); } void operator delete(void* e) { memoryManager().delete_elem(e); } static MemoryManager<SubbandEntry>& memoryManager(); private: const unsigned subbandX_; const gsl_complex bkl_; }; class GreaterThan { public: bool operator()(SubbandEntry* sbX1, SubbandEntry* sbX2) { return (gsl_complex_abs(sbX1->bkl()) > gsl_complex_abs(sbX2->bkl())); } }; class Iterator; class SubbandList : public Countable { public: SubbandList(const gsl_vector_complex* bkl, unsigned useSubbandsN = 0); ~SubbandList(); unsigned useSubbandsN() const { return useSubbandsN_; } SubbandEntry** subbands() { return subbands_; } friend class Iterator; private: const unsigned subbandsN_; const unsigned useSubbandsN_; SubbandEntry** subbands_; }; typedef refcountable_ptr<SubbandList> SubbandListPtr; class Iterator { public: Iterator(const SubbandListPtr& subbandList) : subbandX_(0), useSubbandsN_(subbandList->useSubbandsN()), subbands_(subbandList->subbands()) { } void operator++(int) { subbandX_++; } bool more() { return subbandX_ < useSubbandsN_; } const SubbandEntry& operator*() { return *(subbands_[subbandX_]); } private: unsigned subbandX_; const unsigned useSubbandsN_; SubbandEntry** subbands_; }; public: BaseDecomposition(unsigned orderN, unsigned subbandsN, double a, double sampleRate, unsigned useSubbandsN = 0, bool spatial = false); ~BaseDecomposition(); unsigned orderN() const { return orderN_; } unsigned modesN() const { return modesN_; } unsigned subbandsN2() const { return subbandsN2_; } unsigned subbandsN() const { return subbandsN_; } unsigned useSubbandsN() const { return useSubbandsN_; } unsigned subbandLengthN() const { return subbandLengthN_; } SubbandListPtr subbandList() { return subbandList_; } virtual void reset(); static gsl_complex harmonic(int order, int degree, double theta, double phi); gsl_complex harmonic(int order, int degree, unsigned channelX) const; static gsl_complex harmonic_deriv_polar_angle(int order, int degree, double theta, double phi); static gsl_complex harmonic_deriv_azimuth(int order, int degree, double theta, double phi); static gsl_complex modal_coefficient(unsigned order, double ka); gsl_complex modal_coefficient(unsigned order, unsigned subbandX) const; virtual void transform(const gsl_vector_complex* initial, gsl_vector_complex* transformed) { } virtual void estimate_Bkl(double theta, double phi, const gsl_vector_complex* snapshot, unsigned subbandX) = 0; virtual void calculate_gkl(double theta, double phi, unsigned subbandX) = 0; virtual const gsl_matrix_complex* linearize(gsl_vector* xk, int frame_no) = 0; virtual const gsl_vector_complex* predicted_observation(gsl_vector* xk, int frame_no) = 0; #ifdef ENABLE_LEGACY_BTK_API static gsl_complex harmonicDerivPolarAngle(int order, int degree, double theta, double phi){ return harmonic_deriv_polar_angle(order, degree, theta, phi); } static gsl_complex harmonicDerivAzimuth(int order, int degree, double theta, double phi){ return harmonic_deriv_azimuth(order, degree, theta, phi); } static gsl_complex modalCoefficient(unsigned order, double ka){ return modal_coefficient(order, ka); } #endif static const unsigned StateN_; static const unsigned ChannelsN_; static const gsl_complex ComplexZero_; static const gsl_complex ComplexOne_; static const double SpeedOfSound_; protected: static gsl_complex calc_in_(int n); void set_eigenmike_geometry_(); gsl_complex calc_Gnm_(unsigned subbandX, int n, int m, double theta, double phi); gsl_complex calc_dGnm_dtheta_(unsigned subbandX, int n, int m, double theta, double phi); static double calc_Pnm_(int order, int degree, double theta); static double calc_dPnm_dtheta_(int n, int m, double theta); static double calc_normalization_(int order, int degree); const unsigned orderN_; const unsigned modesN_; const unsigned subbandsN_; const unsigned subbandsN2_; const unsigned useSubbandsN_; const unsigned subbandLengthN_; const double samplerate_; const double a_; gsl_vector_complex** bn_; gsl_vector* theta_s_; gsl_vector* phi_s_; gsl_vector_complex** spherical_component_; gsl_vector_complex* bkl_; gsl_vector_complex* dbkl_dtheta_; gsl_vector_complex* dbkl_dphi_; gsl_vector_complex** gkl_; gsl_vector_complex** dgkl_dtheta_; gsl_vector_complex** dgkl_dphi_; gsl_vector_complex* vkl_; gsl_matrix_complex* Hbar_k_; gsl_vector_complex* yhat_k_; SubbandListPtr subbandList_; }; typedef refcountable_ptr<BaseDecomposition> BaseDecompositionPtr; // ----- definition of class 'ModalDecomposition' ----- // class ModalDecomposition : public BaseDecomposition { public: ModalDecomposition(unsigned orderN, unsigned subbandsN, double a, double sampleRate, unsigned useSubbandsN = 0); ~ModalDecomposition() { } virtual void estimate_Bkl(double theta, double phi, const gsl_vector_complex* snapshot, unsigned subbandX); virtual void transform(const gsl_vector_complex* initial, gsl_vector_complex* transformed); virtual const gsl_matrix_complex* linearize(gsl_vector* xk, int frame_no); virtual const gsl_vector_complex* predicted_observation(gsl_vector* xk, int frame_no); virtual void calculate_gkl(double theta, double phi, unsigned subbandX); }; typedef Inherit<ModalDecomposition, BaseDecompositionPtr> ModalDecompositionPtr; // ----- definition of class 'SpatialDecomposition' ----- // class SpatialDecomposition : public BaseDecomposition { public: SpatialDecomposition(unsigned orderN, unsigned subbandsN, double a, double sampleRate, unsigned useSubbandsN = 0); ~SpatialDecomposition() { } virtual void estimate_Bkl(double theta, double phi, const gsl_vector_complex* snapshot, unsigned subbandX); virtual const gsl_matrix_complex* linearize(gsl_vector* xk, int frame_no); virtual const gsl_vector_complex* predicted_observation(gsl_vector* xk, int frame_no); virtual void calculate_gkl(double theta, double phi, unsigned subbandX); }; typedef Inherit<SpatialDecomposition, BaseDecompositionPtr> SpatialDecompositionPtr; // ----- definition of class 'BaseSphericalArrayTracker' ----- // class BaseSphericalArrayTracker : public VectorFloatFeatureStream { typedef list<VectorComplexFeatureStreamPtr> ChannelList_; typedef ChannelList_::iterator ChannelIterator_; typedef BaseDecomposition::SubbandEntry SubbandEntry; typedef BaseDecomposition::SubbandListPtr SubbandListPtr; typedef BaseDecomposition::Iterator Iterator; public: BaseSphericalArrayTracker(BaseDecompositionPtr& baseDecomposition, double sigma2_u = 10.0, double sigma2_v = 10.0, double sigma2_init = 10.0, unsigned maxLocalN = 1, const String& nm = "BaseSphericalArrayTracker"); ~BaseSphericalArrayTracker(); virtual const gsl_vector_float* next(int frame_no = -5) = 0; virtual void reset(); unsigned chanN() const { return channelList_.size(); } void set_channel(VectorComplexFeatureStreamPtr& chan); void set_V(const gsl_matrix_complex* Vk, unsigned subbandX); void next_speaker(); void set_initial_position(double theta, double phi); #ifdef ENABLE_LEGACY_BTK_API void setChannel(VectorComplexFeatureStreamPtr& chan){ set_channel(chan); } void setV(const gsl_matrix_complex* Vk, unsigned subbandX){ set_V(Vk, subbandX); } void nextSpeaker(){ next_speaker(); } void setInitialPosition(double theta, double phi){ set_initial_position(theta, phi); } #endif protected: static void printMatrix_(const gsl_matrix_complex* mat); static void printMatrix_(const gsl_matrix* mat); static void printVector_(const gsl_vector_complex* vec); static void printVector_(const gsl_vector* vec); static double calc_givens_rotation_(double v1, double v2, double& c, double& s); static void apply_givens_rotation_(double v1, double v2, double c, double s, double& v1p, double& v2p); void alloc_image_(); void update_(const gsl_matrix_complex* Hbar_k, const gsl_vector_complex* yhat_k, const SubbandListPtr& subbandList); void lower_triangularize_(); void copy_position_(); void check_physical_constraints_(); double calc_residual_(); void realify_(const gsl_matrix_complex* Hbar_k, const gsl_vector_complex* yhat_k); void realify_residual_(); static const unsigned StateN_; static const gsl_complex ComplexZero_; static const gsl_complex ComplexOne_; static const double Epsilon_; static const double Tolerance_; bool firstFrame_; const unsigned subbandsN_; const unsigned subbandsN2_; const unsigned useSubbandsN_; const unsigned modesN_; const unsigned subbandLengthN_; const unsigned observationN_; const unsigned maxLocalN_; bool is_end_; const double sigma_init_; SnapShotArrayPtr snapshot_array_; BaseDecompositionPtr base_decomposition_; ChannelList_ channelList_; // these quantities are stored as Cholesky factors gsl_matrix* U_; gsl_matrix* V_; gsl_matrix* K_k_k1_; // work space for state estimate update gsl_matrix* prearray_; gsl_vector_complex* vk_; gsl_matrix* Hbar_k_; gsl_vector* yhat_k_; gsl_vector* correction_; gsl_vector* position_; gsl_vector* eta_i_; gsl_vector* delta_; gsl_vector_complex* residual_; gsl_vector* residual_real_; gsl_vector* scratch_; }; typedef Inherit<BaseSphericalArrayTracker, VectorFloatFeatureStreamPtr> BaseSphericalArrayTrackerPtr; // ----- definition of class 'ModalSphericalArrayTracker' ----- // class ModalSphericalArrayTracker : public BaseSphericalArrayTracker { typedef list<VectorComplexFeatureStreamPtr> ChannelList_; typedef ChannelList_::iterator ChannelIterator_; public: ModalSphericalArrayTracker(ModalDecompositionPtr& modalDecomposition, double sigma2_u = 10.0, double sigma2_v = 10.0, double sigma2_init = 10.0, unsigned maxLocalN = 1, const String& nm = "ModalSphericalArrayTracker"); ~ModalSphericalArrayTracker() { } const gsl_vector_float* next(int frame_no = -5); }; typedef Inherit<ModalSphericalArrayTracker, VectorFloatFeatureStreamPtr> ModalSphericalArrayTrackerPtr; // ----- definition of class 'SpatialSphericalArrayTracker' ----- // class SpatialSphericalArrayTracker : public BaseSphericalArrayTracker { typedef list<VectorComplexFeatureStreamPtr> ChannelList_; typedef ChannelList_::iterator ChannelIterator_; public: SpatialSphericalArrayTracker(SpatialDecompositionPtr& spatialDecomposition, double sigma2_u = 10.0, double sigma2_v = 10.0, double sigma2_init = 10.0, unsigned maxLocalN = 1, const String& nm = "SpatialSphericalArrayTracker"); ~SpatialSphericalArrayTracker() { } const gsl_vector_float* next(int frame_no= -5); }; typedef Inherit<SpatialSphericalArrayTracker, VectorFloatFeatureStreamPtr> SpatialSphericalArrayTrackerPtr; // ----- definition of class 'PlaneWaveSimulator' ----- // class PlaneWaveSimulator : public VectorComplexFeatureStream { public: PlaneWaveSimulator(const VectorComplexFeatureStreamPtr& source, ModalDecompositionPtr& modalDecomposition, unsigned channelX, double theta, double phi, const String& nm = "Plane Wave Simulator"); ~PlaneWaveSimulator(); const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); private: static const gsl_complex ComplexZero_; const unsigned subbandsN_; const unsigned subbandsN2_; const unsigned channelX_; const double theta_; const double phi_; VectorComplexFeatureStreamPtr source_; ModalDecompositionPtr modalDecomposition_; gsl_vector_complex* subbandCoefficients_; }; typedef Inherit<PlaneWaveSimulator, VectorComplexFeatureStreamPtr> PlaneWaveSimulatorPtr; #ifdef HAVE_GSL_V11X int gsl_matrix_complex_add( gsl_matrix_complex *am, gsl_matrix_complex *bm ) { if( am->size1 != bm->size1 ){ fprintf(stderr,"Dimension error \n",am->size1, bm->size1 ); return 0; } if( am->size2 != bm->size2 ){ fprintf(stderr,"Dimension error \n",am->size2, bm->size2 ); return 0; } for(size_t i=0;i<am->size1;i++){ for(size_t j=0;j<am->size2;j++){ gsl_complex val = gsl_complex_add( gsl_matrix_complex_get(am,i,j), gsl_matrix_complex_get(bm,i,j) ); gsl_matrix_complex_set(am,i,j,val); } } return 1; } int gsl_vector_complex_add( gsl_vector_complex *av, gsl_vector_complex *bv ) { if( av->size != bv->size ){ fprintf(stderr,"Dimension error \n",av->size, bv->size); return 0; } for(size_t i=0;i<av->size;i++){ gsl_complex val = gsl_complex_add( gsl_vector_complex_get(av,i), gsl_vector_complex_get(bv,i) ); gsl_vector_complex_set(av,i,val); } return 1; } int gsl_vector_complex_sub( const gsl_vector_complex *av, const gsl_vector_complex *bv ) { if( av->size != bv->size ){ fprintf(stderr,"Dimension error \n",av->size, bv->size); return 0; } for(size_t i=0;i<av->size;i++){ gsl_complex val = gsl_complex_sub( gsl_vector_complex_get(av,i), gsl_vector_complex_get(bv,i) ); gsl_vector_complex_set((gsl_vector_complex*)av,i,val); } return 1; } #endif /* End of HAVE_GSL_V11X */ #endif
{ "alphanum_fraction": 0.744891598, "avg_line_length": 34.538277512, "ext": "h", "hexsha": "72401ef9452a39dd238d9993ac78a559611e8001", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/beamformer/tracker.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/beamformer/tracker.h", "max_line_length": 151, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/beamformer/tracker.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 3704, "size": 14437 }
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, D. Strubbe This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <ctype.h> #include <math.h> #include <gsl/gsl_complex_math.h> #include "symbols.h" #include "gsl_userdef.h" /* The symbol table: a chain of `struct symrec'. */ symrec *sym_table = (symrec *)0; void str_tolower(char *in) { for(; *in; in++) *in = (char)tolower(*in); } void sym_mark_table_used () { symrec *ptr; for (ptr = sym_table; ptr != (symrec *) 0; ptr = (symrec *)ptr->next) { ptr->used = 1; } } symrec *putsym (const char *sym_name, symrec_type sym_type) { symrec *ptr; ptr = (symrec *)malloc(sizeof(symrec)); /* names are always lowercase */ ptr->name = strdup(sym_name); str_tolower(ptr->name); ptr->def = 0; ptr->used = 0; ptr->type = sym_type; GSL_SET_COMPLEX(&ptr->value.c, 0, 0); /* set value to 0 even if fctn. */ ptr->next = (struct symrec *)sym_table; sym_table = ptr; return ptr; } symrec *getsym (const char *sym_name) { symrec *ptr; for (ptr = sym_table; ptr != (symrec *) 0; ptr = (symrec *)ptr->next) if (strcasecmp(ptr->name,sym_name) == 0){ ptr->used = 1; return ptr; } return (symrec *) 0; } int rmsym (const char *sym_name) { symrec *ptr, *prev; for (prev = (symrec *) 0, ptr = sym_table; ptr != (symrec *) 0; prev = ptr, ptr = ptr->next) if (strcasecmp(ptr->name,sym_name) == 0){ if(prev == (symrec *) 0) sym_table = ptr->next; else prev->next = ptr->next; free(ptr->name); free(ptr); return 1; } return 0; } struct init_fntc{ char *fname; int nargs; gsl_complex (*fnctptr)(); }; void sym_notdef (symrec *sym) { fprintf(stderr, "Parser error: symbol '%s' used before being defined.\n", sym->name); exit(1); } void sym_redef (symrec *sym) { fprintf(stderr, "Parser warning: redefining symbol, previous value "); sym_print(stderr, sym); fprintf(stderr, "\n"); } void sym_wrong_arg (symrec *sym) { if(sym->type == S_BLOCK) { fprintf(stderr, "Parser error: block name '%s' used in variable context.\n", sym->name); } else if(sym->type == S_STR) { fprintf(stderr, "Parser error: string variable '%s' used in expression context.\n", sym->name); } else { fprintf(stderr, "Parser error: function '%s' requires %d argument(s).\n", sym->name, sym->nargs); } exit(1); } static struct init_fntc arith_fncts[] = { {"sqrt", 1, (gsl_complex (*)()) &gsl_complex_sqrt}, {"exp", 1, (gsl_complex (*)()) &gsl_complex_exp}, {"ln", 1, (gsl_complex (*)()) &gsl_complex_log}, {"log", 1, (gsl_complex (*)()) &gsl_complex_log}, {"log10", 1, (gsl_complex (*)()) &gsl_complex_log10}, {"logb", 2, (gsl_complex (*)()) &gsl_complex_log_b}, /* takes two arguments logb(z, b) = log_b(z) */ {"arg", 1, (gsl_complex (*)()) &gsl_complex_carg}, {"abs", 1, (gsl_complex (*)()) &gsl_complex_cabs}, {"abs2", 1, (gsl_complex (*)()) &gsl_complex_cabs2}, {"logabs", 1, (gsl_complex (*)()) &gsl_complex_clogabs}, {"conjg", 1, (gsl_complex (*)()) &gsl_complex_conjugate}, {"inv", 1, (gsl_complex (*)()) &gsl_complex_inverse}, {"sin", 1, (gsl_complex (*)()) &gsl_complex_sin}, {"cos", 1, (gsl_complex (*)()) &gsl_complex_cos}, {"tan", 1, (gsl_complex (*)()) &gsl_complex_tan}, {"sec", 1, (gsl_complex (*)()) &gsl_complex_sec}, {"csc", 1, (gsl_complex (*)()) &gsl_complex_csc}, {"cot", 1, (gsl_complex (*)()) &gsl_complex_cot}, {"asin", 1, (gsl_complex (*)()) &gsl_complex_arcsin}, {"acos", 1, (gsl_complex (*)()) &gsl_complex_arccos}, {"atan", 1, (gsl_complex (*)()) &gsl_complex_arctan}, {"atan2", 2, (gsl_complex (*)()) &gsl_complex_arctan2}, /* takes two arguments atan2(y,x) = atan(y/x) */ {"asec", 1, (gsl_complex (*)()) &gsl_complex_arcsec}, {"acsc", 1, (gsl_complex (*)()) &gsl_complex_arccsc}, {"acot", 1, (gsl_complex (*)()) &gsl_complex_arccot}, {"sinh", 1, (gsl_complex (*)()) &gsl_complex_sinh}, {"cosh", 1, (gsl_complex (*)()) &gsl_complex_cosh}, {"tanh", 1, (gsl_complex (*)()) &gsl_complex_tanh}, {"sech", 1, (gsl_complex (*)()) &gsl_complex_sech}, {"csch", 1, (gsl_complex (*)()) &gsl_complex_csch}, {"coth", 1, (gsl_complex (*)()) &gsl_complex_coth}, {"asinh", 1, (gsl_complex (*)()) &gsl_complex_arcsinh}, {"acosh", 1, (gsl_complex (*)()) &gsl_complex_arccosh}, {"atanh", 1, (gsl_complex (*)()) &gsl_complex_arctanh}, {"asech", 1, (gsl_complex (*)()) &gsl_complex_arcsech}, {"acsch", 1, (gsl_complex (*)()) &gsl_complex_arccsch}, {"acoth", 1, (gsl_complex (*)()) &gsl_complex_arccoth}, /* user-defined step function. this is not available in GSL, but we use GSL namespacing and macros here. */ {"step", 1, (gsl_complex (*)()) &gsl_complex_step_real}, /* Minimum and maximum of two arguments (comparing real parts) */ {"min", 2, (gsl_complex (*)()) &gsl_complex_min_real}, {"max", 2, (gsl_complex (*)()) &gsl_complex_max_real}, {"erf", 1, (gsl_complex (*)()) &gsl_complex_erf}, {"realpart", 1, (gsl_complex (*)()) &gsl_complex_realpart}, {"imagpart", 1, (gsl_complex (*)()) &gsl_complex_imagpart}, {"round", 1, (gsl_complex (*)()) &gsl_complex_round}, {"floor", 1, (gsl_complex (*)()) &gsl_complex_floor}, {"ceiling", 1, (gsl_complex (*)()) &gsl_complex_ceiling}, {"rand", 0, (gsl_complex (*)()) &gsl_complex_rand}, {0, 0, 0} }; struct init_cnst{ char *fname; double re; double im; }; static struct init_cnst arith_cnts[] = { {"pi", M_PI, 0}, {"e", M_E, 0}, {"i", 0, 1}, {"true", 1, 0}, {"yes", 1, 0}, {"false", 0, 0}, {"no", 0, 0}, {0, 0, 0} }; char *reserved_symbols[] = { "x", "y", "z", "r", "w", "t", 0 }; void sym_init_table () /* puts arithmetic functions in table. */ { int i; symrec *ptr; for (i = 0; arith_fncts[i].fname != 0; i++){ ptr = putsym (arith_fncts[i].fname, S_FNCT); ptr->def = 1; ptr->used = 1; ptr->nargs = arith_fncts[i].nargs; ptr->value.fnctptr = arith_fncts[i].fnctptr; } /* now the constants */ for (i = 0; arith_cnts[i].fname != 0; i++){ ptr = putsym(arith_cnts[i].fname, S_CMPLX); ptr->def = 1; ptr->used = 1; GSL_SET_COMPLEX(&ptr->value.c, arith_cnts[i].re, arith_cnts[i].im); } } void sym_end_table() { symrec *ptr, *ptr2; for (ptr = sym_table; ptr != NULL;){ free(ptr->name); switch(ptr->type){ case S_STR: free(ptr->value.str); break; case S_BLOCK: if(ptr->value.block->n > 0){ free(ptr->value.block->lines); } free(ptr->value.block); break; case S_CMPLX: case S_FNCT: break; } ptr2 = ptr->next; free(ptr); ptr = ptr2; } sym_table = NULL; } /* this function is defined in src/basic/varinfo_low.c */ int varinfo_variable_exists(const char * var_name); void sym_output_table(int only_unused, int mpiv_node) { FILE *f; symrec *ptr; int any_unused = 0; if(mpiv_node != 0) { return; } if(only_unused) { f = stderr; } else { f = stdout; } for(ptr = sym_table; ptr != NULL; ptr = ptr->next){ if(only_unused && ptr->used == 1) continue; if(only_unused && varinfo_variable_exists(ptr->name)) continue; if(any_unused == 0) { fprintf(f, "\nParser warning: possible mistakes in input file.\n"); fprintf(f, "List of variable assignments not used by parser:\n"); any_unused = 1; } sym_print(f, ptr); } if(any_unused == 1) { fprintf(f, "\n"); } } void sym_print(FILE *f, const symrec *ptr) { fprintf(f, "%s", ptr->name); switch(ptr->type){ case S_CMPLX: if(fabs(GSL_IMAG(ptr->value.c)) < 1.0e-14){ fprintf(f, " = %f\n", GSL_REAL(ptr->value.c)); } else { fprintf(f, " = (%f,%f)\n", GSL_REAL(ptr->value.c), GSL_IMAG(ptr->value.c)); } break; case S_STR: fprintf(f, " = \"%s\"\n", ptr->value.str); break; case S_BLOCK: fprintf(f, "%s\n", " <= BLOCK"); break; case S_FNCT: fprintf(f, "%s\n", " <= FUNCTION"); break; } }
{ "alphanum_fraction": 0.5971563981, "avg_line_length": 27.2676923077, "ext": "c", "hexsha": "12d95987f26290c4f1860e03cd305fc8c96eea31", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "shunsuke-sato/octopus", "max_forks_repo_path": "liboct_parser/symbols.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_issues_repo_issues_event_max_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_issues_event_min_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "shunsuke-sato/octopus", "max_issues_repo_path": "liboct_parser/symbols.c", "max_line_length": 107, "max_stars_count": 4, "max_stars_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "shunsuke-sato/octopus", "max_stars_repo_path": "liboct_parser/symbols.c", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "num_tokens": 2937, "size": 8862 }
/* * Copyright 2019 Virtru Corporation * * SPDX - License Identifier: BSD-3-Clause-Clear * */ // // TDF SDK // // Created by Sujan Reddy on 2019/04/07. // #ifndef VIRTRU_BYTES_H #define VIRTRU_BYTES_H #include <gsl/span> #include <array> /// This provides a simple wrapper around gsl to work with bytes. namespace virtru::crypto { /// Constants constexpr auto kKeyLength = 32; constexpr auto kIVLength = 16; /// /// Define the bytes(Read only). /// template <std::ptrdiff_t Extent = gsl :: dynamic_extent> using BytesT = gsl::span <const gsl::byte, Extent>; using Bytes = BytesT<>; /// /// Wrapper around std::array /// template <std::size_t N> using ByteArray = std::array <gsl :: byte, N>; using WrappedKey = ByteArray<kKeyLength>; using IV = ByteArray<kIVLength>; /// /// Define writeable bytes /// template <std::ptrdiff_t Extent = gsl::dynamic_extent> using WriteableBytesT = gsl::span <gsl::byte, Extent>; using WriteableBytes = WriteableBytesT<>; template <std :: ptrdiff_t Extent > constexpr auto toBytes(BytesT < Extent > data) noexcept { return data; } template <std::ptrdiff_t Extent> constexpr auto toWriteableBytes(WriteableBytesT <Extent> data) noexcept { return data; } /// Adding constness template <std::ptrdiff_t Extent> constexpr auto toBytes (gsl::span <gsl::byte, Extent> data) noexcept { return BytesT <Extent> {data}; } /// Any containers inherited from basic_string<ElementType> to bytes(Read only). template <typename ElementType, std::ptrdiff_t Extent, typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> > auto toBytes (gsl::span <ElementType, Extent> data) noexcept { return as_bytes(data); } /// Any containers inherited from basic_string<ElementType> to writable bytes. template <typename ElementType, std::ptrdiff_t Extent, typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> > auto toWriteableBytes(gsl::span <ElementType, Extent> data) noexcept { return as_writeable_bytes(data); } /// Form std::array to bytes(Read only). template <typename ElementType, std::size_t N, typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> > constexpr auto toBytes(const std::array <ElementType, N> & data) noexcept { return toBytes(gsl::span <const ElementType, N > { data }); } /// Form std::array to writable bytes. template <typename ElementType, std::size_t N, typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> > constexpr auto toWriteableBytes(std::array <ElementType, N> & data) noexcept { return toWriteableBytes(gsl::span <ElementType, N> { data }); } // Form Plain old C array to bytes(Read only). template <typename ElementType, std::size_t N, typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> > constexpr auto toBytes(ElementType (& arr)[N]) noexcept { return toBytes(gsl::make_span(arr)); } // Form Plain old C array to writable bytes. template <typename ElementType, std::size_t N, typename = std::enable_if_t <std::has_unique_object_representations_v <ElementType>> > constexpr auto toWriteableBytes(ElementType(&arr)[N]) noexcept { return toWriteableBytes(gsl::make_span(arr)); } // From container(std::string/std::vector<char>) to bytes(Read only). template <class Cont, typename = std::enable_if_t <std::has_unique_object_representations_v <std::remove_reference_t < decltype(* std::declval <const Cont&> ().data ())>> > > constexpr auto toBytes(const Cont & cont) noexcept { return toBytes(gsl::make_span(cont)); } // From container(std::string/std::vector<char>) to to writable bytes. template <class Cont, typename = std::enable_if_t <std::has_unique_object_representations_v <std::remove_reference_t < decltype(* std::declval <Cont &> ().data ())>> > > constexpr auto toWriteableBytes(Cont & cont) noexcept { return toWriteableBytes(gsl::make_span(cont)); } /// /// Simple conversions. /// template <typename T> using ConvertibleToBytes = decltype(toBytes(std::declval <const T&> ())); template <typename T, std::ptrdiff_t Extent = gsl::dynamic_extent> inline constexpr bool isBytes = std::is_convertible_v <const T&, BytesT <Extent>>; template <typename T> using ExplicitlyConvertibleToBytes = std::enable_if_t <! isBytes <T>, ConvertibleToBytes <T>>; template <typename T, typename = ConvertibleToBytes <T>> auto toDynamicBytes (const T& t) { return Bytes { toBytes(t) }; } template <typename T, typename = ExplicitlyConvertibleToBytes <T>> auto toDynamicBytesExplicitly (const T& t) { return toDynamicBytes(t); } inline unsigned char* toUchar(gsl::byte* p) { return reinterpret_cast <unsigned char *> (p); } inline const unsigned char *toUchar (const gsl::byte *p) { return reinterpret_cast <const unsigned char *> (p); } template <std::ptrdiff_t Extent> auto toUchar(BytesT<Extent> src) { return gsl::span <const unsigned char, Extent> {reinterpret_cast <const unsigned char *> (src.data ()), src.size()}; } inline char* toChar(gsl::byte *p) { return reinterpret_cast <char*> (p); } inline const char* toChar(const gsl::byte* p) { return reinterpret_cast <const char *> (p); } template <std::ptrdiff_t Extent> auto toChar(BytesT <Extent> src) { return gsl :: span <const char, Extent> { reinterpret_cast <const char*> (src.data()), src.size ()}; } template <std::ptrdiff_t Extent> auto toChar(WriteableBytesT <Extent> src) { return gsl::span <const char, Extent> { reinterpret_cast <const char *> (src.data()), src.size ()}; } inline auto finalizeSize(WriteableBytes& buffer, const int& size) { return gsl::finally( [&buffer, &size ] { buffer = buffer.first(size); }); } } // namespace virtru::crypto #endif //VIRTRU_BYTES_H
{ "alphanum_fraction": 0.6434501845, "avg_line_length": 34.5957446809, "ext": "h", "hexsha": "6de72185fec91d21997ee77adc40a801a2c26f8b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-03-09T18:40:47.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-09T18:40:47.000Z", "max_forks_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "opentdf/client-cpp", "max_forks_repo_path": "src/lib/include/crypto/bytes.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_issues_repo_issues_event_max_datetime": "2022-03-28T22:44:54.000Z", "max_issues_repo_issues_event_min_datetime": "2022-01-31T14:42:51.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "opentdf/client-cpp", "max_issues_repo_path": "src/lib/include/crypto/bytes.h", "max_line_length": 124, "max_stars_count": null, "max_stars_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "opentdf/client-cpp", "max_stars_repo_path": "src/lib/include/crypto/bytes.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1592, "size": 6504 }
// ******************** Functions for segSiteHMM #include "stdio.h" #include "math.h" #include "segSites.h" #include "../hmm/popGenTools.h" #include "../hmm/numerical.h" #include "assert.h" #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_min.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf.h> //core function for probs double my_h(double q, void * p){ struct my_f_params * params = (struct my_f_params *) p; double beta = params->beta; int i = params->i; int n = params->n; return ((1.0 - exp(-2.0 * beta * (1.0 - q))) / (1.0 - exp(-2.0 * beta))) \ * (2.0 / (q * (1.0 - q))) * gsl_ran_binomial_pdf(i, q, n); } /* integral of f over allele freq -- returns Prob(Segsite | mu, beta) */ double my_H(gsl_vector *pVector, void * p){ struct my_F_params * params = (struct my_F_params *) p; struct my_f_params fParams; gsl_function f; gsl_integration_workspace * w; double result,error; if (gsl_vector_get(pVector, 0) == 0){ return gsl_vector_get(pVector, 1) / params->i; } else{ w = gsl_integration_workspace_alloc (100000); fParams.beta = gsl_vector_get(pVector, 0); fParams.i = params->i; fParams.n = params->n; f.function = &(my_h); f.params = &fParams; gsl_integration_qags(&f,0.0,1.0,1e-5,1e-5, 100000,w, &result,&error); gsl_integration_workspace_free(w); return result * gsl_vector_get(pVector,1); } } /* siteProbMatrix- fills up a matrix of log siteProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent variable sampleSizes (2 to max), columns represent freqs (0 to max -1), freq 0 is for monomorphic sites */ void siteProbMatrix(gsl_matrix *probs, gsl_vector *pVector, int maxSampleSize, gsl_vector *sampleSizeVector){ struct my_snpProb_params FParams; int i, j; double tot, prob; //check & init probs assert(probs->size1 == maxSampleSize + 1 && probs->size2 == maxSampleSize); gsl_matrix_set_zero(probs); //go through sampleSizes for(i = 2; i <= maxSampleSize; i++){ //have sample size i? if (gsl_vector_get(sampleSizeVector, i)){ //set tot to zero for p{monomorphic} tot = 0; //go through freqs for(j = 1; j < maxSampleSize; j++){ //calc prob prob = 0; FParams.i = j; FParams.n = i; //need to impose constraint that p{SegSite = 0 | theta < 0} if(gsl_vector_get(pVector,1) < 0){ prob = 0; } else{ prob = my_H(pVector, &FParams); } gsl_matrix_set(probs, i, j, log(prob)); tot += prob; } //set p{monomorphic} gsl_matrix_set(probs,i, 0, log(1.0 - tot)); } } } double weightedLikLookSites(gsl_vector *pVector, void * p){ struct my_jointLik_params * params = (struct my_jointLik_params *) p; gsl_matrix *probs; double lik; int i; //make prob matrix (log space) probs = gsl_matrix_alloc(params->maxSampleSize + 1, params->maxSampleSize); siteProbMatrix(probs, pVector, params->maxSampleSize, params->sampleSizeVector); //tally likelihood lik = 0; for(i = 0; i < params->snpNumber; i++){ lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i); } gsl_matrix_free(probs); return -lik; } // weightedLikLookSites2State -- for use in 2 state HMM double weightedLikLookSites2State(gsl_vector *pVector, void * p){ struct my_jointLik_params * params = (struct my_jointLik_params *) p; gsl_matrix *probs, *probsN; gsl_vector *npVector; double lik; int i; //setup neutral params npVector = gsl_vector_alloc(2); gsl_vector_set(npVector,0,0); gsl_vector_set(npVector,1,gsl_vector_get(pVector,1)); //alloc & make probs and probsN matrix (log space) probs = gsl_matrix_alloc(params->maxSampleSize + 1, params->maxSampleSize); siteProbMatrix(probs, pVector, params->maxSampleSize, params->sampleSizeVector); probsN = gsl_matrix_alloc(params->maxSampleSize + 1, params->maxSampleSize); siteProbMatrix(probsN,npVector, params->maxSampleSize, params->sampleSizeVector); //tally likelihood lik = 0; for(i = 0; i < params->snpNumber; i++){ lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i); lik += gsl_matrix_get(probsN,params->data[i].n,params->data[i].i) * (1.0 - gsl_vector_get(params->weights,i)); } gsl_matrix_free(probs); gsl_matrix_free(probsN); gsl_vector_free(npVector); return -lik; } gsl_vector *jointMLEst(double *lik, void * p){ size_t np = 2; struct my_jointLik_params * params = (struct my_jointLik_params *) p; const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex; gsl_multimin_fminimizer *s = NULL; gsl_multimin_function minex_func; gsl_vector *ss, *x, *results; size_t iter = 0, i; int status; double size; /* Initial vertex size vector */ ss = gsl_vector_alloc (np); //initialize results vector results = gsl_vector_alloc (np); /* Set all step sizes to 1 */ gsl_vector_set_all (ss, 0.01); /* Starting point */ x = gsl_vector_alloc (np); gsl_vector_set (x, 0, gsl_vector_get(params->startingPoint,0)); gsl_vector_set (x, 1, gsl_vector_get(params->startingPoint,1)); /* Initialize method and iterate */ minex_func.f = &weightedLikLookSites2State; minex_func.n = np; minex_func.params = params; s = gsl_multimin_fminimizer_alloc (T, np); gsl_multimin_fminimizer_set (s, &minex_func, x, ss); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if (status) break; size = gsl_multimin_fminimizer_size (s); status = gsl_multimin_test_size (size, 1e-3); } while (status == GSL_CONTINUE && iter < 500); for (i = 0; i < np; i++){ gsl_vector_set(results,i,gsl_vector_get (s->x, i)); } gsl_vector_free(ss); gsl_multimin_fminimizer_free (s); return(results); } // weightedLikLookSitesNState -- for use in n state HMM // pVector now consists of n parameters, not just two // pVector = [theta_hat, beta_hat_1, beta_hat_2, double weightedLikLookSitesNState(gsl_vector *pVector, void * p){ struct my_jointLik_params * params = (struct my_jointLik_params *) p; gsl_matrix *probs; gsl_vector *currentVector; double lik; int i,j; //setup neutral params currentVector = gsl_vector_alloc(params->nstates); gsl_vector_set(currentVector,0,0); gsl_vector_set(currentVector,1,gsl_vector_get(pVector,0)); //make prob matrix (log space) probs = gsl_matrix_alloc(params->maxSampleSize + 1, params->maxSampleSize); siteProbMatrix(probs, currentVector, params->maxSampleSize, params->sampleSizeVector); //tally likelihood due to neutral lik = 0; for(i = 0; i < params->snpNumber; i++){ lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_matrix_get(params->posts,0,i); } //go through states tallying lik for (i = 1; i < params->nstates; i++){ gsl_vector_set(currentVector,0,gsl_vector_get(pVector,i)); gsl_vector_set(currentVector,1,gsl_vector_get(pVector,0)); siteProbMatrix(probs,currentVector, params->maxSampleSize, params->sampleSizeVector); for(j = 0; j < params->snpNumber; j++){ lik += gsl_matrix_get(probs,params->data[j].n,params->data[j].i) * gsl_matrix_get(params->posts,i,j); } } gsl_matrix_free(probs); gsl_vector_free(currentVector); return -lik; } //N state version void jointMLEstNState(gsl_vector *results, double *lik, void * p){ struct my_jointLik_params * params = (struct my_jointLik_params *) p; size_t np = params->nstates; const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex; gsl_multimin_fminimizer *s = NULL; gsl_multimin_function minex_func; gsl_vector *ss, *x; size_t iter = 0, i; int status,j; double size; //check results vector assert(results->size == np); /* Initial vertex size vector */ ss = gsl_vector_alloc (np); /* Set all step sizes to 1 */ gsl_vector_set_all (ss, 0.01); /* Starting point */ x = gsl_vector_alloc (np); for(j = 0; j < np; j++){ gsl_vector_set (x, j, gsl_vector_get(params->startingPoint,j)); } /* Initialize method and iterate */ minex_func.f = &weightedLikLookSitesNState; minex_func.n = np; minex_func.params = params; s = gsl_multimin_fminimizer_alloc (T, np); gsl_multimin_fminimizer_set (s, &minex_func, x, ss); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if (status) break; size = gsl_multimin_fminimizer_size (s); status = gsl_multimin_test_size (size, 1e-5); } while (status == GSL_CONTINUE && iter < 500); for (i = 0; i < np; i++){ gsl_vector_set(results,i,gsl_vector_get (s->x, i)); } gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free (s); }
{ "alphanum_fraction": 0.6850853549, "avg_line_length": 30.5979381443, "ext": "c", "hexsha": "b74ef992c0720c4e0d1549a349cb5cb0cad94780", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_path": "segSiteHMM/segSites.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_path": "segSiteHMM/segSites.c", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_path": "segSiteHMM/segSites.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2699, "size": 8904 }
#include "jfftw_complex_Plan.h" #include <fftw.h> /* * Class: jfftw_complex_Plan * Method: createPlan * Signature: (III)V */ JNIEXPORT void JNICALL Java_jfftw_complex_Plan_createPlan( JNIEnv *env, jobject obj, jint n, jint dir, jint flags ) { jclass clazz; jfieldID id; jbyteArray arr; unsigned char* carr; if( sizeof( jdouble ) != sizeof( fftw_real ) ) { (*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/RuntimeException" ), "jdouble and fftw_real are incompatible" ); return; } clazz = (*env)->GetObjectClass( env, obj ); id = (*env)->GetFieldID( env, clazz, "plan", "[B" ); arr = (*env)->NewByteArray( env, sizeof( fftw_plan ) ); carr = (*env)->GetByteArrayElements( env, arr, 0 ); (*env)->MonitorEnter( env, (*env)->FindClass( env, "jfftw/Plan" ) ); *(fftw_plan*)carr = fftw_create_plan( n, dir, flags ); (*env)->MonitorExit( env, (*env)->FindClass( env, "jfftw/Plan" ) ); (*env)->ReleaseByteArrayElements( env, arr, carr, 0 ); (*env)->SetObjectField( env, obj, id, arr ); } /* * Class: jfftw_complex_Plan * Method: createPlanSpecific * Signature: (III[DI[DI)V */ JNIEXPORT void JNICALL Java_jfftw_complex_Plan_createPlanSpecific( JNIEnv *env, jobject obj, jint n, jint dir, jint flags, jdoubleArray in, jint idist, jdoubleArray out, jint odist ) { jclass clazz; jfieldID id; jbyteArray arr; unsigned char* carr; double *cin, *cout; if( sizeof( jdouble ) != sizeof( fftw_real ) ) { (*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/RuntimeException" ), "jdouble and fftw_real are incompatible" ); return; } clazz = (*env)->GetObjectClass( env, obj ); id = (*env)->GetFieldID( env, clazz, "plan", "[B" ); arr = (*env)->NewByteArray( env, sizeof( fftw_plan ) ); carr = (*env)->GetByteArrayElements( env, arr, 0 ); cin = (*env)->GetDoubleArrayElements( env, in, 0 ); cout = (*env)->GetDoubleArrayElements( env, out, 0 ); (*env)->MonitorEnter( env, (*env)->FindClass( env, "jfftw/Plan" ) ); *(fftw_plan*)carr = fftw_create_plan_specific( n, dir, flags, (fftw_complex*)cin, idist, (fftw_complex*)cout, odist ); (*env)->MonitorExit( env, (*env)->FindClass( env, "jfftw/Plan" ) ); (*env)->ReleaseDoubleArrayElements( env, in, cin, 0 ); (*env)->ReleaseDoubleArrayElements( env, out, cout, 0 ); (*env)->ReleaseByteArrayElements( env, arr, carr, 0 ); (*env)->SetObjectField( env, obj, id, arr ); } /* * Class: jfftw_complex_Plan * Method: destroyPlan * Signature: ()V */ JNIEXPORT void JNICALL Java_jfftw_complex_Plan_destroyPlan( JNIEnv* env, jobject obj ) { jclass clazz = (*env)->GetObjectClass( env, obj ); jfieldID id = (*env)->GetFieldID( env, clazz, "plan", "[B" ); jbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id ); unsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 ); fftw_destroy_plan( *(fftw_plan*)carr ); (*env)->ReleaseByteArrayElements( env, arr, carr, 0 ); (*env)->SetObjectField( env, obj, id, NULL ); } /* * Class: jfftw_complex_Plan * Method: transform * Signature: ([D)[D */ JNIEXPORT jdoubleArray JNICALL Java_jfftw_complex_Plan_transform___3D( JNIEnv* env, jobject obj, jdoubleArray in ) { jdouble *cin, *cout; jdoubleArray out; int i; jclass clazz = (*env)->GetObjectClass( env, obj ); jfieldID id = (*env)->GetFieldID( env, clazz, "plan", "[B" ); jbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id ); unsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 ); fftw_plan plan = *(fftw_plan*)carr; if( plan->n * 2 != (*env)->GetArrayLength( env, in ) ) { (*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/IndexOutOfBoundsException" ), "the Plan was created for a different length" ); (*env)->ReleaseByteArrayElements( env, arr, carr, 0 ); return NULL; } cin = (*env)->GetDoubleArrayElements( env, in, 0 ); if( ! plan->flags & FFTW_THREADSAFE ) { // synchronization (*env)->MonitorEnter( env, obj ); } if( plan->flags & FFTW_IN_PLACE ) { out = in; fftw_one( plan, (fftw_complex*)cin, NULL ); } else { out = (*env)->NewDoubleArray( env, plan->n * 2 ); cout = (*env)->GetDoubleArrayElements( env, out, 0 ); fftw_one( plan, (fftw_complex*)cin, (fftw_complex*)cout ); (*env)->ReleaseDoubleArrayElements( env, out, cout, 0 ); } if( ! plan->flags & FFTW_THREADSAFE ) { // synchronization (*env)->MonitorEnter( env, obj ); } (*env)->ReleaseByteArrayElements( env, arr, carr, 0 ); (*env)->ReleaseDoubleArrayElements( env, in, cin, 0 ); return out; } /* * Class: jfftw_complex_Plan * Method: transform * Signature: (I[DII[DII)V */ JNIEXPORT void JNICALL Java_jfftw_complex_Plan_transform__I_3DII_3DII( JNIEnv *env, jobject obj, jint howmany, jdoubleArray in, jint istride, jint idist, jdoubleArray out, jint ostride, jint odist ) { jdouble *cin, *cout; int i; jclass clazz = (*env)->GetObjectClass( env, obj ); jfieldID id = (*env)->GetFieldID( env, clazz, "plan", "[B" ); jbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id ); unsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 ); fftw_plan plan = *(fftw_plan*)carr; if( (howmany - 1) * idist * 2 + plan->n * istride * 2 != (*env)->GetArrayLength( env, in ) ) { (*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/IndexOutOfBoundsException" ), "the Plan was created for a different length (in)" ); (*env)->ReleaseByteArrayElements( env, arr, carr, 0 ); return; } if( (howmany - 1) * odist * 2 + plan->n * ostride * 2 != (*env)->GetArrayLength( env, out ) ) { (*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/IndexOutOfBoundsException" ), "the Plan was created for a different length (out)" ); (*env)->ReleaseByteArrayElements( env, arr, carr, 0 ); return; } cin = (*env)->GetDoubleArrayElements( env, in, 0 ); cout = (*env)->GetDoubleArrayElements( env, out, 0 ); if( ! plan->flags & FFTW_THREADSAFE ) { // synchronization (*env)->MonitorEnter( env, obj ); } fftw( plan, howmany, (fftw_complex*)cin, istride, idist, (fftw_complex*)cout, ostride, odist ); if( ! plan->flags & FFTW_THREADSAFE ) { // synchronization (*env)->MonitorExit( env, obj ); } (*env)->ReleaseByteArrayElements( env, arr, carr, 0 ); (*env)->ReleaseDoubleArrayElements( env, in, cin, 0 ); (*env)->ReleaseDoubleArrayElements( env, out, cout, 0 ); }
{ "alphanum_fraction": 0.6564765206, "avg_line_length": 32.3775510204, "ext": "c", "hexsha": "fc982c291de16efbb47a4526fa4dd0774d28da4a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-03-09T05:30:21.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-08T14:04:52.000Z", "max_forks_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "CSCSI/Triana", "max_forks_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_Plan.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_issues_repo_issues_event_max_datetime": "2016-01-22T13:06:00.000Z", "max_issues_repo_issues_event_min_datetime": "2015-08-28T13:52:42.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "CSCSI/Triana", "max_issues_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_Plan.c", "max_line_length": 198, "max_stars_count": 8, "max_stars_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "CSCSI/Triana", "max_stars_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_Plan.c", "max_stars_repo_stars_event_max_datetime": "2019-01-15T21:45:38.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-02T10:12:13.000Z", "num_tokens": 1999, "size": 6346 }
#include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include "../globals.h" #include "galaxy_cluster.h" #define NTABLE 256 #define GSL_SPLINE gsl_interp_cspline #define Zero 1 #define Infinity 1e25 struct HaloProperties Halo = { 0 }; void setup_GalaxyCluster() { Problem.Boxsize[0] = Problem.Boxsize[1] = Problem.Boxsize[2] = 1000; // kpc Halo.Rho0 = 1e-26; // g/cm^3 Halo.Beta = 2.0 / 3.0; Halo.Rcore = 20; // kpc Halo.R_Sample = Problem.Boxsize[0]; sprintf ( Problem.Name, "IC_GalaxyCluster" ); Problem.Rho_Max = Halo.Rho0; Density_Func_Ptr = &GalaxyCluster_Density; U_Func_Ptr = &GalaxyCluster_U; Velocity_Func_Ptr = &GalaxyCluster_Velocity; } float betamodel ( const float r ) { float rho0 = Halo.Rho0; float beta = Halo.Beta; float rc = Halo.Rcore; return rho0 * pow ( 1 + p2 ( r / rc ), -1.5 * beta ); } float GalaxyCluster_Density ( const int ipart , const double bias ) { const float x = P[ipart].Pos[0] - 0.5 * Problem.Boxsize[0]; const float y = P[ipart].Pos[1] - 0.5 * Problem.Boxsize[1];; const float z = P[ipart].Pos[2] - 0.5 * Problem.Boxsize[2];; const float r = sqrt ( x * x + y * y + z * z ); return betamodel ( r ); } void GalaxyCluster_Velocity ( const int ipart, float out[3] ) { out[0] = 0.0; out[1] = 0.0; out[2] = 0.0; } float GalaxyCluster_U ( const int ipart ) { return 0; }
{ "alphanum_fraction": 0.6322081575, "avg_line_length": 22.21875, "ext": "c", "hexsha": "14a04a94584253be4ec13a45f7a28926283617ee", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:31:56.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-29T09:38:57.000Z", "max_forks_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elehcim/WVTICs", "max_forks_repo_path": "src/problems/galaxy_cluster.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_issues_repo_issues_event_max_datetime": "2021-02-23T12:22:14.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-23T12:22:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "elehcim/WVTICs", "max_issues_repo_path": "src/problems/galaxy_cluster.c", "max_line_length": 80, "max_stars_count": 5, "max_stars_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elehcim/WVTICs", "max_stars_repo_path": "src/problems/galaxy_cluster.c", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-29T04:44:13.000Z", "num_tokens": 479, "size": 1422 }
#pragma once #include <cstddef> // std::byte #include <map> #include <memory> // std::align #include <memory_resource> #include <vector> #include <gsl-lite/gsl-lite.hpp> #include <cuda/runtime_api.hpp> namespace thrustshift { namespace pmr { //! Unified CUDA Memory Resource. Buffers cannet be deallocated partially. Alignment is ignored. class managed_resource_type : public std::pmr::memory_resource { void* do_allocate(std::size_t bytes, [[maybe_unused]] std::size_t alignment) override { auto region = cuda::memory::managed::detail::allocate(bytes); return region.get(); } void do_deallocate(void* p, [[maybe_unused]] std::size_t bytes, [[maybe_unused]] std::size_t alignment) override { cuda::memory::managed::detail::free(p); } bool do_is_equal( const std::pmr::memory_resource& other) const noexcept override { return this == &other; } }; //! Device CUDA Memory Resource. Buffers cannot be deallocated partially. Alignment is ignored. class device_resource_type : public std::pmr::memory_resource { void* do_allocate(std::size_t bytes, [[maybe_unused]] std::size_t alignment) override { auto region = cuda::memory::device::detail::allocate(bytes); return region.get(); } void do_deallocate(void* p, [[maybe_unused]] std::size_t bytes, [[maybe_unused]] std::size_t alignment) override { cuda::memory::device::free(p); } bool do_is_equal( const std::pmr::memory_resource& other) const noexcept override { return this == &other; } }; class host_resource_type : public std::pmr::memory_resource { void* do_allocate(std::size_t bytes, [[maybe_unused]] std::size_t alignment) override { return malloc(bytes); } void do_deallocate(void* p, [[maybe_unused]] std::size_t bytes, [[maybe_unused]] std::size_t alignment) override { free(p); } bool do_is_equal( const std::pmr::memory_resource& other) const noexcept override { return this == &other; } }; namespace detail { struct page_id_type { size_t bytes; size_t alignment; }; inline bool operator<(const page_id_type& a, const page_id_type& b) { if (a.bytes == b.bytes) { return a.alignment < b.alignment; } return a.bytes < b.bytes; } } // namespace detail /*! \brief Allocates only if requested buffer size is currently not in the free pool. * * This pool is useful for functions, which require temporary GPU memory. The * host can allocate memory via this pool, launch the kernel with the corresponding * pointer and exit the function without deallocating the memory because the * host is not aware about the runtime of the GPU kernel and when the kernel * may read the temporary required memory. This pool should not be used if the * byte size of the allocations differ often becaues every time an allocation * is called it actually results into a new allocation if not the exact same * size was allocated previously. * * This class is useful if functions delegate the memory resource to other functions, which * are maybe called iteratively and if the function requires different buffers of * the same size. * * \note std::pmr compatible */ template <class Upstream> class delayed_pool_type : public std::pmr::memory_resource { private: struct page_item_type { void* ptr; bool allocated; }; public: delayed_pool_type() = default; ~delayed_pool_type() noexcept { for (auto& [page_id, book_page] : book_) { for (auto& page_item : book_page) { res_.deallocate( page_item.ptr, page_id.bytes, page_id.alignment); } } } auto& get_book() const { return book_; } private: void* do_allocate(size_t bytes, size_t alignment) override { if (bytes == 0) { return nullptr; } const detail::page_id_type page_id({bytes, alignment}); if (auto it = book_.find(page_id); it != book_.end()) { for (auto& page_item : it->second) { if (!page_item.allocated) { page_item.allocated = true; return page_item.ptr; } } // no page item was free void* ptr = res_.allocate(bytes, alignment); it->second.push_back({ptr, true}); return ptr; } // the required size was never allocated before void* ptr = res_.allocate(bytes, alignment); book_[page_id] = {{ptr, true}}; return ptr; } void do_deallocate(void* ptr, size_t bytes, size_t alignment) noexcept override { const detail::page_id_type page_id({bytes, alignment}); if (ptr == nullptr || bytes == 0) { return; } for (auto& page_item : book_[page_id]) { if (page_item.ptr == ptr && page_item.allocated) { page_item.allocated = false; return; } } // The pointer which should be deallocated was never allocated before std::terminate(); } bool do_is_equal( const std::pmr::memory_resource& other) const noexcept override { return this == &other; } Upstream res_; // size in bytes -> (ptr, alignment) std::map<detail::page_id_type, std::vector<page_item_type>> book_; }; /*! \brief Allocates only if there is no buffer in the free pool which is of the required size or larger. * * This pool searches for the smallest buffer in the pool which has the required alignment and is * of equal or larger byte size than the required buffer and returns that buffer if do_allocate is called. * Morevover, this pool has the same 'delayed' properties than the `delayed_pool_type`. * * \sa delayed_pool_type * \note std::pmr compatible */ template <class Upstream> class delayed_fragmenting_pool_type : public std::pmr::memory_resource { private: struct page_item_type { void* ptr; bool allocated; }; public: delayed_fragmenting_pool_type() = default; ~delayed_fragmenting_pool_type() noexcept { for (auto& [page_id, book_page] : book_) { for (auto& page_item : book_page) { res_.deallocate( page_item.ptr, page_id.bytes, page_id.alignment); } } } auto& get_book() const { return book_; } private: void* do_allocate(size_t bytes, size_t alignment) override { if (bytes == 0) { return nullptr; } const detail::page_id_type page_id({bytes, alignment}); for (auto& [k, v] : book_) { if (k.alignment == alignment && k.bytes >= bytes) { for (auto& p : v) { if (!p.allocated) { p.allocated = true; return p.ptr; } } } } // no page item was free if (auto it = book_.find(page_id); it != book_.end()) { void* ptr = res_.allocate(bytes, alignment); it->second.push_back({ptr, true}); return ptr; } // the required size was never allocated before void* ptr = res_.allocate(bytes, alignment); book_[page_id] = {{ptr, true}}; return ptr; } void do_deallocate(void* ptr, size_t bytes, size_t alignment) noexcept override { const detail::page_id_type page_id({bytes, alignment}); if (ptr == nullptr || bytes == 0) { return; } for (auto& [k, v] : book_) { if (k.alignment == alignment && k.bytes >= bytes) { for (auto& p : v) { // no comparison based on the bytes because the buffer can be larger // than the amount of requested bytes. if (p.ptr == ptr && p.allocated) { p.allocated = false; return; } } } } // The pointer which should be deallocated was never allocated before std::terminate(); } bool do_is_equal( const std::pmr::memory_resource& other) const noexcept override { return this == &other; } Upstream res_; // size in bytes -> (ptr, alignment) std::map<detail::page_id_type, std::vector<page_item_type>> book_; }; /*! \brief Wraps a memory resource around an existing buffer of fixed size. * * This class takes a pointer and a size of an existing buffer and wraps a memory * resource around that buffer. The resource can provide parts of that buffer by * calling `do_allocate` and simply returns subsequently aligned parts of the buffer. * If the buffer size is exceeded `gsl_FailFast()` is called. * * \note std::pmr compatible */ class wrapping_resource_type : public std::pmr::memory_resource { public: wrapping_resource_type(void* ptr, size_t size_in_bytes) : size_in_bytes_(size_in_bytes), ptr_(ptr) { static_assert(sizeof(std::byte) == 1); } private: void* do_allocate(size_t bytes, size_t alignment) noexcept override { if (bytes == 0) { return nullptr; } void* ptr = std::align(alignment, bytes, ptr_, size_in_bytes_); gsl_Expects(ptr); // not nullptr gsl_Expects( ptr == ptr_); // this is how I understand the function documentation of std::align gsl_Expects(size_in_bytes_ >= bytes); size_in_bytes_ -= bytes; ptr_ = reinterpret_cast<std::byte*>(ptr_) + bytes; return ptr; } void do_deallocate([[maybe_unused]] void* ptr, [[maybe_unused]] size_t bytes, [[maybe_unused]] size_t alignment) noexcept override { } bool do_is_equal( const std::pmr::memory_resource& other) const noexcept override { return this == &other; } size_t size_in_bytes_; void* ptr_; }; static managed_resource_type default_resource; } // namespace pmr } // namespace thrustshift
{ "alphanum_fraction": 0.6710115264, "avg_line_length": 27.9608433735, "ext": "h", "hexsha": "96dcce2c2459f61109d4eb01a27efb8e622e56c4", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "codecircuit/thrustshift", "max_forks_repo_path": "include/thrustshift/memory-resource.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "codecircuit/thrustshift", "max_issues_repo_path": "include/thrustshift/memory-resource.h", "max_line_length": 107, "max_stars_count": 1, "max_stars_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "codecircuit/thrustshift", "max_stars_repo_path": "include/thrustshift/memory-resource.h", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "num_tokens": 2354, "size": 9283 }
/* specfunc/test_bessel.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_test.h> #include <gsl/gsl_sf.h> #include "test_sf.h" static double J[100]; static double Y[100]; static double I[100]; static double K[100]; int test_bessel(void) { gsl_sf_result r; int i; int s = 0; int sa; TEST_SF(s, gsl_sf_bessel_J0_e, (0.1, &r), 0.99750156206604003230, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J0_e, (2.0, &r), 0.22389077914123566805, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J0_e, (100.0, &r), 0.019985850304223122424, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J0_e, (1.0e+10, &r), 2.1755917502468917269e-06, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J1_e, (0.1, &r), 0.04993752603624199756, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J1_e, (2.0, &r), 0.57672480775687338720, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J1_e, (100.0, &r), -0.07714535201411215803, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J1_e, (1.0e+10, &r), -7.676508175684157103e-06, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (4, 0.1, &r), 2.6028648545684032338e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (5, 2.0, &r), 0.007039629755871685484, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (10, 20.0, &r), 0.18648255802394508321, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (100, 100.0, &r), 0.09636667329586155967, TEST_TOL0, GSL_SUCCESS); /* exercise the BUG#3 problem */ TEST_SF(s, gsl_sf_bessel_Jn_e, (2, 900.0, &r), -0.019974345269680646400, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (2, 15000.0, &r), -0.0020455820181216382666, TEST_TOL4, GSL_SUCCESS); #ifdef TEST_LARGE TEST_SF(s, gsl_sf_bessel_Jn_e, (0, 1.0e+10, &r), 2.1755917502468917269e-06, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (1, 1.0e+10, &r), -7.676508175684157103e-06, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (0, 20000, &r), 0.00556597490495494615709982972, TEST_TOL4, GSL_SUCCESS); #endif /* Testcase demonstrating long calculation time: Time spent in gsl_sf_bessel_J_CF1 for large x<1000 and n<5 grows in proportion to x Jonny Taylor <j.m.taylor@durham.ac.uk> */ TEST_SF(s, gsl_sf_bessel_Jn_e, (45, 900.0, &r), 0.02562434700634278108, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y0_e, (0.1, &r), -1.5342386513503668441, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y0_e, (2, &r), 0.5103756726497451196, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y0_e, (256.0, &r), -0.03381290171792454909 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y0_e, (4294967296.0, &r), 3.657903190017678681e-06, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y1_e, (0.1, &r), -6.45895109470202698800, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y1_e, (2, &r), -0.10703243154093754689, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y1_e, (100.0, &r), -0.020372312002759793305, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y1_e, (4294967296.0, &r), 0.000011612249378370766284, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (4, 0.1, &r), -305832.29793353160319, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (5, 2, &r), -9.935989128481974981, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (100, 100.0, &r), -0.16692141141757650654, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (100, 4294967296.0, &r), 3.657889671577715808e-06, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (1000, 4294967296.0, &r), 3.656551321485397501e-06, 2.0e-05, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (2, 15000.0, &r), -0.006185217273358617849, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (1e-10, &r), 0.99999999990000000001, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (0.1, &r), 0.90710092578230109640, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (2, &r), 0.30850832255367103953, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (100.0, &r), 0.03994437929909668265, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (65536.0, &r), 0.0015583712551952223537, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_scaled_e, (0.1, &r), 0.04529844680880932501, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_scaled_e, (2, &r), 0.21526928924893765916, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_scaled_e, (100.0, &r), 0.03974415302513025267, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_scaled_e, (65536.0, &r), 0.0015583593657207350452, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( -4, 0.1, &r), 2.3575258620054605307e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 4, 0.1, &r), 2.3575258620054605307e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 5, 2.0, &r), 0.0013297610941881578142, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 100, 100.0, &r), 1.7266862628167695785e-22, TEST_TOL0, GSL_SUCCESS); /* BJG: the "exact" values in the following two tests were originally computed from the taylor series for I_nu using "long double" and rescaling. The last few digits were inaccurate due to cumulative roundoff. BJG: 2006/05 I have now replaced these with the term asymptotic expansion from A&S 9.7.1 which should be fully accurate. */ TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 2, 1e7, &r), 1.261566024466416433e-4, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 2, 1e8, &r), 3.989422729212649531e-5, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_e, (0.1, &r), 1.0025015629340956014, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_e, (2.0, &r), 2.2795853023360672674, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_e, (100.0, &r), 1.0737517071310738235e+42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_e, (0.1, &r), 0.05006252604709269211, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_e, (2.0, &r), 1.59063685463732906340, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_e, (100.0, &r), 1.0683693903381624812e+42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_e, ( 4, 0.1, &r), 2.6054690212996573677e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_e, ( 5, 2.0, &r), 0.009825679323131702321, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_e, ( 100, 100.0, &r), 4.641534941616199114e+21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_scaled_e, (0.1, &r), 2.6823261022628943831, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_scaled_e, (2.0, &r), 0.8415682150707714179, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_scaled_e, (100.0, &r), 0.1251756216591265789, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_scaled_e, (0.1, &r), 10.890182683049696574, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_scaled_e, (2.0, &r), 1.0334768470686885732, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_scaled_e, (100.0, &r), 0.1257999504795785293, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_scaled_e, ( 4, 0.1, &r), 530040.2483725626207, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_scaled_e, ( 5, 2.0, &r), 69.68655087607675118, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_scaled_e, ( 100, 100.0, &r), 2.0475736731166756813e+19, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_e, (0.1, &r), 2.4270690247020166125, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_e, (2.0, &r), 0.11389387274953343565, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_e, (100.0, &r), 4.656628229175902019e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_e, (0.1, &r), 9.853844780870606135, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_e, (2.0, &r), 0.13986588181652242728, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_e, (100.0, &r), 4.679853735636909287e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_e, ( 4, 0.1, &r), 479600.2497925682849, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_e, ( 5, 2.0, &r), 9.431049100596467443, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_e, ( 100, 100.0, &r), 7.617129630494085416e-25, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, (-10.0, &r), -0.05440211108893698134, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, (0.001, &r), 0.9999998333333416667, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, ( 1.0, &r), 0.84147098480789650670, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, ( 10.0, &r), -0.05440211108893698134, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, (100.0, &r), -0.005063656411097587937, TEST_TOL1, GSL_SUCCESS); #ifdef FIXME TEST_SF(s, gsl_sf_bessel_j0_e, (1048576.0, &r), 3.1518281938718287624e-07, TEST_TOL2, GSL_SUCCESS); #endif /* these values are from Mathematica */ #ifdef FIXME TEST_SF(s, gsl_sf_bessel_j0_e, (1.0e18, &r), -9.9296932074040507620955e-19, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, (1.0e20, &r), -6.4525128526578084420581e-21, TEST_TOL0, GSL_SUCCESS); #endif TEST_SF(s, gsl_sf_bessel_j1_e, (-10.0, &r), -0.07846694179875154709, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, (0.01, &r), 0.003333300000119047399, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, ( 1.0, &r), 0.30116867893975678925, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, ( 10.0, &r), 0.07846694179875154709, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, (100.0, &r), -0.008673825286987815220, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, (1048576.0, &r), -9.000855242905546158e-07, TEST_TOL0, GSL_SUCCESS); /*TEST_SF(s, gsl_sf_bessel_j1_e, (1.0e18, &r), -1.183719902187107336049e-19, TEST_TOL0, GSL_SUCCESS);*/ TEST_SF(s, gsl_sf_bessel_j2_e, (-10.0, &r), 0.07794219362856244547, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (0.01, &r), 6.666619047751322551e-06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, ( 1.0, &r), 0.06203505201137386110, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, ( 10.0, &r), 0.07794219362856244547, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (100.0, &r), 0.004803441652487953480, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (1048576.0, &r), -3.1518539455252413111e-07, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (0, 0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (1, 10.0, &r), 0.07846694179875154709000, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (5, 1.0, &r), 0.00009256115861125816357, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (10, 10.0, &r), 0.06460515449256426427, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (100, 100.0, &r), 0.010880477011438336539, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (2000, 1048576.0, &r), 7.449384239168568534e-07, TEST_SQRT_TOL0, GSL_SUCCESS); /* related to BUG#3 problem */ TEST_SF(s, gsl_sf_bessel_jl_e, (2, 900.0, &r), -0.0011089115568832940086, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (2, 15000.0, &r), -0.00005955592033075750554, TEST_TOL4, GSL_SUCCESS); /* Bug report by Mario Santos, value computed from AS 10.1.8 */ TEST_SF(s, gsl_sf_bessel_jl_e, (100, 1000.0, &r), -0.00025326311230945818285, TEST_TOL4, GSL_SUCCESS); /* Bug reported by Koichi Takahashi <ktakahashi@molsci.org>, computed from Pari besseljh(n,x) and AS 10.1.1 */ TEST_SF(s, gsl_sf_bessel_jl_e, (30, 3878.62, &r), -0.00023285567034330878410434732790, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (49, 9912.63, &r), 5.2043354544842669214485107019E-5 , TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (49, 9950.35, &r), 5.0077368819565969286578715503E-5 , TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (52, 9930.51, &r), -7.4838588266727718650124475651E-6 , TEST_TOL4, GSL_SUCCESS); /* bug report #37209 */ TEST_SF(s, gsl_sf_bessel_jl_e, (364, 36.62, &r), 1.118907148986954E-318, TEST_TOL0, GSL_SUCCESS); /*TEST_SF(s, gsl_sf_bessel_jl_e, (149, 1.0, &r), 2.6599182755508469E-307, TEST_TOL0, GSL_SUCCESS);*/ TEST_SF(s, gsl_sf_bessel_y0_e, (0.001, &r), -999.99950000004166670, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, ( 1.0, &r), -0.5403023058681397174, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, ( 10.0, &r), 0.08390715290764524523, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, (100.0, &r), -0.008623188722876839341, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, (65536.0, &r), 0.000011014324202158573930, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, (4294967296.0, &r), 2.0649445131370357007e-10, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, ( 0.01, &r), -10000.499987500069444, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, ( 1.0, &r), -1.3817732906760362241, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, ( 10.0, &r), 0.06279282637970150586, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, (100.0, &r), 0.004977424523868819543, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, (4294967296.0, &r), 1.0756463271573404688e-10, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, ( 0.01, &r), -3.0000500012499791668e+06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, ( 1.0, &r), -3.605017566159968955, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, ( 10.0, &r), -0.06506930499373479347, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, (100.0, &r), 0.008772511458592903927, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, (4294967296.0, &r), -2.0649445123857054207e-10, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (0, 0.01, &r), -99.995000041666528, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (0, 1.0, &r), -0.54030230586813972, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (1, 10.0, &r), 0.062792826379701506, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (5, 1.0, &r), -999.44034339223641, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (10, 0.01, &r), -6.5473079797378378e+30, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (10, 10.0, &r), -0.172453672088057849, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (100, 1.0, &r), -6.6830794632586775e+186, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (100, 100.0, &r), -0.0229838504915622811, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (2000, 1048576.0, &r), 5.9545201447146155e-07, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i0_scaled_e, (0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i0_scaled_e, (0.1, &r), 0.9063462346100907067, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i0_scaled_e, (2.0, &r), 0.24542109027781645493, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i0_scaled_e, (100.0, &r), 0.005000000000000000000, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i1_scaled_e, (0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i1_scaled_e, (0.1, &r), 0.030191419289002226846, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i1_scaled_e, (2.0, &r), 0.131868364583275317610, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i1_scaled_e, (100.0, &r), 0.004950000000000000000, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i2_scaled_e, (0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i2_scaled_e, (0.1, &r), 0.0006036559400239012567, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i2_scaled_e, (2.0, &r), 0.0476185434029034785100, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i2_scaled_e, (100.0, &r), 0.0048515000000000000000, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 0, 0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 1, 0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 4, 0.001, &r), 1.0571434341190365013e-15, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 4, 0.1, &r), 9.579352242057134927e-08, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 5, 2.0, &r), 0.0004851564602127540059, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 5, 100.0, &r), 0.004300446777500000000, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 100, 100.0, &r), 1.3898161964299132789e-23, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k0_scaled_e, (0.1, &r), 15.707963267948966192, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k0_scaled_e, (2.0, &r), 0.7853981633974483096, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k0_scaled_e, (100.0, &r), 0.015707963267948966192, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k1_scaled_e, (0.1, &r), 172.78759594743862812, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k1_scaled_e, (2.0, &r), 1.1780972450961724644, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k1_scaled_e, (100.0, &r), 0.015865042900628455854, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k2_scaled_e, (0.1, &r), 5199.335841691107810, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k2_scaled_e, (2.0, &r), 2.5525440310417070063, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k2_scaled_e, (100.0, &r), 0.016183914554967819868, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_kl_scaled_e, ( 4, 1.0/256.0, &r), 1.8205599816961954439e+14, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_kl_scaled_e, ( 4, 1.0/8.0, &r), 6.1173217814406597530e+06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_kl_scaled_e, ( 5, 2.0, &r), 138.10735829492005119, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_kl_scaled_e, ( 100, 100.0, &r), 3.985930768060258219e+18, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.0001, 1.0, &r), 0.7652115411876708497, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.0001, 10.0, &r), -0.2459270166445205, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.0009765625, 10.0, &r), -0.2458500798634692, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.75, 1.0, &r), 0.5586524932048917478, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.75, 10.0, &r), -0.04968928974751508135, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, ( 1.0, 0.001, &r), 0.0004999999375000026, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, ( 1.0, 1.0, &r), 0.4400505857449335160, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, ( 1.75, 1.0, &r), 0.168593922545763170103, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (30.0, 1.0, &r), 3.482869794251482902e-42, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (30.0, 100.0, &r), 0.08146012958117222297, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (10.0, 1.0, &r), 2.6306151236874532070e-10, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (10.0, 100.0, &r), -0.05473217693547201474, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (10.2, 100.0, &r), -0.03548919161046526864, TEST_TOL2, GSL_SUCCESS); /* related to BUG#3 problem */ TEST_SF(s, gsl_sf_bessel_Jnu_e, (2.0, 900.0, &r), -0.019974345269680646400, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (2.0, 15000.0, &r), -0.0020455820181216382666, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (0.0001, 1.0, &r), 0.08813676933044478439, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (0.0001,10.0, &r), 0.05570979797521875261, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, ( 0.75, 1.0, &r), -0.6218694174429746383, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, ( 0.75, 10.0, &r), 0.24757063446760384953, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, ( 1.0, 0.001, &r), -636.6221672311394281, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, ( 1.0, 1.0, &r), -0.7812128213002887165, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (30.0, 1.0, &r), -3.0481287832256432162e+39, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (30.0, 100.0, &r), 0.006138839212010033452, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (10.0, 1.0, &r), -1.2161801427868918929e+08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (10.0, 100.0, &r), 0.05833157423641492875, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (10.2, 100.0, &r), 0.07169383985546287091, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (0.0001,10.0, &r), 0.12783333709581669672, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, ( 1.0, 0.001, &r), 0.0004995003123542213370, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, ( 1.0, 1.0, &r), 0.20791041534970844887, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (30.0, 1.0, &r), 1.3021094983785914437e-42, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (30.0, 100.0, &r), 0.0004486987756920986146, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (10.0, 1.0, &r), 1.0127529864692066036e-10, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (10.0, 100.0, &r), 0.024176682718258828365, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (10.2, 100.0, &r), 0.023691628843913810043, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (0.0001,10.0, &r), 2815.7166269770030352, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, ( 1.0, 0.001, &r), 0.0005000000625000026042, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, ( 1.0, 1.0, &r), 0.5651591039924850272, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (30.0, 1.0, &r), 3.539500588106447747e-42, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (30.0, 100.0, &r), 1.2061548704498434006e+40, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (10.0, 1.0, &r), 2.7529480398368736252e-10, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (10.0, 100.0, &r), 6.498975524720147799e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (10.2, 100.0, &r), 6.368587361287030443e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (0.0001,10.0, &r), 0.3916319346235421817, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, ( 1.0, 0.001, &r), 1000.9967345590684524, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, ( 1.0, 1.0, &r), 1.6361534862632582465, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (30.0, 1.0, &r), 1.2792629867539753925e+40, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (30.0, 100.0, &r), 10.673443449954850040, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.0, 1.0, &r), 4.912296520990198599e+08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.0, 100.0, &r), 0.20578687173955779807, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.0, 1000.0, &r), 0.04165905142800565788, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.0, 1.0e+8, &r), 0.00012533147624060789938, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.2, 100.0, &r), 0.20995808355244385075, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (0.0001,0.001, &r), 7.023689431812884141, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (0.0001,10.0, &r), 0.000017780062324654874306, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, ( 1.0, 0.001, &r), 999.9962381560855743, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, ( 1.0, 1.0, &r), 0.6019072301972345747, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (10.0, 0.001, &r), 1.8579455483904008064e+38, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (10.0, 1.0, &r), 1.8071328990102945469e+08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (10.0, 100.0, &r), 7.655427977388100611e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (10.2, 100.0, &r), 7.810600225948217841e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (30.0, 1.0, &r), 4.706145526783626883e+39, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (30.0, 100.0, &r), 3.970602055959398739e-43, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (0.0001,1.0e-100, &r), 5.439794449319847, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (0.0001,0.0001, &r), 2.232835507214331, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (0.0001,10.0, &r), -10.93743282256098, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, ( 1.0, 1.0e-100, &r), 230.2585092994045, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, ( 1.0, 1.0e-10, &r), 23.025850929940456840, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, ( 1.0, 0.001, &r), 6.907751517131146, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, ( 1.0, 1.0, &r), -0.5076519482107523309, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (30.0, 1.0e-100, &r), 6999.113586185543475, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (30.0, 1.0, &r), 91.34968784026325464, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (30.0, 100.0, &r), -97.63224126416760932, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (100.0, 1.0e-100, &r), 23453.606706185466825, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (100.0, 1.0, &r), 427.7532510250188083, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (100.0, 100.0, &r), -55.53422771502921431, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (1000.0, 1.0e-100, &r), 236856.183755993135, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (10000.0, 1.0e-100, &r), 2.39161558914890695e+06, TEST_TOL0, GSL_SUCCESS); /* [bug #31528] gsl_sf_bessel_lnKnu overflows for large nu */ TEST_SF(s, gsl_sf_bessel_lnKnu_e, (180.0, 2.2, &r), 735.1994170369583930752590258, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (3500.5, 1500.0, &r), 1731.220077116482710070986699, TEST_TOL1, GSL_SUCCESS); sa = 0; gsl_sf_bessel_Jn_array(3, 38, 1.0, J); sa += ( test_sf_frac_diff(J[0], 0.0195633539826684059190 ) > TEST_TOL1); sa += ( test_sf_frac_diff(J[1], 0.0024766389641099550438 ) > TEST_TOL1); sa += ( test_sf_frac_diff(J[10], 1.9256167644801728904e-14 ) > TEST_TOL1); sa += ( test_sf_frac_diff(J[35], 6.911232970971626272e-57 ) > TEST_TOL1); gsl_test(sa, " gsl_sf_bessel_Jn_array"); s += sa; sa = 0; gsl_sf_bessel_Yn_array(3, 38, 1.0, Y); sa += ( test_sf_frac_diff(Y[0], -5.821517605964728848 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[1], -33.27842302897211870 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[10], -1.2753618701519837595e+12 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[35], -1.2124435663593357154e+54 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_Yn_array"); s += sa; sa = 0; gsl_sf_bessel_In_scaled_array(3, 38, 1.0, I); sa += ( test_sf_frac_diff(I[0], 0.0081553077728142938170 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(I[1], 0.0010069302573377758637 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(I[10], 7.341518665628926244e-15 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(I[35], 2.5753065298357542893e-57 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_In_scaled_array"); s += sa; sa = 0; gsl_sf_bessel_In_array(3, 38, 1.0, Y); sa += ( test_sf_frac_diff(Y[0], 0.0221684249243319024760 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[1], 0.0027371202210468663251 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[10], 1.9956316782072007564e-14 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[35], 7.000408942764452901e-57 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_In_array"); s += sa; sa = 0; gsl_sf_bessel_Kn_array(3, 38, 1.0, K); sa += ( test_sf_frac_diff(K[0], 7.101262824737944506 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[1], 44.23241584706284452 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[10], 1.9215763927929940846e+12 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[35], 1.8789385023806051223e+54 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_Kn_array"); s += sa; sa = 0; gsl_sf_bessel_Kn_scaled_array(3, 38, 1.0, K); sa += ( test_sf_frac_diff(K[0], 19.303233695596904277 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[1], 120.23617222591483717 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[10], 5.223386190525076473e+12 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[35], 5.107484387813251411e+54 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_Kn_scaled_array"); s += sa; sa = 0; gsl_sf_bessel_jl_array(50, 1.0, J); sa += ( test_sf_frac_diff(J[0], 0.84147098480789650670 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(J[1], 0.30116867893975678925 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(J[10], 7.116552640047313024e-11 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(J[50], 3.615274717489787311e-81 ) > TEST_TOL2 ); gsl_test(sa, " gsl_sf_bessel_jl_array"); s += sa; sa = 0; gsl_sf_bessel_jl_steed_array(99, 1.0, J); sa += ( test_sf_frac_diff(J[0], 0.84147098480789650670 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(J[1], 0.30116867893975678925 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(J[10], 7.116552640047313024e-11 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(J[50], 3.615274717489787311e-81 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(J[80], 1.136352423414503264e-144 ) > TEST_TOL1 ); gsl_test(sa, " gsl_sf_bessel_jl_steed_array"); s += sa; sa = 0; gsl_sf_bessel_yl_array(50, 1.0, Y); sa += ( test_sf_frac_diff(Y[0], -0.5403023058681397174 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[1], -1.3817732906760362241 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[10], -6.722150082562084436e+08 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[50], -2.7391922846297571576e+78 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_yl_array"); s += sa; { double Y0[1]; sa = 0; gsl_sf_bessel_yl_array(0, 1.0, Y0); sa += ( test_sf_frac_diff(Y0[0], -0.5403023058681397174 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_yl_array (lmax=0)"); s += sa; } sa = 0; gsl_sf_bessel_il_scaled_array(50, 1.0, I); sa += ( test_sf_frac_diff(I[0], 0.43233235838169365410 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[1], 0.13533528323661269189 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[10], 2.7343719371837065460e-11 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[50], 1.3429606061892023653e-81 ) > TEST_TOL2 ); gsl_test(sa, " gsl_sf_bessel_il_scaled_array"); s += sa; sa = 0; gsl_sf_bessel_il_scaled_array(50, 0.0, I); sa += ( test_sf_frac_diff(I[0], 1.0 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[1], 0.0 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[10], 0.0 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[50], 0.0 ) > TEST_TOL2 ); gsl_test(sa, " gsl_sf_bessel_il_scaled_array (L=0)"); s += sa; sa = 0; gsl_sf_bessel_kl_scaled_array(50, 1.0, K); sa += ( test_sf_frac_diff(K[0], 1.5707963267948966192 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[1], 3.1415926535897932385 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[10], 2.7231075458948147010e+09 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[50], 1.1578440432804522544e+79 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_kl_scaled_array"); s += sa; { double K0[1]; sa = 0; gsl_sf_bessel_kl_scaled_array(0, 1.0, K0); sa += ( test_sf_frac_diff(K[0], 1.5707963267948966192 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_kl_scaled_array (lmax=0)"); s += sa; } sa = 0; sa += ( gsl_sf_bessel_zero_J0_e(0, &r) != GSL_EINVAL ); sa += ( r.val != 0.0 ); s += sa; TEST_SF(s, gsl_sf_bessel_zero_J0_e, ( 1, &r), 2.404825557695771, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J0_e, ( 2, &r), 5.520078110286304, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J0_e, (20, &r), 62.048469190227081, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J0_e, (25, &r), 77.756025630388058, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J0_e, (100, &r), 313.37426607752784, TEST_TOL1, GSL_SUCCESS); sa = 0; sa += ( gsl_sf_bessel_zero_J1_e(0, &r) != GSL_SUCCESS ); sa += ( r.val != 0.0 ); s += sa; TEST_SF(s, gsl_sf_bessel_zero_J1_e, ( 1, &r), 3.831705970207512, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J1_e, ( 2, &r), 7.015586669815619, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J1_e, (20, &r), 63.61135669848124, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J1_e, (25, &r), 79.32048717547630, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J1_e, (100, &r), 314.9434728377672, TEST_TOL2, GSL_SUCCESS); sa = 0; sa += ( gsl_sf_bessel_zero_Jnu_e(0.0, 0, &r) != GSL_EINVAL ); sa += ( r.val != 0.0 ); s += sa; TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 1, &r), 2.404825557695771, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 2, &r), 5.520078110286304, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 20, &r), 62.048469190227081, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 25, &r), 77.756025630388058, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 100, &r), 313.37426607752784, TEST_TOL1, GSL_SUCCESS); sa = 0; sa += ( gsl_sf_bessel_zero_Jnu_e(1.0, 0, &r) != GSL_SUCCESS ); sa += (r.val != 0.0); s += sa; TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 1, &r), 4.4934094579090641, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 1, &r), 8.7714838159599540, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 2, &r), 7.7252518369377072, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 2, &r), 12.338604197466944, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 3, &r), 10.904121659428900, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 3, &r), 15.700174079711671, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 4, &r), 14.066193912831473, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 4, &r), 18.980133875179921, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 5, &r), 17.220755271930768, TEST_TOL1, GSL_SUCCESS); /* Something wrong with the tolerances on these */ TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 5, &r), 22.217799896561268, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 8.0, 5, &r), 26.266814641176644, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (20.0, 5, &r), 41.413065513892636, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 6, &r), 20.371302959287563, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 6, &r), 25.430341154222704, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 8.0, 6, &r), 29.545659670998550, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 7, &r), 23.519452498689007, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 7, &r), 28.626618307291138, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 8.0, 7, &r), 32.795800037341462, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 8, &r), 26.666054258812674, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 8, &r), 31.811716724047763, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (10.0, 8, &r), 38.761807017881651, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 9, &r), 29.811598790892959, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 9, &r), 34.988781294559295, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (10.0, 9, &r), 42.004190236671805, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 10, &r), 32.956389039822477, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 10, &r), 38.159868561967132, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 10, &r), 52.017241278881633, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 11, &r), 41.326383254047406, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 11, &r), 55.289204146560061, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 12, &r), 44.4893191232197314, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 12, &r), 58.5458289043850856, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 13, &r), 47.6493998066970948, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 13, &r), 61.7897598959450550, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 14, &r), 50.8071652030063595, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 14, &r), 65.0230502510422545, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 15, &r), 53.9630265583781707, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 15, &r), 68.2473219964207837, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 16, &r), 57.1173027815042647, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 16, &r), 71.4638758850226630, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 17, &r), 60.2702450729428077, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 17, &r), 74.6737687121404241, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 18, &r), 63.4220540458757799, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 18, &r), 77.8778689734863729, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 19, &r), 66.5728918871182703, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 19, &r), 81.0768977206328326, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 20, &r), 69.722891161716742, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 20, &r), 84.271459069716442, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 23.0, 11, &r), 65.843393469524653, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 30.0, 11, &r), 74.797306585175426, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 32.0, 15, &r), 90.913637691861741, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 50.0, 15, &r), 113.69747988073942, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 22, &r), 76.020793430591605, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 10.0, 22, &r), 83.439189796105756, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 12.0, 22, &r), 86.345496520534055, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (100.0, 22, &r), 199.82150220122519, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (500.0, 22, &r), 649.34132440891735, TEST_TOL2, GSL_SUCCESS); sa = 0; for(i=0; i<100; i++) { J[i] = i/10.0; } gsl_sf_bessel_sequence_Jnu_e(2.0, GSL_MODE_DEFAULT, 100, J); sa += ( test_sf_frac_diff(J[1], 0.0012489586587999188454 ) > TEST_TOL1 ); sa += ( test_sf_frac_diff(J[20], 0.3528340286156377192 ) > TEST_TOL4 ); sa += ( test_sf_frac_diff(J[50], 0.0465651162777522155 ) > TEST_TOL4 ); gsl_test(sa, " gsl_sf_sequence_Jnu_e(2)"); s += sa; sa = 0; for(i=0; i<100; i++) { J[i] = i; } gsl_sf_bessel_sequence_Jnu_e(12.0, GSL_MODE_DEFAULT, 100, J); sa += ( test_sf_frac_diff(J[1], 4.999718179448405289e-13 ) > TEST_TOL1 ); sa += ( test_sf_frac_diff(J[5], 7.627813166084551355e-05 ) > TEST_TOL1 ); sa += ( test_sf_frac_diff(J[7], 2.655620035894568062e-03 ) > TEST_TOL3 ); sa += ( test_sf_frac_diff(J[10], 6.337025497015601509e-02 ) > TEST_TOL3 ); sa += ( test_sf_frac_diff(J[15], 0.23666584405476805591 ) > TEST_TOL3 ); sa += ( test_sf_frac_diff(J[30], 0.14825335109966010021 ) > TEST_TOL3 ); sa += ( test_sf_frac_diff(J[70], 0.04109913716555364262 ) > TEST_TOL4 ); sa += ( test_sf_frac_diff(J[99], -0.0015052760501176728 ) > TEST_TOL5 ); gsl_test(sa, " gsl_sf_sequence_Jnu_e(12)"); s += sa; sa = 0; for(i=0; i<100; i++) { J[i] = i * 20; } gsl_sf_bessel_sequence_Jnu_e(1000.0, GSL_MODE_DEFAULT, 100, J); sa += ( test_sf_frac_diff(J[50], 0.04473067294796404088 ) > TEST_TOL5 ); sa += ( test_sf_frac_diff(J[99], 0.01400619760349853902 ) > TEST_TOL6 ); gsl_test(sa, " gsl_sf_sequence_Jnu_e(1000)"); s += sa; return s; }
{ "alphanum_fraction": 0.7132629992, "avg_line_length": 67.083728278, "ext": "c", "hexsha": "9aa8a2eb8cbc5cbe40d9a7113921d72b1b29db55", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/specfunc/test_bessel.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/specfunc/test_bessel.c", "max_line_length": 114, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/specfunc/test_bessel.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 17846, "size": 42464 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_statistics_double.h> #include <math.h> #include <utilities.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_voxel_linked_list.h" #include "tz_stack_sampling.h" #include "tz_voxel_graphics.h" #include "tz_stack_code.h" #include "tz_stack_math.h" #include "tz_stack_utils.h" #include "tz_objdetect.h" #include "tz_voxeltrans.h" #include "tz_stack_stat.h" #include "tz_stack_draw.h" #include "tz_geo3d_vector.h" #include "tz_stack_bwmorph.h" #include "tz_stack_bwdist.h" #include "tz_neurotrace.h" #include "tz_stack_threshold.h" #include "tz_iarray.h" #include "tz_darray.h" /* * trace_neuron - trace neuron from given seeds * * trace_neuron [!wtr] seed_file -Dsave_dir * -r: write intermediate results * */ int main(int argc, char* argv[]) { static char *Spec[] = { "[!wtr] [-canvas <string>] [-mask <string>] [-res <string>] [-minr <int>]", "-minlen <double>", " <image:string> -S<string> -D<string>", NULL}; Process_Arguments(argc, argv, Spec, 1); char *dir = Get_String_Arg("-D"); char file_path[100]; sprintf(file_path, "%s/%s", dir, Get_String_Arg("-S")); printf("%s\n", file_path); Geo3d_Scalar_Field *seed = Read_Geo3d_Scalar_Field(file_path); int idx; sprintf(file_path, "%s/%s.bn", dir, "max_r"); double max_r; int tmp; if (fexist(file_path)) { darray_read2(file_path, &max_r, &tmp); } else { max_r = darray_max(seed->values, seed->size, &idx); } printf("%g\n", max_r); max_r *= 1.5; /* sprintf(file_path, "%s/%s", dir, "soma0.bn"); if (!fexist(file_path)) { max_r *= 2.0; } */ Set_Neuroseg_Max_Radius(max_r); Stack *signal = Read_Stack(Get_String_Arg("image")); dim_type dim[3]; dim[0] = signal->width; dim[1] = signal->height; dim[2] = signal->depth; /* IMatrix *chord = Make_IMatrix(dim, 3); Stack *code = Make_Stack(GREY16, signal->width, signal->height, signal->depth); */ Rgb_Color color; Set_Color(&color, 255, 0, 0); Stack *canvas = NULL; char trace_file_path[100]; sprintf(trace_file_path, "%s/%s", dir, Get_String_Arg("-canvas")); if (fexist(trace_file_path) == 1) { canvas = Read_Stack((char *) trace_file_path); } else { canvas = Copy_Stack(signal); Stretch_Stack_Value_Q(canvas, 0.999); Translate_Stack(canvas, COLOR, 1); } Stack *traced = NULL; char trace_mask_path[100]; sprintf(trace_mask_path, "%s/%s", dir, Get_String_Arg("-mask")); if (fexist(trace_mask_path) == 1) { traced = Read_Stack((char *) trace_mask_path); } else { traced = Make_Stack(GREY, signal->width, signal->height, signal->depth); One_Stack(traced); } //Object_3d *obj = NULL; int seed_offset = -1; Neurochain *chain = NULL; double z_scale = 1.0; if (Is_Arg_Matched("-res")) { sprintf(file_path, "%s", Get_String_Arg("-res")); if (fexist(file_path)) { double res[3]; int length; darray_read2(file_path, res, &length); if (res[0] != res[1]) { perror("Different X-Y resolutions."); TZ_ERROR(ERROR_DATA_VALUE); } z_scale = res[0] / res[2]; } } //sprintf(file_path, "%s/%s", dir, Get_String_Arg("-M")); //Stack *stack = Read_Stack(file_path); tic(); FILE *fp = NULL; char chain_file_path[100]; char vrml_file_path[100]; double min_chain_length = 25.0; if (Is_Arg_Matched("-minlen")) { min_chain_length = Get_Double_Arg("-minlen"); } int *indices = iarray_malloc(seed->size); double *values = darray_malloc(seed->size); int i; Local_Neuroseg *locseg = (Local_Neuroseg *) malloc(seed->size * sizeof(Local_Neuroseg)); int index = 0; for (i = 0; i < seed->size; i++) { printf("-----------------------------> seed: %d / %d\n", i, seed->size); indices[i] = i; index = i; int x = (int) seed->points[index][0]; int y = (int) seed->points[index][1]; int z = (int) seed->points[index][2]; double width = seed->values[index]; chain = New_Neurochain(); seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height, signal->depth); if (width < 3.0) { width += 0.5; } Set_Neuroseg(&(locseg[i].seg), width, width, 12.0, 0.0, 0.0, 0.0); double cpos[3]; cpos[0] = x; cpos[1] = y; cpos[2] = z; cpos[2] *= z_scale; Set_Neuroseg_Position(&(locseg[i]), cpos, NEUROSEG_CENTER); Stack_Fit_Score fs; fs.n = 1; fs.options[0] = 1; values[i] = Local_Neuroseg_Orientation_Search_C(&(locseg[i]), signal, z_scale, &fs); } darray_qsort(values, indices, seed->size); /* for (i = 0; i < seed->size; i++) { indices[i] = i; } darraycpy(values, seed->values, 0, seed->size); darray_qsort(values, indices, seed->size); */ int counter = 0; // for (i = seed->size - 1; i >= seed->size - 231; i--) { for (i = seed->size - 1; i >= 0; i--) { index = indices[i]; printf("-----------------------------> seed: %d / %d\n", i, seed->size); sprintf(chain_file_path, "%s/chain%d.bn", dir, index); sprintf(vrml_file_path, "%s/chain%d.wrl", dir, index); if (fexist(chain_file_path) == 1) { chain = Read_Neurochain(chain_file_path); if (Neurochain_Geolen(chain) >= min_chain_length) { Write_Neurochain_Vrml(vrml_file_path, chain); Neurochain_Label(canvas, chain, z_scale); Neurochain_Erase_E(traced, chain, z_scale, 0, Neurochain_Length(chain, FORWARD), 1.5, 0.0); } Free_Neurochain(chain); printf("chain exists\n"); continue; } int x = (int) seed->points[index][0]; int y = (int) seed->points[index][1]; int z = (int) seed->points[index][2]; if (*STACK_PIXEL_8(traced, x, y, z, 0) == 0) { printf("traced \n"); continue; } double width = seed->values[index]; if (width > max_r) { printf("too thick\n"); continue; } if (Is_Arg_Matched("-minr")) { int max_level = (int) (width + 0.5); if (max_level <= Get_Int_Arg("-minr")) { printf("too thin\n"); continue; } } /* seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height, signal->depth); */ chain = New_Neurochain(); /* Stack_Level_Code_Constraint(stack, code, chord->array, &seed_offset, 1, max_level + 1); Voxel_t v; v[0] = x; v[1] = y; v[2] = z; Stack *tmp_stack = Copy_Stack(stack); obj = Stack_Grow_Object_Constraint(tmp_stack, 1, v, chord, code, max_level); Free_Stack(tmp_stack); Print_Object_3d_Info(obj); double vec[3]; Object_3d_Orientation_Zscale(obj, vec, MAJOR_AXIS, z_scale); double theta, psi; Geo3d_Vector obj_vec; Set_Geo3d_Vector(&obj_vec, vec[0], vec[1], vec[2]); Geo3d_Vector_Orientation(&obj_vec, &theta, &psi); */ /* if (width < 3.0) { width += 0.5; } Set_Neuroseg(&(chain->locseg.seg), width, width, 12.0, 0.0, 0.0, 0.0); double cpos[3]; cpos[0] = x; cpos[1] = y; cpos[2] = z; cpos[2] *= z_scale; //Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_BOTTOM); Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_CENTER); Stack_Fit_Score fs; fs.n = 1; fs.options[0] = 1; Local_Neuroseg_Orientation_Search_C(&(chain->locseg), signal, z_scale, &fs); //fs.options[0] = 1; */ Copy_Local_Neuroseg(&(chain->locseg), &(locseg[index])); Neurochain *chain_head = chain; if (Initialize_Tracing(signal, chain, NULL, z_scale) >= MIN_SCORE) { if ((Neuroseg_Hit_Traced(&(chain->locseg), traced, z_scale) == FALSE) && (chain->locseg.seg.r1 < max_r) && (chain->locseg.seg.r2 < max_r)) { //Initialize_Tracing(signal, chain, NULL, z_scale); chain = Trace_Neuron2(signal, chain, BOTH, traced, z_scale, 500); //Neurochain *chain_head = Neurochain_Head(chain); chain_head = Neurochain_Remove_Overlap_Segs(chain); chain_head = Neurochain_Remove_Turn_Ends(chain_head, 0.5); /* if (i == seed->size - 231) { Print_Neurochain(chain_head); } */ fp = fopen(chain_file_path, "w"); Neurochain_Fwrite(chain_head, fp); fclose(fp); if (Neurochain_Geolen(chain_head) >= min_chain_length) { Write_Neurochain_Vrml(vrml_file_path, chain_head); Neurochain_Erase_E(traced, chain_head, z_scale, 0, Neurochain_Length(chain_head, FORWARD), 1.5, 0.0); Neurochain_Label(canvas, chain_head, z_scale); counter += Neurochain_Length(chain_head, FORWARD); if (counter > 500) { if (Is_Arg_Matched("-r")) { Write_Stack((char *) trace_mask_path, traced); } if (Is_Arg_Matched("-r")) { Write_Stack((char *) trace_file_path, canvas); } counter = 0; } } } } Free_Neurochain(chain_head); //Kill_Object_3d(obj); } Write_Stack((char *) trace_file_path, canvas); if (Is_Arg_Matched("-r")) { Write_Stack((char *) trace_mask_path, traced); } Kill_Geo3d_Scalar_Field(seed); printf("Time passed: %lld\n", toc()); return 0; }
{ "alphanum_fraction": 0.6135867191, "avg_line_length": 24.3510638298, "ext": "c", "hexsha": "7a1f429361d5d8eb97d42bdc4475d9d0bd085d1f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_neuron.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_neuron.c", "max_line_length": 88, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_neuron.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 2903, "size": 9156 }
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ #ifndef VNMRFDIST_H #define VNMRFDIST_H #ifdef VNMR_GPL #include <gsl/gsl_cdf.h> #define f_distribution(f,n1,n2) gsl_cdf_fdist_P( (f), (n1), (n2) ) #else extern double f_distribution(double f, double n1, double n2); #endif #endif
{ "alphanum_fraction": 0.7280334728, "avg_line_length": 21.7272727273, "ext": "h", "hexsha": "4dfad9a76329038fbbb7e67f59ba764bf4fbd407", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-03-20T05:41:54.000Z", "max_forks_repo_forks_event_min_datetime": "2016-01-23T15:27:16.000Z", "max_forks_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "timburrow/openvnmrj-source", "max_forks_repo_path": "src/vnmrbg/vnmr_fdist.h", "max_issues_count": 128, "max_issues_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:53:52.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-13T17:09:02.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "timburrow/openvnmrj-source", "max_issues_repo_path": "src/vnmrbg/vnmr_fdist.h", "max_line_length": 70, "max_stars_count": 32, "max_stars_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "DanIverson/OpenVnmrJ", "max_stars_repo_path": "src/vnmrbg/vnmr_fdist.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:54:44.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-17T05:04:26.000Z", "num_tokens": 134, "size": 478 }
#include "lah.h" #ifdef HAVE_LAPACK #include <lapacke.h> /* General Singular Value Decomposition*/ /* For now get all eigen values jobz ='A', * Can use this parameter later for truncated version */ lah_Return lah_SVD(lah_mat *A, lah_mat *U, lah_value *S, lah_mat *Vt) { lapack_int res; if (A == NULL || U == NULL || S == NULL || Vt == NULL || A->nR != A->nC || A->nR != U->nR || A->nC != Vt->nC ) { return lahReturnParameterError; } /* matrix_layout = LAH_LAPACK_LAYOUT(A); if (matrix_layout == LAPACK_COL_MAJOR) { lda = A->nR; ldu = U->nR; ldv = Vt->nR; } else { lda = A->nC; ldu = U->nC; ldv = Vt->nC; } */ /* Do the actual SVD: */ res = GESDD(LAH_LAPACK_LAYOUT, 'A', A->nC, A->nR, A->data, LAH_LEADING_DIM(A), S, U->data, LAH_LEADING_DIM(U), Vt->data, LAH_LEADING_DIM(Vt)); return (res == 0) ? lahReturnOk : lahReturnExternError; } #endif
{ "alphanum_fraction": 0.5528455285, "avg_line_length": 25.2307692308, "ext": "c", "hexsha": "ecca6e6489c366e3c9e3d1f63b9d3c7f01d47f4c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maj0e/linear-algebra-helpers", "max_forks_repo_path": "Source/lah_SVD.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "maj0e/linear-algebra-helpers", "max_issues_repo_path": "Source/lah_SVD.c", "max_line_length": 146, "max_stars_count": null, "max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maj0e/linear-algebra-helpers", "max_stars_repo_path": "Source/lah_SVD.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 334, "size": 984 }
// lasp_math_raw.h // // Author: J.A. de Jong - ASCEE // // Description: Raw math routines working on raw arrays of floats and // complex numbers. ////////////////////////////////////////////////////////////////////// #pragma once #ifndef LASP_MATH_RAW_H #define LASP_MATH_RAW_H #include "lasp_assert.h" #include "lasp_tracer.h" #include "lasp_types.h" #include <float.h> #include <math.h> #if LASP_USE_BLAS == 1 #include <cblas.h> #elif LASP_USE_BLAS == 0 #else #error "LASP_USE_BLAS should be set to either 0 or 1" #endif #ifdef LASP_DOUBLE_PRECISION #define c_real creal #define c_imag cimag #define d_abs fabs #define c_abs cabs #define c_conj conj #define d_atan2 atan2 #define d_acos acos #define d_sqrt sqrt #define c_exp cexp #define d_sin sin #define d_cos cos #define d_pow pow #define d_log10 log10 #define d_ln log #define d_epsilon (DBL_EPSILON) #else // LASP_DOUBLE_PRECISION not defined #define c_conj conjf #define c_real crealf #define c_imag cimagf #define d_abs fabsf #define c_abs cabsf #define d_atan2 atan2f #define d_acos acosf #define d_sqrt sqrtf #define c_exp cexpf #define d_sin sinf #define d_cos cosf #define d_pow powf #define d_log10 log10f #define d_ln logf #define d_epsilon (FLT_EPSILON) #endif // LASP_DOUBLE_PRECISION /// Positive infinite #define d_inf (INFINITY) #ifdef M_PI static const d number_pi = M_PI; #else static const d number_pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679; #endif /** * Set all elements in an array equal to val * * @param to * @param val * @param size */ static inline void d_set(d to[],d val,us size) { for(us i=0;i<size;i++) { to[i]=val; } } /** * Set all elements in an array equal to val * * @param to * @param val * @param size */ static inline void c_set(c to[],c val,us size) { for(us i=0;i<size;i++) { to[i]=val; } } /** * Return the maximum of two doubles * * @param a value 1 * @param b value 2 * * @returns the maximum of value 1 and 2 */ static inline d d_max(const d a,const d b) { return a>b?a:b; } /** * Return the dot product of two arrays, one of them complex-valued, * the other real-valued * * @param a the complex-valued array * @param b the real-valued array * @param size the size of the arrays. *Should be equal-sized!* * * @return the dot product */ static inline c cd_dot(const c a[],const d b[],us size){ c result = 0; us i; for(i=0;i<size;i++){ result+=a[i]*b[i]; } return result; } /** * Return the dot product of two complex-valued arrays. Wraps BLAS * when LASP_USE_BLAS == 1. * * @param a complex-valued array * @param b complex-valued array * @param size the size of the arrays. *Should be equal-sized!* * * @return the dot product */ static inline c cc_dot(const c a[],const c b[],us size){ #if LASP_USE_BLAS == 1 WARN("CBlas zdotu not yet tested"); #if LASP_DOUBLE_PRECISION // assert(0); return cblas_zdotu(size,(d*) a,1,(d*) b,1); #else return cblas_cdotu(size,(d*) a,1,(d*) b,1); #endif #else c result = 0; us i; for(i=0;i<size;i++){ result+=a[i]*b[i]; } return result; #endif } /** * Compute the dot product of two real arrays. * * @param a First array. * @param b Second array. * @param size Size of the arrays. * @return The result. */ static inline d d_dot(const d a[],const d b[],const us size){ #if LASP_USE_BLAS == 1 #if LASP_DOUBLE_PRECISION return cblas_ddot(size,a,1,b,1); #else // Single precision function return cblas_sdot(size,a,1,b,1); #endif #else // No BLAS, do it manually d result = 0; us i; for(i=0;i<size;i++){ result+=a[i]*b[i]; } return result; #endif } /** * Copy array of floats. * * @param to : Array to write to * @param from : Array to read from * @param size : Size of arrays * @param to_inc : Mostly equal to 1, the stride of the array to copy to * @param from_inc : Mostly equal to 1, the stride of the array to copy from */ static inline void d_copy(d to[], const d from[], const us size, const us to_inc, const us from_inc){ #if LASP_USE_BLAS == 1 cblas_dcopy(size,from,from_inc,to,to_inc); #else us i; for(i=0;i<size;i++) to[i*to_inc] = from[i*from_inc]; #endif } /** * Copy array of floats to array of complex floats. Imaginary part set * to zero. * * @param to : Array to write to * @param from : Array to read from * @param size : Size of arrays */ static inline void cd_copy(c to[],const d from[],const us size) { us i; for(i=0;i<size;i++) { to[i] = (c) (from[i]); dbgassert(cimag(to[i]) == 0,"Imaginary part not equal to zero"); } } /** * Copy float vector to complex vector. Imaginary part set * to zero. * * @param to : Vector to write to * @param from : Vector to read from */ static inline void c_copy(c to[],const c from[],const us size){ #if LASP_USE_BLAS == 1 #if LASP_DOUBLE_PRECISION cblas_zcopy(size,(d*) from,1,(d*) to,1); #else cblas_ccopy(size,(d*) from,1,(d*) to,1); #endif #else us i; for(i=0;i<size;i++) to[i] = from[i]; #endif } /** * Multiply y with fac, and add result to x * * @param x[in,out] Array to add to * @param y[in] Array to add to x * @param[in] fac Factor with which to multiply y * @param[in] size Size of the arrays */ static inline void d_add_to(d x[],const d y[], const d fac,const us size){ #if LASP_USE_BLAS == 1 #if LASP_DOUBLE_PRECISION cblas_daxpy(size,fac,y,1,x,1); #else cblas_saxpy(size,fac,y,1,x,1); #endif #else us i; for(i=0;i<size;i++) x[i]+=fac*y[i]; #endif } /** * x = x + fac*y * * @param[in,out] x Array to add to * @param[in] y Array to add to x * @param[in] fac Factor with which to multiply y * @param[in] size Size of the arrays */ static inline void c_add_to(c x[],const c y[], const c fac,const us size){ fsTRACE(15); #if LASP_USE_BLAS == 1 #if LASP_DOUBLE_PRECISION cblas_zaxpy(size,(d*) &fac,(d*) y,1,(d*) x,1); #else cblas_caxpy(size,(d*) &fac,(d*) y,1,(d*) x,1); #endif #else us i; for(i=0;i<size;i++) x[i]+=fac*y[i]; #endif feTRACE(15); } /** * Scale an array of doubles * * @param a array * @param scale_fac scale factor * @param size size of the array */ static inline void d_scale(d a[],const d scale_fac,us size){ #if LASP_USE_BLAS == 1 #if LASP_DOUBLE_PRECISION cblas_dscal(size,scale_fac,a,1); #else cblas_sscal(size,scale_fac,a,1); #endif #else us i; for(i=0;i<size;i++) a[i]*=scale_fac; #endif } /** * Scale an array of complex floats * * @param a array * @param scale_fac scale factor * @param size size of the array */ static inline void c_scale(c a[],const c scale_fac,us size){ #if LASP_USE_BLAS == 1 // Complex argument should be given in as array of two double // values. The first the real part, the second the imaginary // part. Fortunately the (c) type stores the two values in this // order. To be portable and absolutely sure anything goes well, // we convert it explicitly here. #if LASP_DOUBLE_PRECISION cblas_zscal(size,(d*) &scale_fac,(d*) a,1); #else cblas_cscal(size,(d*) &scale_fac,(d*) a,1); #endif #else us i; for(i=0;i<size;i++) a[i]*=scale_fac; #endif } /** * Compute the maximum value of an array * * @param a array * @param size size of the array * @return maximum */ static inline d darray_max(const d a[],us size){ us i; d max = a[0]; for(i=1;i<size;i++){ if(a[i] > max) max=a[i]; } return max; } /** * Compute the minimum of an array * * @param a array * @param size size of the array * @return minimum */ static inline d d_min(const d a[],us size){ us i; d min = a[0]; for(i=1;i<size;i++){ if(a[i] > min) min=a[i]; } return min; } /** * Compute the \f$ L_2 \f$ norm of an array of doubles * * @param a Array * @param size Size of array */ static inline d d_norm(const d a[],us size){ #if LASP_USE_BLAS == 1 return cblas_dnrm2(size,a,1); #else d norm = 0; us i; for(i=0;i<size;i++){ norm+=a[i]*a[i]; } norm = d_sqrt(norm); return norm; #endif } /** * Compute the \f$ L_2 \f$ norm of an array of complex floats * * @param a Array * @param size Size of array */ static inline d c_norm(const c a[],us size){ #if LASP_USE_BLAS == 1 return cblas_dznrm2(size,(d*) a,1); #else d norm = 0; us i; for(i=0;i<size;i++){ d absa = c_abs(a[i]); norm+=absa*absa; } norm = d_sqrt(norm); return norm; #endif } /** * Computes the element-wise vector product, or Hadamard product of * arr1 and arr2 * * @param res Where the result will be stored * @param arr1 Array 1 * @param vec2 Array 2 * @param size: Size of the arrays */ void d_elem_prod_d(d res[], const d arr1[], const d arr2[], const us size); /** * Computes the element-wise vector product, or Hadamard product of * arr1 and arr2 for complex floats * * @param res Where the result will be stored * @param arr1 Array 1 * @param vec2 Array 2 * @param size: Size of the arrays */ void c_hadamard(c res[], const c arr1[], const c arr2[], const us size); /** * Compute the complex conjugate of a complex vector and store the * result. * * @param res Result vector * @param in Input vector * @param size Size of the vector */ static inline void carray_conj(c res[],const c in[],const us size) { // First set the result vector to zero fsTRACE(15); c_set(res,0,size); #if LASP_USE_BLAS == 1 #if LASP_DOUBLE_PRECISION // Cast as a float, scale all odd elements with minus one to find // the complex conjugate. cblas_daxpy(size ,1.0,(d*) in,2,(d*) res,2); cblas_daxpy(size,-1.0,&((d*) in)[1],2,&((d*) res)[1],2); #else cblas_faxpy(size ,1,(d*) in,2,(d*) res,2); cblas_faxpy(size,-1,&((d*) in)[1],2,&((d*) res)[1],2); #endif // LASP_DOUBLE_PRECISION #else for(us i=0;i<size;i++) { res[i] = c_conj(in[i]); } #endif // LASP_USE_BLAS feTRACE(15); } /** * In place complex conjugation * * @param res Result vector * @param size Size of the vector */ static inline void c_conj_inplace(c res[],us size) { #if LASP_USE_BLAS #if LASP_DOUBLE_PRECISION // Cast as a float, scale all odd elements with minus one to find // the complex conjugate. cblas_dscal(size,-1,&((d*) res)[1],2); #else cblas_sscal(size,-1,&((d*) res)[1],2); #endif // LASP_DOUBLE_PRECISION #else for(us i=0;i<size;i++) { res[i] = c_conj(res[i]); } #endif // LASP_USE_BLAS } #endif // LASP_MATH_RAW_H //////////////////////////////////////////////////////////////////////
{ "alphanum_fraction": 0.5997158586, "avg_line_length": 22.8438133874, "ext": "h", "hexsha": "c707cd73a39e59957811c526f1e90104c445a839", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7cc77b073a91eb7470b449604544d9f57faf32e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "asceenl/lasp", "max_forks_repo_path": "lasp/c/lasp_math_raw.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7cc77b073a91eb7470b449604544d9f57faf32e9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "asceenl/lasp", "max_issues_repo_path": "lasp/c/lasp_math_raw.h", "max_line_length": 130, "max_stars_count": null, "max_stars_repo_head_hexsha": "7cc77b073a91eb7470b449604544d9f57faf32e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "asceenl/lasp", "max_stars_repo_path": "lasp/c/lasp_math_raw.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3422, "size": 11262 }
/***************************************************************************** * * Rokko: Integrated Interface for libraries of eigenvalue decomposition * * Copyright (C) 2012-2020 Rokko Developers https://github.com/t-sakashita/rokko * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * *****************************************************************************/ #ifndef ROKKO_SCALAPACK_SCALAPACK_INTERFACE_H #define ROKKO_SCALAPACK_SCALAPACK_INTERFACE_H #include <rokko/config.h> #include <rokko/mangling.h> #include <lapacke.h> #ifdef __cplusplus extern "C" { #endif #define SCALAPACK_descinit ROKKO_GLOBAL(descinit,DESCINIT) void SCALAPACK_descinit(int* desc, const int* m, const int* n, const int* mb, const int* nb, const int* irsrc, const int* icsrc, const int* ictxt, const int* lld, int* info); #define SCALAPACK_indxg2p ROKKO_GLOBAL(indxg2p,INDXG2P) int SCALAPACK_indxg2p(int* indxglob, int* nb, int* iproc, int* isrcproc, int* nprocs); #define SCALAPACK_numroc ROKKO_GLOBAL(numroc,NUMROC) int SCALAPACK_numroc(int* n, int* nb, int* iproc, int* isrcproc, int* nprocs); #define SCALAPACK_pdelget ROKKO_GLOBAL(pdelget,PDELGET) void SCALAPACK_pdelget(const char* scope, const char* top, double* alpha, const double* A, const int* ia, const int* ja, const int* descA); #define SCALAPACK_pdelset ROKKO_GLOBAL(pdelset,PDELSET) void SCALAPACK_pdelset(double* A, const int* ia, const int* ja, const int* descA, const double* alpha); #define SCALAPACK_pdlamch ROKKO_GLOBAL(pdlamch,PDLAMCH) double SCALAPACK_pdlamch(const int* icnt, const char* cmch); #define SCALAPACK_pdlange ROKKO_GLOBAL(pdlange,PDLANGE) double SCALAPACK_pdlange(const char* norm, int* m, int* n, const double* A, const int* ia, const int* ja, const int* descA, double* work); #define SCALAPACK_pdlaprnt ROKKO_GLOBAL(pdlaprnt,PDLAPRNT) void SCALAPACK_pdlaprnt(const int* m, const int* n, const double* A, const int* ia, const int* ja, const int* descA, const int* irprnt, const int* icprnt, const char* cmatnm, const int* nout, double* work); #define SCALAPACK_PSYEV_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const char* jobz, const char* uplo, const int* n, \ TYPE* A, const int* ia, const int* ja, const int* descA, \ TYPE_REAL* w, TYPE* Z, const int* iz, const int* jz, const int* descZ, \ TYPE* work, const int* lwork, int* info); SCALAPACK_PSYEV_DECL(pssyev, PSSYEV, float, float); SCALAPACK_PSYEV_DECL(pdsyev, PDSYEV, double, double); SCALAPACK_PSYEV_DECL(pcheev, PCHEEV, lapack_complex_float, float); SCALAPACK_PSYEV_DECL(pzheev, PZHEEV, lapack_complex_double, double); #undef SCALAPACK_PSYEV_DECL #define SCALAPACK_PSYEVD_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const char* jobz, const char* uplo, const int* n, \ TYPE* A, const int* ia, const int* ja, const int* descA, \ TYPE_REAL* w, \ TYPE* Z, const int* iz, const int* jz, const int* descZ, \ TYPE* work, const int* lwork, int* iwork, const int* liwork, int* info); SCALAPACK_PSYEVD_DECL(pssyevd, PSSYEVD, float, float); SCALAPACK_PSYEVD_DECL(pdsyevd, PDSYEVD, double, double); SCALAPACK_PSYEVD_DECL(pcheevd, PCHEEVD, lapack_complex_float, float); SCALAPACK_PSYEVD_DECL(pzheevd, PZHEEVD, lapack_complex_double, double); #undef SCALAPACK_PSYEVD_DECL #define SCALAPACK_PSYEVX_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const char* jobz, const char* range, const char* uplo, const int* n, \ TYPE* A, const int* iA, const int* jA, const int* descA, \ const TYPE_REAL* vl, const TYPE_REAL* vu, const int* il, const int* iu, \ const TYPE_REAL* abstol, int* m, int* nZ, TYPE_REAL* w, const TYPE_REAL* orfac, \ TYPE* Z, const int* iZ, const int* jZ, const int* descZ, \ TYPE* work, const int* lwork, int* iwork, const int* liwork, \ int* ifail, int* iclustr, TYPE_REAL* gap, int* info); SCALAPACK_PSYEVX_DECL(pssyevx, PSSYEVX, float, float); SCALAPACK_PSYEVX_DECL(pdsyevx, PDSYEVX, double, double); SCALAPACK_PSYEVX_DECL(pcheevx, PCHEEVX, lapack_complex_float, float); SCALAPACK_PSYEVX_DECL(pzheevx, PZHEEVX, lapack_complex_double, double); #undef SCALAPACK_PSYEVX_DECL #ifdef ROKKO_HAVE_SCALAPACK_PDSYEVR #define SCALAPACK_PSYEVR_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const char* jobz, const char* range, const char* uplo, const int* n, \ TYPE* A, const int* iA, const int* jA, const int* descA, \ const TYPE_REAL* vl, const TYPE_REAL* vu, const int* il, const int* iu, \ int* m, int* nz, \ TYPE_REAL* w, TYPE* Z, const int* iz, const int* jz, const int* descZ, \ TYPE* work, const int* lwork, int* iwork, const int* liwork, int* info); SCALAPACK_PSYEVR_DECL(pssyevr, PSSYEVR, float, float); SCALAPACK_PSYEVR_DECL(pdsyevr, PDSYEVR, double, double); SCALAPACK_PSYEVR_DECL(pcheevr, PCHEEVR, lapack_complex_float, float); SCALAPACK_PSYEVR_DECL(pzheevr, PZHEEVR, lapack_complex_double, double); #undef SCALAPACK_PSYEVR_DECL #endif #define SCALAPACK_pselget ROKKO_GLOBAL(pselget,PSELGET) void SCALAPACK_pselget(const char* scope, const char* top, float* alpha, const float* A, const int* ia, const int* ja, const int* descA); #define SCALAPACK_pselset ROKKO_GLOBAL(pselset,PSELSET) void SCALAPACK_pselset(float* A, const int* ia, const int* ja, const int* descA, const float* alpha); #define SCALAPACK_pslamch ROKKO_GLOBAL(pslamch,PSLAMCH) float SCALAPACK_pslamch(const int* icnt, const char* cmch); #define SCALAPACK_pslange ROKKO_GLOBAL(pslange,PSLANGE) float SCALAPACK_pslange(const char* norm, int* m, int* n, const float* A, const int* ia, const int* ja, const int* descA, float* work); #define SCALAPACK_pslaprnt ROKKO_GLOBAL(pslaprnt,PSLAPRNT) void SCALAPACK_pslaprnt(const int* m, const int* n, const float* A, const int* ia, const int* ja, const int* descA, const int* irprnt, const int* icprnt, const char* cmatnm, const int* nout, float* work); #define SCALAPACK_PSTEBZ_DECL(NAMES, NAMEL, TYPE) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const int* ictxt, const char* range, const char* order, const int* n, \ const TYPE* vl, const TYPE* vu, const int* il, const int* iu, \ const TYPE* abstol, const TYPE* d, const TYPE* e, int* m, int* nsplit, \ TYPE* w, int* iblock, int* isplit, \ TYPE* work, const int* lwork, int* iwork, const int* liwork, int* info); SCALAPACK_PSTEBZ_DECL(psstebz, PSSTEBZ, float); SCALAPACK_PSTEBZ_DECL(pdstebz, PDSTEBZ, double); #undef SCALAPACK_PSTEBZ_DECL #define SCALAPACK_PSTEIN_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const int* n, const TYPE_REAL* d, const TYPE_REAL* e, const int* m, \ TYPE_REAL* w, const int* iblock, const int* isplit, const TYPE_REAL* orfac, \ TYPE* Z, const int* iZ, const int* jZ, const int* descZ, \ TYPE* work, const int* lwork, int* iwork, const int* liwork, \ int* ifail, int* iclustr, TYPE_REAL* gap, int* info); SCALAPACK_PSTEIN_DECL(psstein, PSSTEIN, float, float); SCALAPACK_PSTEIN_DECL(pdstein, PDSTEIN, double, double); SCALAPACK_PSTEIN_DECL(pcstein, PCSTEIN, lapack_complex_float, float); SCALAPACK_PSTEIN_DECL(pzstein, PZSTEIN, lapack_complex_double, double); #undef SCALAPACK_PSTEIN_DECL #define SCALAPACK_PSTEDC_DECL(NAMES, NAMEL, TYPE) \ void ROKKO_GLOBAL(NAMES, NAMEL) (const char* compz, const int* n, TYPE* d, TYPE* e, \ TYPE* Q, const int* iq, const int* jq, const int* descQ, \ TYPE* work, const int* lwork, int* iwork, const int* liwork, int* info); SCALAPACK_PSTEDC_DECL(psstedc, PSSTEDC, float); SCALAPACK_PSTEDC_DECL(pdstedc, PDSTEDC, double); #undef SCALAPACK_PSTEDC_DECL #ifdef __cplusplus } #endif #endif // ROKKO_SCALAPACK_SCALAPACK_INTERFACE_H
{ "alphanum_fraction": 0.6780185759, "avg_line_length": 46.6555555556, "ext": "h", "hexsha": "731252d5dcefb1e757ba76fca33d8ca2c3715e3a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_path": "rokko/scalapack/scalapack_interface.h", "max_issues_count": 514, "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_path": "rokko/scalapack/scalapack_interface.h", "max_line_length": 110, "max_stars_count": 16, "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_path": "rokko/scalapack/scalapack_interface.h", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "num_tokens": 2681, "size": 8398 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_legendre.h> #include "ccl.h" /*--------ROUTINE: taper_cl ------ TASK:n Apply cosine tapering to Cls to reduce aliasing INPUT: number of ell bins for Cl, ell vector, C_ell vector, limits for tapering e.g., ell_limits=[low_ell_limit_lower,low_ell_limit_upper,high_ell_limit_lower,high_ell_limit_upper] */ static int taper_cl(int n_ell,double *ell,double *cl, double *ell_limits) { for(int i=0;i<n_ell;i++) { if(ell[i]<ell_limits[0] || ell[i]>ell_limits[3]) { cl[i]=0;//ell outside desirable range continue; } if(ell[i]>=ell_limits[1] && ell[i]<=ell_limits[2]) continue;//ell within good ell range if(ell[i]<ell_limits[1])//tapering low ell cl[i]*=cos((ell[i]-ell_limits[1])/(ell_limits[1]-ell_limits[0])*M_PI/2.); if(ell[i]>ell_limits[2])//tapering high ell cl[i]*=cos((ell[i]-ell_limits[2])/(ell_limits[3]-ell_limits[2])*M_PI/2.); } return 0; } /*--------ROUTINE: ccl_tracer_corr_fftlog ------ TASK: For a given tracer, get the correlation function Following function takes a function to calculate angular cl as well. By default above function will call it using ccl_angular_cl INPUT: type of tracer, number of theta values to evaluate = NL, theta vector */ static void ccl_tracer_corr_fftlog(ccl_cosmology *cosmo, int n_ell,double *ell,double *cls, int n_theta,double *theta,double *wtheta, int corr_type,int do_taper_cl,double *taper_cl_limits, int *status) { int i; double *l_arr,*cl_arr,*th_arr,*wth_arr; l_arr=ccl_log_spacing(cosmo->spline_params.ELL_MIN_CORR,cosmo->spline_params.ELL_MAX_CORR,cosmo->spline_params.N_ELL_CORR); if(l_arr==NULL) { *status=CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n"); return; } cl_arr=malloc(cosmo->spline_params.N_ELL_CORR*sizeof(double)); if(cl_arr==NULL) { free(l_arr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n"); return; } //Interpolate input Cl into array needed for FFTLog ccl_f1d_t *cl_spl=ccl_f1d_t_new(n_ell,ell,cls,cls[0],0, ccl_f1d_extrap_const, ccl_f1d_extrap_logx_logy, status); if(cl_spl==NULL) { free(l_arr); free(cl_arr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog " "ran out of memory\n"); return; } for(i=0;i<cosmo->spline_params.N_ELL_CORR;i++) cl_arr[i]=ccl_f1d_t_eval(cl_spl,l_arr[i]); ccl_f1d_t_free(cl_spl); if (do_taper_cl) taper_cl(cosmo->spline_params.N_ELL_CORR,l_arr,cl_arr,taper_cl_limits); th_arr=malloc(sizeof(double)*cosmo->spline_params.N_ELL_CORR); if(th_arr==NULL) { free(l_arr); free(cl_arr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n"); return; } wth_arr=(double *)malloc(sizeof(double)*cosmo->spline_params.N_ELL_CORR); if(wth_arr==NULL) { free(l_arr); free(cl_arr); free(th_arr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n"); return; } for(i=0;i<cosmo->spline_params.N_ELL_CORR;i++) th_arr[i]=0; //Although set here to 0, theta is modified by FFTlog to obtain the correlation at ~1/l int i_bessel=0; if(corr_type==CCL_CORR_GG) i_bessel=0; if(corr_type==CCL_CORR_GL) i_bessel=2; if(corr_type==CCL_CORR_LP) i_bessel=0; if(corr_type==CCL_CORR_LM) i_bessel=4; ccl_fftlog_ComputeXi2D(i_bessel,0, 1, cosmo->spline_params.N_ELL_CORR,l_arr,&cl_arr, th_arr,&wth_arr, status); // Interpolate to output values of theta ccl_f1d_t *wth_spl=ccl_f1d_t_new(cosmo->spline_params.N_ELL_CORR,th_arr, wth_arr,wth_arr[0],0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (wth_spl == NULL) { free(l_arr); free(cl_arr); free(th_arr); free(wth_arr); *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n"); return; } for(i=0;i<n_theta;i++) wtheta[i]=ccl_f1d_t_eval(wth_spl,theta[i]*M_PI/180.); ccl_f1d_t_free(wth_spl); free(l_arr); free(cl_arr); free(th_arr); free(wth_arr); return; } typedef struct { ccl_f1d_t *cl_spl; int i_bessel; double th; } corr_int_par; static double corr_bessel_integrand(double l,void *params) { double cl,jbes; corr_int_par *p=(corr_int_par *)params; double x=l*p->th; cl=ccl_f1d_t_eval(p->cl_spl,l); jbes=gsl_sf_bessel_Jn(p->i_bessel,x); return l*jbes*cl; } static void ccl_tracer_corr_bessel(ccl_cosmology *cosmo, int n_ell,double *ell,double *cls, int n_theta,double *theta,double *wtheta, int corr_type,int *status) { corr_int_par cp; ccl_f1d_t *cl_spl = NULL; cl_spl = ccl_f1d_t_new(n_ell, ell, cls, cls[0], 0, ccl_f1d_extrap_const, ccl_f1d_extrap_logx_logy, status); if(cl_spl == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_correlation.c: ccl_tracer_corr_bessel ran out of memory\n"); return; } int ith, gslstatus; double result,eresult; gsl_function F; gsl_integration_workspace *w = NULL; int local_status; #pragma omp parallel default(none) \ shared(cosmo, status, wtheta, n_ell, ell, cls, \ corr_type, cl_spl, theta, n_theta) \ private(w, F, result, eresult, local_status, ith, \ gslstatus, cp) { local_status = *status; switch(corr_type) { case CCL_CORR_GG: cp.i_bessel = 0; break; case CCL_CORR_GL: cp.i_bessel = 2; break; case CCL_CORR_LP: cp.i_bessel = 0; break; case CCL_CORR_LM: cp.i_bessel = 4; break; } cp.cl_spl = cl_spl; w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w == NULL) { local_status = CCL_ERROR_MEMORY; } F.function = &corr_bessel_integrand; F.params = &cp; #pragma omp for schedule(dynamic) for(ith=0; ith < n_theta; ith++) { if (local_status == 0) { cp.th = theta[ith]*M_PI/180; //TODO: Split into intervals between first bessel zeros before integrating //This will help both speed and accuracy of the integral. gslstatus = gsl_integration_qag(&F, 0, cosmo->spline_params.ELL_MAX_CORR, 0, cosmo->gsl_params.INTEGRATION_EPSREL, cosmo->gsl_params.N_ITERATION, cosmo->gsl_params.INTEGRATION_GAUSS_KRONROD_POINTS, w, &result, &eresult); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_correlation.c: ccl_tracer_corr_bessel():"); local_status |= gslstatus; } wtheta[ith] = result/(2*M_PI); } } if (local_status) { #pragma omp atomic write *status = local_status; } gsl_integration_workspace_free(w); } ccl_f1d_t_free(cl_spl); } /*--------ROUTINE: ccl_compute_legendre_polynomial ------ TASK: Compute input factor for ccl_tracer_corr_legendre INPUT: tracer 1, tracer 2, i_bessel, theta array, n_theta, L_max, output Pl_theta */ static void ccl_compute_legendre_polynomial(int corr_type,double theta,int ell_max,double *Pl_theta) { int i,j; double k=0; double cth=cos(theta*M_PI/180); //Initialize Pl_theta for (j=0;j<=ell_max;j++) Pl_theta[j]=0.; if(corr_type==CCL_CORR_GG) { gsl_sf_legendre_Pl_array(ell_max,cth,Pl_theta); for (j=0;j<=ell_max;j++) Pl_theta[j]*=(2*j+1); } else if(corr_type==CCL_CORR_GL) { for (j=2;j<=ell_max;j++) {//https://arxiv.org/pdf/1007.4809.pdf Pl_theta[j]=gsl_sf_legendre_Plm(j,2,cth); Pl_theta[j]*=(2*j+1.)/((j+0.)*(j+1.)); } } } /*--------ROUTINE: ccl_tracer_corr_legendre ------ TASK: Compute correlation function via Legendre polynomials INPUT: cosmology, number of theta bins, theta array, tracer 1, tracer 2, i_bessel, boolean for tapering, vector of tapering limits, correlation vector, angular_cl function. */ static void ccl_tracer_corr_legendre(ccl_cosmology *cosmo, int n_ell,double *ell,double *cls, int n_theta,double *theta,double *wtheta, int corr_type,int do_taper_cl,double *taper_cl_limits, int *status) { int i; double *l_arr = NULL, *cl_arr = NULL, *Pl_theta = NULL; ccl_f1d_t *cl_spl; if(corr_type==CCL_CORR_LM || corr_type==CCL_CORR_LP){ *status=CCL_ERROR_NOT_IMPLEMENTED; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: CCL does not support full-sky xi+- calcuations.\nhttps://arxiv.org/abs/1702.05301 indicates flat-sky to be sufficient.\n"); } if(*status==0) { l_arr=malloc(((int)(cosmo->spline_params.ELL_MAX_CORR)+1)*sizeof(double)); if(l_arr==NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\n"); } } if(*status==0) { cl_arr=malloc(((int)(cosmo->spline_params.ELL_MAX_CORR)+1)*sizeof(double)); if(cl_arr==NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\n"); } } if(*status==0) { //Interpolate input Cl into cl_spl=ccl_f1d_t_new(n_ell,ell,cls,cls[0],0, ccl_f1d_extrap_const, ccl_f1d_extrap_logx_logy, status); if(cl_spl==NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\n"); } } if(*status==0) { for(i=0;i<=(int)(cosmo->spline_params.ELL_MAX_CORR);i++) { double l=(double)i; l_arr[i]=l; cl_arr[i]=ccl_f1d_t_eval(cl_spl,l); } ccl_f1d_t_free(cl_spl); if (do_taper_cl) *status=taper_cl((int)(cosmo->spline_params.ELL_MAX_CORR)+1,l_arr,cl_arr,taper_cl_limits); } int local_status, i_L; #pragma omp parallel default(none) \ shared(cosmo, theta, cl_arr, wtheta, n_theta, status, corr_type) \ private(Pl_theta, i, i_L, local_status) { Pl_theta = NULL; local_status = *status; if (local_status == 0) { Pl_theta = malloc(sizeof(double)*((int)(cosmo->spline_params.ELL_MAX_CORR)+1)); if (Pl_theta == NULL) { local_status = CCL_ERROR_MEMORY; } } #pragma omp for schedule(dynamic) for (int i=0; i < n_theta; i++) { if (local_status == 0) { wtheta[i] = 0; ccl_compute_legendre_polynomial(corr_type, theta[i], (int)(cosmo->spline_params.ELL_MAX_CORR), Pl_theta); for (i_L=1; i_L < (int)(cosmo->spline_params.ELL_MAX_CORR); i_L+=1) wtheta[i] += cl_arr[i_L]*Pl_theta[i_L]; wtheta[i] /= (M_PI*4); } } if (local_status) { #pragma omp atomic write *status = local_status; } free(Pl_theta); } free(l_arr); free(cl_arr); } /*--------ROUTINE: ccl_tracer_corr ------ TASK: For a given tracer, get the correlation function. Do so by running ccl_angular_cls. If you already have Cls calculated, go to the next function to pass them directly. INPUT: cosmology, number of theta values to evaluate = NL, theta vector, tracer 1, tracer 2, i_bessel, key for tapering, limits of tapering correlation function. */ void ccl_correlation(ccl_cosmology *cosmo, int n_ell,double *ell,double *cls, int n_theta,double *theta,double *wtheta, int corr_type,int do_taper_cl,double *taper_cl_limits,int flag_method, int *status) { switch(flag_method) { case CCL_CORR_FFTLOG : ccl_tracer_corr_fftlog(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type, do_taper_cl,taper_cl_limits,status); break; case CCL_CORR_LGNDRE : ccl_tracer_corr_legendre(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type, do_taper_cl,taper_cl_limits,status); break; case CCL_CORR_BESSEL : ccl_tracer_corr_bessel(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,status); break; default : *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation. Unknown algorithm\n"); } } /*--------ROUTINE: ccl_correlation_3d ------ TASK: Calculate the 3d-correlation function. Do so by using FFTLog. INPUT: cosmology, scale factor a, number of r values, r values, key for tapering, limits of tapering Correlation function result will be in array xi */ void ccl_correlation_3d(ccl_cosmology *cosmo, double a, int n_r,double *r,double *xi, int do_taper_pk,double *taper_pk_limits, int *status) { int i,N_ARR; double *k_arr,*pk_arr,*r_arr,*xi_arr; if (!cosmo->computed_nonlin_power) { *status = CCL_ERROR_NONLIN_POWER_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_correlation.c: ccl_correlation_3d(): non-linear power spctrum has not been computed!"); return; } //number of data points for k and pk array N_ARR=(int)(cosmo->spline_params.N_K_3DCOR*log10(cosmo->spline_params.K_MAX/cosmo->spline_params.K_MIN)); k_arr=ccl_log_spacing(cosmo->spline_params.K_MIN,cosmo->spline_params.K_MAX,N_ARR); if(k_arr==NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n"); return; } pk_arr=malloc(N_ARR*sizeof(double)); if(pk_arr==NULL) { free(k_arr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n"); return; } for (i=0; i<N_ARR; i++){ pk_arr[i] = ccl_nonlin_matter_power(cosmo, k_arr[i], a, status); } if (do_taper_pk) taper_cl(N_ARR,k_arr,pk_arr,taper_pk_limits); r_arr=malloc(sizeof(double)*N_ARR); if(r_arr==NULL) { free(k_arr); free(pk_arr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n"); return; } xi_arr=malloc(sizeof(double)*N_ARR); if(xi_arr==NULL) { free(k_arr); free(pk_arr); free(r_arr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n"); return; } for(i=0;i<N_ARR;i++) r_arr[i]=0; ccl_fftlog_ComputeXi3D(0, 0, 1, N_ARR, k_arr, &pk_arr, r_arr, &xi_arr, status); // Interpolate to output values of r ccl_f1d_t *xi_spl=ccl_f1d_t_new(N_ARR,r_arr,xi_arr,xi_arr[0],0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (xi_spl == NULL) { free(k_arr); free(pk_arr); free(r_arr); free(xi_arr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n"); return; } for(i=0;i<n_r;i++) xi[i]=ccl_f1d_t_eval(xi_spl,r[i]); ccl_f1d_t_free(xi_spl); free(k_arr); free(pk_arr); free(r_arr); free(xi_arr); return; } /*--------ROUTINE: ccl_correlation_multipole ------ TASK: Calculate multipole of the redshift space correlation function. Do so using FFTLog. INPUT: cosmology, scale factor a, beta (= growth rate / bias), multipole order l = 0, 2, or 4, number of s values, s values Multipole function result will be in array xi */ void ccl_correlation_multipole(ccl_cosmology *cosmo, double a, double beta, int l, int n_s, double *s, double *xi, int *status) { int i, N_ARR; double *k_arr, *pk_arr, *s_arr, *xi_arr, *xi_arr0; if (!cosmo->computed_nonlin_power) { *status = CCL_ERROR_NONLIN_POWER_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_correlation.c: ccl_correlation_multipole(): non-linear power spctrum has not been computed!"); return; } N_ARR = (int)(cosmo->spline_params.N_K_3DCOR * log10(cosmo->spline_params.K_MAX / cosmo->spline_params.K_MIN)); k_arr = ccl_log_spacing(cosmo->spline_params.K_MIN, cosmo->spline_params.K_MAX, N_ARR); if (k_arr == NULL) { *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole ran out of memory\n"); return; } pk_arr = malloc(N_ARR * sizeof(double)); if (pk_arr == NULL) { free(k_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole ran out of memory\n"); return; } for (i = 0; i < N_ARR; i++) pk_arr[i] = ccl_nonlin_matter_power(cosmo, k_arr[i], a, status); s_arr = malloc(sizeof(double) * N_ARR); if (s_arr == NULL) { free(k_arr); free(pk_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole ran out of memory\n"); return; } xi_arr = malloc(sizeof(double) * N_ARR); if (xi_arr == NULL) { free(k_arr); free(pk_arr); free(s_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole ran out of memory\n"); return; } xi_arr0 = malloc(sizeof(double) * N_ARR); if (xi_arr0 == NULL) { free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole ran out of memory\n"); return; } for (i = 0; i < N_ARR; i++) s_arr[i] = 0; // Calculate multipoles if (l == 0) { ccl_fftlog_ComputeXi3D(0, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr0, status); for (i = 0; i < N_ARR; i++) xi_arr[i] = (1. + 2. / 3 * beta + 1. / 5 * beta * beta) * xi_arr0[i]; } else if (l == 2) { ccl_fftlog_ComputeXi3D(2, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr0, status); for (i = 0; i < N_ARR; i++) xi_arr[i] = -(4. / 3 * beta + 4. / 7 * beta * beta) * xi_arr0[i]; } else if (l == 4) { ccl_fftlog_ComputeXi3D(4, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr0, status); for (i = 0; i < N_ARR; i++) xi_arr[i] = 8. / 35 * beta * beta * xi_arr0[i]; } else { strcpy(cosmo->status_message, "unavailable value of l\n"); return; } // Interpolate to output values of s ccl_f1d_t *xi_spl = ccl_f1d_t_new(N_ARR, s_arr, xi_arr, xi_arr[0], 0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (xi_spl == NULL) { free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); free(xi_arr0); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole ran out of memory\n"); } for (i = 0; i < n_s; i++) xi[i] = ccl_f1d_t_eval(xi_spl,s[i]); ccl_f1d_t_free(xi_spl); free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); free(xi_arr0); return; } /*--------ROUTINE: ccl_correlation_multipole_spline ------ TASK: Store multipoles of the redshift-space correlation in global splines INPUT: cosmology, scale factor a Result is stored in cosmo->data.rsd_splines[] */ void ccl_correlation_multipole_spline(ccl_cosmology *cosmo, double a, int *status) { int i, N_ARR; double *k_arr, *pk_arr, *s_arr, *xi_arr, *xi_arr0, *xi_arr2, *xi_arr4; if (!cosmo->computed_nonlin_power) { *status = CCL_ERROR_NONLIN_POWER_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_correlation.c: ccl_correlation_multipole_spline(): non-linear power spctrum has not been computed!"); return; } N_ARR = (int)(cosmo->spline_params.N_K_3DCOR * log10(cosmo->spline_params.K_MAX / cosmo->spline_params.K_MIN)); k_arr = ccl_log_spacing(cosmo->spline_params.K_MIN, cosmo->spline_params.K_MAX, N_ARR); if (k_arr == NULL) { *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } pk_arr = malloc(N_ARR * sizeof(double)); if (pk_arr == NULL) { free(k_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } for (i = 0; i < N_ARR; i++) pk_arr[i] = ccl_nonlin_matter_power(cosmo, k_arr[i], a, status); s_arr = malloc(sizeof(double) * N_ARR); if (s_arr == NULL) { free(k_arr); free(pk_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } xi_arr = malloc(sizeof(double) * N_ARR); if (xi_arr == NULL) { free(k_arr); free(pk_arr); free(s_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } xi_arr0 = malloc(sizeof(double) * N_ARR); if (xi_arr0 == NULL) { free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } xi_arr2 = malloc(sizeof(double) * N_ARR); if (xi_arr2 == NULL) { free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); free(xi_arr0); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } xi_arr4 = malloc(sizeof(double) * N_ARR); if (xi_arr4 == NULL) { free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); free(xi_arr0); free(xi_arr2); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } for (i = 0; i < N_ARR; i++) s_arr[i] = 0; // Calculate multipoles ccl_fftlog_ComputeXi3D(0, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr0, status); ccl_fftlog_ComputeXi3D(2, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr2, status); ccl_fftlog_ComputeXi3D(4, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr4, status); // free any memory that may have been allocated ccl_f1d_t_free(cosmo->data.rsd_splines[0]); ccl_f1d_t_free(cosmo->data.rsd_splines[1]); ccl_f1d_t_free(cosmo->data.rsd_splines[2]); cosmo->data.rsd_splines[0] = NULL; cosmo->data.rsd_splines[1] = NULL; cosmo->data.rsd_splines[1] = NULL; // Interpolate to output values of s cosmo->data.rsd_splines[0] = ccl_f1d_t_new(N_ARR, s_arr, xi_arr0, xi_arr0[0], 0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (cosmo->data.rsd_splines[0] == NULL) { free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); free(xi_arr0); free(xi_arr2); free(xi_arr4); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } cosmo->data.rsd_splines[1] = ccl_f1d_t_new(N_ARR, s_arr, xi_arr2, xi_arr2[0], 0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (cosmo->data.rsd_splines[1] == NULL) { free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); free(xi_arr0); free(xi_arr2); free(xi_arr4); ccl_f1d_t_free(cosmo->data.rsd_splines[0]); cosmo->data.rsd_splines[0] = NULL; *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } cosmo->data.rsd_splines[2] = ccl_f1d_t_new(N_ARR, s_arr, xi_arr4, xi_arr4[0], 0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (cosmo->data.rsd_splines[2] == NULL) { free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); free(xi_arr0); free(xi_arr2); free(xi_arr4); ccl_f1d_t_free(cosmo->data.rsd_splines[0]); cosmo->data.rsd_splines[0] = NULL; ccl_f1d_t_free(cosmo->data.rsd_splines[1]); cosmo->data.rsd_splines[1] = NULL; *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_multipole_spline ran out of " "memory\n"); return; } // set the scale factor cosmo->data.rsd_splines_scalefactor = a; free(k_arr); free(pk_arr); free(s_arr); free(xi_arr); free(xi_arr0); free(xi_arr2); free(xi_arr4); return; } /*--------ROUTINE: ccl_correlation_3dRsd ------ TASK: Calculate the redshift-space correlation function. INPUT: cosmology, scale factor a, number of s values, s values, mu = cosine of galaxy separation angle w.r.t. line of sight, beta (= growth rate / bias), key for using spline Correlation function result will be in array xi */ void ccl_correlation_3dRsd(ccl_cosmology *cosmo, double a, int n_s, double *s, double mu, double beta, double *xi, int use_spline, int *status) { int i; double *xi_arr0, *xi_arr2, *xi_arr4; if (!cosmo->computed_nonlin_power) { *status = CCL_ERROR_NONLIN_POWER_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_correlation.c: ccl_correlation_3dRsd(): non-linear power spctrum has not been computed!"); return; } if (use_spline == 0) { xi_arr0 = malloc(sizeof(double) * n_s); if (xi_arr0 == NULL) { *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_3dRsd ran out of memory\n"); return; } xi_arr2 = malloc(sizeof(double) * n_s); if (xi_arr2 == NULL) { free(xi_arr0); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_3dRsd ran out of memory\n"); return; } xi_arr4 = malloc(sizeof(double) * n_s); if (xi_arr4 == NULL) { free(xi_arr0); free(xi_arr2); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_3dRsd ran out of memory\n"); return; } ccl_correlation_multipole(cosmo, a, beta, 0, n_s, s, xi_arr0, status); ccl_correlation_multipole(cosmo, a, beta, 2, n_s, s, xi_arr2, status); ccl_correlation_multipole(cosmo, a, beta, 4, n_s, s, xi_arr4, status); for (i = 0; i < n_s; i++) xi[i] = xi_arr0[i] + xi_arr2[i] * gsl_sf_legendre_Pl(2, mu) + xi_arr4[i] * gsl_sf_legendre_Pl(4, mu); free(xi_arr0); free(xi_arr2); free(xi_arr4); } else { if ((cosmo->data.rsd_splines[0] == NULL) || (cosmo->data.rsd_splines[1] == NULL) || (cosmo->data.rsd_splines[2] == NULL) || (cosmo->data.rsd_splines_scalefactor != a)) ccl_correlation_multipole_spline(cosmo, a, status); for (i = 0; i < n_s; i++) xi[i] = (1. + 2. / 3 * beta + 1. / 5 * beta * beta) * ccl_f1d_t_eval(cosmo->data.rsd_splines[0],s[i]) - (4. / 3 * beta + 4. / 7 * beta * beta) * ccl_f1d_t_eval(cosmo->data.rsd_splines[1],s[i]) * gsl_sf_legendre_Pl(2, mu) + 8. / 35 * beta * beta * ccl_f1d_t_eval(cosmo->data.rsd_splines[2],s[i]) * gsl_sf_legendre_Pl(4, mu); } return; } /*--------ROUTINE: ccl_correlation_3dRsd_avgmu ------ TASK: Calculate the average of redshift-space correlation function xi(s,mu) over mu at constant s INPUT: cosmology, scale factor a, number of s values, s values, beta (= growth rate / bias) The result will be in array xi */ void ccl_correlation_3dRsd_avgmu(ccl_cosmology *cosmo, double a, int n_s, double *s, double beta, double *xi, int *status) { // The average is just the l=0 multipole - the higher multiples inetegrate to zero. ccl_correlation_multipole(cosmo, a, beta, 0, n_s, s, xi, status); return; } /*--------ROUTINE: ccl_correlation_pi_sigma ------ TASK: Calculate the redshift-space correlation function using longitudinal and transverse coordinates pi and sigma. INPUT: cosmology, scale factor a, beta (= growth rate / bias), pi, number of sigma values, sigma values, key for using spline Correlation function result will be in array xi */ void ccl_correlation_pi_sigma(ccl_cosmology *cosmo, double a, double beta, double pi, int n_sig, double *sig, double *xi, int use_spline, int *status) { int i; double *mu_arr, *s_arr, *xi_arr; if (!cosmo->computed_nonlin_power) { *status = CCL_ERROR_NONLIN_POWER_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_correlation.c: ccl_correlation_pi_sigma(): non-linear power spctrum has not been computed!"); return; } mu_arr = malloc(sizeof(double) * n_sig); if (mu_arr == NULL) { *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_pi_sigma ran out of memory\n"); return; } s_arr = malloc(sizeof(double) * n_sig); if (s_arr == NULL) { free(mu_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_pi_sigma ran out of memory\n"); return; } xi_arr = malloc(sizeof(double) * n_sig); if (xi_arr == NULL) { free(mu_arr); free(s_arr); *status = CCL_ERROR_MEMORY; strcpy(cosmo->status_message, "ccl_correlation.c: ccl_correlation_pi_sigma ran out of memory\n"); return; } for (i = 0; i < n_sig; i++) { s_arr[i] = sqrt(pi * pi + sig[i] * sig[i]); mu_arr[i] = pi / s_arr[i]; } for (i = 0; i < n_sig; i++) { ccl_correlation_3dRsd(cosmo, a, n_sig, s_arr, mu_arr[i], beta, xi_arr, use_spline, status); xi[i] = xi_arr[i]; } free(mu_arr); free(xi_arr); free(s_arr); return; }
{ "alphanum_fraction": 0.6458838359, "avg_line_length": 31.3465045593, "ext": "c", "hexsha": "5036bcccac4c509bd963a36406436666c2fb1d3f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "04cb83885ccd5f343b48cd8151bebd5779518ca6", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "damonge/CCL", "max_forks_repo_path": "src/ccl_correlation.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "04cb83885ccd5f343b48cd8151bebd5779518ca6", "max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "damonge/CCL", "max_issues_repo_path": "src/ccl_correlation.c", "max_line_length": 187, "max_stars_count": null, "max_stars_repo_head_hexsha": "04cb83885ccd5f343b48cd8151bebd5779518ca6", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "damonge/CCL", "max_stars_repo_path": "src/ccl_correlation.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9500, "size": 30939 }
/* randist/gausstail.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf_erf.h> double gsl_ran_gaussian_tail (const gsl_rng * r, const double a, const double sigma) { /* Returns a gaussian random variable larger than a * This implementation does one-sided upper-tailed deviates. */ double s = a / sigma; if (s < 1) { /* For small s, use a direct rejection method. The limit s < 1 can be adjusted to optimise the overall efficiency */ double x; do { x = gsl_ran_gaussian (r, 1.0); } while (x < s); return x * sigma; } else { /* Use the "supertail" deviates from the last two steps * of Marsaglia's rectangle-wedge-tail method, as described * in Knuth, v2, 3rd ed, pp 123-128. (See also exercise 11, p139, * and the solution, p586.) */ double u, v, x; do { u = gsl_rng_uniform (r); do { v = gsl_rng_uniform (r); } while (v == 0.0); x = sqrt (s * s - 2 * log (v)); } while (x * u > s); return x * sigma; } } double gsl_ran_gaussian_tail_pdf (const double x, const double a, const double sigma) { if (x < a) { return 0; } else { double N, p; double u = x / sigma ; double f = gsl_sf_erfc (a / (sqrt (2.0) * sigma)); N = 0.5 * f; p = (1 / (N * sqrt (2 * M_PI) * sigma)) * exp (-u * u / 2); return p; } } double gsl_ran_ugaussian_tail (const gsl_rng * r, const double a) { return gsl_ran_gaussian_tail (r, a, 1.0) ; } double gsl_ran_ugaussian_tail_pdf (const double x, const double a) { return gsl_ran_gaussian_tail_pdf (x, a, 1.0) ; }
{ "alphanum_fraction": 0.6088755171, "avg_line_length": 24.6203703704, "ext": "c", "hexsha": "e7c9ced79eabe7ba2af2c490961dfc4ee5e2155c", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/gausstail.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/gausstail.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/randist/gausstail.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 779, "size": 2659 }
#pragma once #include "schedule.h" #include <gsl/gsl-lite.hpp> #include <range/v3/view/span.hpp> #include <vector> namespace angonoka::stun { using ranges::span; struct ScheduleParams; /** Makespan estimator. Further reading: https://en.wikipedia.org/wiki/Makespan */ class Makespan { public: /** Constructor. @param params An instance of ScheduleParams @param tasks_count Total number of tasks @param agents_count Total number of agents */ Makespan(const ScheduleParams& params); Makespan(const Makespan& other); Makespan& operator=(const Makespan& other) noexcept; Makespan(Makespan&& other) noexcept; Makespan& operator=(Makespan&& other) noexcept; ~Makespan() noexcept; /** Calculate the makespan of a given scheduling configuration. @param schedule Scheduling configuration @return Makespan in seconds */ float operator()(Schedule schedule) noexcept; /** Get the current ScheduleParams object. @return Schedule parameters. */ [[nodiscard]] const ScheduleParams& params() const; /** Set the ScheduleParams object. @param params ScheduleParams object */ void params(const ScheduleParams& params); private: struct Impl; gsl::not_null<const ScheduleParams*> params_; std::vector<float> sum_buffer; span<float> task_done; span<float> work_done; }; class RandomUtils; /** Shuffle tasks and agents in-place. Randomly swaps two adjacent tasks within the schedule and reassigns an agent of a random task. */ class Mutator { public: /** Mutator options. @var params Schedule parameters @var random Random utils. */ struct Options { gsl::not_null<const ScheduleParams*> params; gsl::not_null<RandomUtils*> random; }; /** Constructor. @param params An instance of ScheduleParams @param random An instance of RandomUtils */ Mutator(const ScheduleParams& params, RandomUtils& random); Mutator(const Options& options); /** Mutates the scheduling configuration in-place. @param schedule Scheduling configuration */ void operator()(MutSchedule schedule) const noexcept; /** Get current options. @return Options. */ [[nodiscard]] Options options() const; /** Set options. @param options Options. */ void options(const Options& options); private: struct Impl; gsl::not_null<const ScheduleParams*> params; gsl::not_null<RandomUtils*> random; }; } // namespace angonoka::stun
{ "alphanum_fraction": 0.6496649293, "avg_line_length": 21.837398374, "ext": "h", "hexsha": "77ee1df083bde3ac502efa51c706bc211f50517a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_path": "src/stun/utils.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_path": "src/stun/utils.h", "max_line_length": 67, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_path": "src/stun/utils.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "num_tokens": 575, "size": 2686 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "parmt_invert.h" #ifdef PARMT_USE_INTEL #include <mkl_lapacke.h> #include <mkl_cblas.h> #else #include <lapacke.h> #include <cblas.h> #endif #include "parmt_utils.h" #include "iscl/array/array.h" #include "iscl/linalg/linalg.h" #include "iscl/memory/memory.h" /*! * @brief Inverts for a moment tensor at each location in the grid-search. * * @param[in] data parMT data structure with observations and * corresponding green's functions at all locations * for all waveforms. * @param[in] ldm Leading dimension of mts. This must be at least 6. * @param[in] lcDev If true then apply the deviatoric constraint. * @param[in] lcDev Otherwise invert for all moment tensors terms. * * @param[out] mts Moment tensors tabulated at each location. This has * dimension [data.nlocs x ldm]. * @param[out] phi L2 objective function for each moment tensor. This has * dimension [data.nlocs]. * * @result 0 indicates success. * */ int parmt_invertLocationSearch(struct parmtData_struct data, const int ldm, const bool lcDev, double *__restrict__ mts, double *__restrict__ phi) { double *G, *gxxAll, *gyyAll, *gzzAll, *gxyAll, *gxzAll, *gyzAll, *obsAll, *wts; //double m6[6], phiLoc; int *dataPtr, i1, ierr, ierr1, ierr2, iloc, iobs, k, mrows; ierr = 0; if (ldm < 6 || mts == NULL || phi == NULL) { if (ldm < 6){fprintf(stderr, "%s: ldm must be at least 6\n", __func__);} if (mts == NULL){fprintf(stderr, "%s: mts is NULL\n", __func__);} if (phi == NULL){fprintf(stderr, "%s: phi is NULL\n", __func__);} return -1; } G = NULL; wts = NULL; gxxAll = NULL; gyyAll = NULL; gzzAll = NULL; gxyAll = NULL; gxzAll = NULL; gyzAll = NULL; // 6 observations required for full MT, 5 for deviatoric constraint if (data.nobs < 6 - (int) lcDev) { fprintf(stderr, "%s: Insufficient number of observations \n", __func__); return -1; } // Figure out the workspace dataPtr = memory_calloc32i(data.nobs+1); for (iobs=0; iobs<data.nobs; iobs++) { dataPtr[iobs+1] = dataPtr[iobs] + data.data[iobs].npts; } if (dataPtr[data.nobs] < 6 - (int) lcDev) { fprintf(stderr, "%s: Insufficient number of points to invert with\n", __func__); goto ERROR; } obsAll = memory_calloc64f(dataPtr[data.nobs]); gxxAll = memory_calloc64f(dataPtr[data.nobs]); gyyAll = memory_calloc64f(dataPtr[data.nobs]); gzzAll = memory_calloc64f(dataPtr[data.nobs]); gxyAll = memory_calloc64f(dataPtr[data.nobs]); gxzAll = memory_calloc64f(dataPtr[data.nobs]); gyzAll = memory_calloc64f(dataPtr[data.nobs]); // Loop on locations for (iloc=0; iloc<data.nlocs; iloc++) { // Loop on observations ierr1 = 0; ierr2 = 0; for (iobs=0; iobs<data.nobs; iobs++) { k = iobs*data.nlocs + iloc;; G = parmt_utils_sacGrns2GrnsMat(data.sacGxx[k], data.sacGyy[k], data.sacGzz[k], data.sacGxy[k], data.sacGxz[k], data.sacGyz[k], &mrows, &ierr1); memory_free64f(&G); if (ierr1 != 0) { fprintf(stderr, "%s: Failed to make greens functions matrix\n", __func__); ierr2 = ierr2 + 1; } if (mrows != dataPtr[iobs+1] - dataPtr[iobs]) { fprintf(stderr, "%s: Internal error on mrows and npts\n", __func__); ierr2 = ierr2 + 1; goto NEXT_OBS; } // Copy the observations and Green's functions i1 = dataPtr[iobs]; cblas_dcopy(mrows, &G[0*mrows], 1, &gxxAll[i1], 1); cblas_dcopy(mrows, &G[1*mrows], 1, &gyyAll[i1], 1); cblas_dcopy(mrows, &G[2*mrows], 1, &gzzAll[i1], 1); cblas_dcopy(mrows, &G[3*mrows], 1, &gxyAll[i1], 1); cblas_dcopy(mrows, &G[4*mrows], 1, &gxzAll[i1], 1); cblas_dcopy(mrows, &G[5*mrows], 1, &gyzAll[i1], 1); cblas_dcopy(mrows, data.data[iobs].data, 1, &obsAll[i1], 1); NEXT_OBS:; memory_free64f(&G); } // loop on observations // Invert it if (ierr2 != 0) { ierr1 = parmt_invertMT64f(data.nobs, lcDev, dataPtr, wts, gxxAll, gyyAll, gzzAll, gxyAll, gxzAll, gyzAll, obsAll, &phi[iloc], &mts[iloc*ldm]); //&phiLoc, m6); if (ierr1 != 0) { fprintf(stderr, "%s: Error inverting location %d\n", __func__, iloc); ierr = ierr + 1; } } else { ierr = ierr + 1; } } ERROR:; memory_free32i(&dataPtr); memory_free64f(&gxxAll); memory_free64f(&gyyAll); memory_free64f(&gzzAll); memory_free64f(&gxyAll); memory_free64f(&gxzAll); memory_free64f(&gyzAll); return 0; } //============================================================================// /*! * @brief * * @param[in] nobs number of waveforms (observations) * @param[in] lcDev if true then force the solution to be purely deviatoric. * otherwise all moment tensor terms will be inverted for. * @param[in] dataPtr points from iobs'th observation to start index of * observation [nobs+1] * @param[in] wts if not NULL then these are the data weights for each * observations [nobs]. * @param[in] gxxAll all Gxx greens functions [dataPtr[nobs]] * @param[in] gyyAll all Gyy greens functions [dataPtr[nobs]] * @param[in] gzzAll all Gzz greens functions [dataPtr[nobs]] * @param[in] gxyAll all Gxy greens functions [dataPtr[nobs]] * @param[in] gxzAll all Gxz greens functions [dataPtr[nobs]] * @param[in] gyzAll all Gyz greens functions [dataPtr[nobs]] * @param[in] obsAll observations [dataPtr[nobs]] * * @param[out] phi L2 difference between observed and estimate seismograms. * @param[out] m on successful contains the moment tensor elements packed * \f$\{ m_{xx}, m_{yy}, m_{zz}, * m_{xy}, m_{xz}, m_{yz} \}\f$. * * @result 0 indicates success * * @author Ben Baker * * @copyright ISTI distributed under Apache 2 * */ int parmt_invertMT64f(const int nobs, const bool lcDev, const int *dataPtr, const double *__restrict__ wts, const double *__restrict__ gxxAll, const double *__restrict__ gyyAll, const double *__restrict__ gzzAll, const double *__restrict__ gxyAll, const double *__restrict__ gxzAll, const double *__restrict__ gyzAll, const double *__restrict__ obsAll, double *phi, double *__restrict__ m) { double *G, *b, *est, m6[6]; int i1, i2, ierr, iobs, ldg, mrows, ncols, nploc; *phi = 0.0; ierr = 0; // Create the forward modeling matrix if (nobs < 5 || dataPtr == NULL || gxxAll == NULL || gyyAll == NULL || gzzAll == NULL || gxyAll == NULL || gxzAll == NULL || gyzAll == NULL || m == NULL) { if (nobs < 5) { fprintf(stderr, "%s: At least 6 observations required\n", __func__); } if (dataPtr == NULL) { fprintf(stderr, "%s: Error dataPtr is NULL\n", __func__); } if (gxxAll == NULL) { fprintf(stderr, "%s: Error gxxAll is NULL\n", __func__); } if (gyyAll == NULL) { fprintf(stderr, "%s: Error gyyAll is NULL\n", __func__); } if (gzzAll == NULL) { fprintf(stderr, "%s: Error gzzAll is NULL\n", __func__); } if (gxyAll == NULL) { fprintf(stderr, "%s: Error gxyAll is NULL\n", __func__); } if (gxzAll == NULL) { fprintf(stderr, "%s: Error gxzAll is NULL\n", __func__); } if (gyzAll == NULL) { fprintf(stderr, "%s: Error gyzAll is NULL\n", __func__); } if (m == NULL){fprintf(stderr, "%s: Error m is NULL\n", __func__);} return -1; } memset(m, 0, 6*sizeof(double)); ncols = 6; if (lcDev){ncols = 5;} // Get the data size mrows = 0; for (iobs=0; iobs<nobs; iobs++) { mrows = mrows + dataPtr[iobs-1] - dataPtr[iobs]; } if (mrows < ncols) { fprintf(stderr, "%s: Error problem is undetermined\n", __func__); return -1; } ldg = mrows; G = memory_calloc64f(ldg*ncols); b = memory_calloc64f(mrows); est = memory_calloc64f(mrows); // Set the forward modeling matrix if (wts == NULL) { if (lcDev) { cblas_dcopy(mrows, gxxAll, 1, &G[0*ldg], 1); cblas_daxpy(mrows, -1.0, gzzAll, 1, &G[0*ldg], 1); // mxx - mzz cblas_dcopy(mrows, gyyAll, 1, &G[1*ldg], 1); cblas_daxpy(mrows, -1.0, gzzAll, 1, &G[1*ldg], 1); // myy - mzz cblas_dcopy(mrows, gxyAll, 1, &G[2*ldg], 1); cblas_dcopy(mrows, gxzAll, 1, &G[3*ldg], 1); cblas_dcopy(mrows, gyzAll, 1, &G[4*ldg], 1); } else { cblas_dcopy(mrows, gxxAll, 1, &G[0*ldg], 1); cblas_dcopy(mrows, gyyAll, 1, &G[1*ldg], 1); cblas_dcopy(mrows, gyyAll, 1, &G[2*ldg], 1); cblas_dcopy(mrows, gxyAll, 1, &G[3*ldg], 1); cblas_dcopy(mrows, gxzAll, 1, &G[4*ldg], 1); cblas_dcopy(mrows, gyzAll, 1, &G[5*ldg], 1); } cblas_dcopy(mrows, obsAll, 1, b, 1); } else { if (lcDev) { for (iobs=0; iobs<nobs; iobs++) { i1 = dataPtr[iobs]; i2 = dataPtr[iobs]; nploc = i2 - i1; cblas_daxpy(nploc, wts[iobs], &gxxAll[i1], 1, &G[0*ldg+i1], 1); cblas_daxpy(nploc,-wts[iobs], &gzzAll[i1], 1, &G[0*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gyyAll[i1], 1, &G[1*ldg+i1], 1); cblas_daxpy(nploc,-wts[iobs], &gzzAll[i1], 1, &G[1*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gxyAll[i1], 1, &G[2*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gxzAll[i1], 1, &G[3*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gyzAll[i1], 1, &G[4*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &obsAll[i1], 1, &b[i1], 1); } } else { for (iobs=0; iobs<nobs; iobs++) { i1 = dataPtr[iobs]; i2 = dataPtr[iobs]; nploc = i2 - i1; cblas_daxpy(nploc, wts[iobs], &gxxAll[i1], 1, &G[0*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gyyAll[i1], 1, &G[1*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gzzAll[i1], 1, &G[2*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gxyAll[i1], 1, &G[3*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gxzAll[i1], 1, &G[4*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &gyzAll[i1], 1, &G[5*ldg+i1], 1); cblas_daxpy(nploc, wts[iobs], &obsAll[i1], 1, &b[i1], 1); } } } // Solve \tilde{G} m = \tilde{b} ierr = linalg_lstsq_qr64f_work(LAPACK_COL_MAJOR, mrows, ncols, 1, false, G, b, m6, NULL); if (ierr != 0) { fprintf(stderr, "%s: Error solving Gm=u\n", __func__); ierr = 1; goto END; } if (lcDev) { m[0] = m6[0]; m[1] = m6[1]; m[2] =-(m6[0] + m6[1]); m[3] = m6[2]; m[4] = m6[3]; m[5] = m6[4]; } else { cblas_dcopy(6, m6, 1, m, 1); } // Apply u = \tilde{G} m cblas_dgemv(CblasColMajor, CblasNoTrans, mrows, ncols, 1.0, G, ncols, m6, 1, 0.0, est, 1); // Compute the least-squares residual *phi = array_normDiff64f(mrows, est, b, TWO_NORM, 2.0, &ierr); END:; // Release memory memory_free64f(&G); memory_free64f(&b); memory_free64f(&est); return ierr; }
{ "alphanum_fraction": 0.500536152, "avg_line_length": 36.0662983425, "ext": "c", "hexsha": "ac799db7002b78c66a0cd485377e59280e2e9cdb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "src/invert.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_path": "src/invert.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "src/invert.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4031, "size": 13056 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <array> #include <gsl/gsl> #include <optional> #include <type_traits> namespace couchbase::protocol { /** * Helper code for encode and decode of LEB128 values. * - mcbp encodes collection-ID as an unsigned LEB128 * - see https://en.wikipedia.org/wiki/LEB128 */ struct Leb128NoThrow { }; /** * decode_unsigned_leb128 returns the decoded T and a const_byte_buffer * initialised with the data following the leb128 data. This form of the decode * does not throw for invalid input and the caller should always check * second.data() for success or error (see returns info). * * @param buf buffer containing a leb128 encoded value (of size T) * @returns On error a std::pair where first is set to 0 and second is nullptr/0 * const_byte_buffer. On success a std::pair where first is the decoded * value and second is a buffer initialised with the data following the * leb128 data. */ template<class T> typename std::enable_if_t<std::is_unsigned_v<T>, std::pair<T, std::string_view>> decode_unsigned_leb128(std::string_view buf, struct Leb128NoThrow /* unused */) { T rv = static_cast<uint8_t>(buf[0]) & 0x7fULL; size_t end = 0; if ((static_cast<uint8_t>(buf[0]) & 0x80ULL) == 0x80ULL) { T shift = 7; // shift in the remaining data for (end = 1; end < buf.size(); end++) { rv |= (static_cast<uint8_t>(buf[end]) & 0x7fULL) << shift; if ((static_cast<uint8_t>(buf[end]) & 0x80ULL) == 0) { break; // no more } shift += 7; } // We should of stopped for a stop byte, not the end of the buffer if (end == buf.size()) { return { 0, std::string_view{} }; } } // Return the decoded value and a buffer for any remaining data return { rv, std::string_view{ buf.data() + end + 1, buf.size() - (end + 1) } }; } /** * decode_unsigned_leb128 returns the decoded T and a const_byte_buffer * initialised with the data following the leb128 data. This form of the decode * throws for invalid input. * * @param buf buffer containing a leb128 encoded value (of size T) * @returns std::pair first is the decoded value and second a buffer for the * remaining data (size will be 0 for no more data) * @throws std::invalid_argument if buf[0] does not encode a leb128 value with * a stop byte. */ template<class T> typename std::enable_if_t<std::is_unsigned_v<T>, std::pair<T, std::string_view>> decode_unsigned_leb128(std::string_view buf) { if (buf.size() > 0) { auto rv = decode_unsigned_leb128<T>(buf, Leb128NoThrow()); if (rv.second.data()) { return rv; } } throw std::invalid_argument("decode_unsigned_leb128: invalid buf size:" + std::to_string(buf.size())); } /** * @return a buffer to the data after the leb128 prefix */ template<class T> typename std::enable_if_t<std::is_unsigned_v<T>, std::string_view> skip_unsigned_leb128(std::string_view buf) { return decode_unsigned_leb128<T>(buf).second; } // Empty, non specialised version of the decoder class template<class T, class Enable = void> class unsigned_leb128 { }; /** * For encoding a unsigned T leb128, class constructs from a T value and * provides a const_byte_buffer for access to the encoded */ template<class T> class unsigned_leb128<T, typename std::enable_if_t<std::is_unsigned_v<T>>> { public: explicit unsigned_leb128(T in) { while (in > 0) { auto byte = gsl::narrow_cast<uint8_t>(in & 0x7fULL); in >>= 7; // In has more data? if (in > 0) { byte |= 0x80; encodedData[encodedSize - 1U] = byte; // Increase the size encodedSize++; } else { encodedData[encodedSize - 1U] = byte; } } } [[nodiscard]] std::string get() const { return { begin(), end() }; } [[nodiscard]] const uint8_t* begin() const { return encodedData.data(); } [[nodiscard]] const uint8_t* end() const { return encodedData.data() + encodedSize; } [[nodiscard]] const uint8_t* data() const { return encodedData.data(); } [[nodiscard]] size_t size() const { return encodedSize; } constexpr static size_t getMaxSize() { return maxSize; } private: // Larger T may need a larger array static_assert(sizeof(T) <= 8, "Class is only valid for uint 8/16/64"); // value is large enough to store ~0 as leb128 static constexpr size_t maxSize = sizeof(T) + (((sizeof(T) + 1) / 8) + 1); std::array<uint8_t, maxSize> encodedData{}; uint8_t encodedSize{ 1 }; }; } // namespace couchbase::protocol
{ "alphanum_fraction": 0.6325388227, "avg_line_length": 30.5966850829, "ext": "h", "hexsha": "65411a35922f61eb62ca982521350de19b3d5182", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-12-29T07:07:27.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-29T07:07:27.000Z", "max_forks_repo_head_hexsha": "fc1ae7706d3b1eb3e35f02a005327411ec34a00f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "avsej/couchbase-ruby-client", "max_forks_repo_path": "ext/couchbase/protocol/unsigned_leb128.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc1ae7706d3b1eb3e35f02a005327411ec34a00f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "avsej/couchbase-ruby-client", "max_issues_repo_path": "ext/couchbase/protocol/unsigned_leb128.h", "max_line_length": 106, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fc1ae7706d3b1eb3e35f02a005327411ec34a00f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "avsej/couchbase-ruby-client", "max_stars_repo_path": "ext/couchbase/protocol/unsigned_leb128.h", "max_stars_repo_stars_event_max_datetime": "2015-05-18T09:47:40.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-18T09:47:40.000Z", "num_tokens": 1434, "size": 5538 }
#pragma once /**************************************************************************** * * nc.h * ($\nativecoin-cpp\src) * * by icedac * ***/ #ifndef ___NATIVECOIN__NATIVECOIN__NC_H_ #define ___NATIVECOIN__NATIVECOIN__NC_H_ #include <string> #include <vector> #include <unordered_map> #include <set> #include <iostream> #include <sstream> #define GSL_THROW_ON_CONTRACT_VIOLATION #include <gsl/gsl> #include <utility> #include <stdio.h> #include <tuple> #include <iomanip> #include "platform.h" namespace nc { typedef unsigned char byte; typedef std::int32_t int32; typedef std::int64_t int64; typedef std::uint32_t uint32; typedef std::uint64_t uint64; using string = std::string; template < typename T > using vector = std::vector<T>; template < typename T > using set = std::set<T>; using stringstream = std::stringstream; using ostringstream = std::ostringstream; template < typename K, typename T > using unordered_map = std::unordered_map< K, T>; typedef uint32 difficulty_t; typedef uint64 nonce_t; typedef uint64 timestamp_t; typedef uint32 blockindex_t; } namespace nc { class coin { public: static const auto SATOSHI_PER_COIN = 1000000; explicit inline coin() noexcept : satoshi(0) {} explicit inline coin(int32 amount) noexcept : satoshi(amount*SATOSHI_PER_COIN) {} inline coin(const coin& c) = default; inline coin& operator = (const coin& rhs) = default; inline coin(coin&& c) = default; inline coin& operator = (coin&& rhs) = default; inline operator int32() const { return get(); } inline coin& operator += (const coin& rhs) { satoshi += rhs.get_as_satoshi(); return *this; } inline coin& operator -= (const coin& rhs) { satoshi -= rhs.get_as_satoshi(); return *this; } inline coin operator + (const coin& rhs) { return coin::from_satoshi(this->get_as_satoshi() + rhs.get_as_satoshi()); } inline coin operator - (const coin& rhs) { return coin::from_satoshi(this->get_as_satoshi() - rhs.get_as_satoshi()); } inline bool operator == (const coin& rhs) const { return this->satoshi == rhs.satoshi; } inline bool operator != (const coin& rhs) const { return !(*this == rhs); } inline int32 get() const { return (int32)(satoshi / SATOSHI_PER_COIN); } inline int64 get_as_satoshi() const { return satoshi; } inline int64 get_satoshi() const { return satoshi % SATOSHI_PER_COIN; } inline string as_string() const { int64 satoshi = get_satoshi(); ostringstream ss; ss << get() << "."; if (satoshi) ss << std::setfill('0') << std::setw(6) << satoshi; else ss << "00"; return ss.str(); } static inline coin from_satoshi(int64 satoshi) { coin c{ 0 }; c.satoshi = satoshi; return c; } private: int64 satoshi; }; } #endif// ___NATIVECOIN__NATIVECOIN__NC_H_
{ "alphanum_fraction": 0.5464306442, "avg_line_length": 25.9097744361, "ext": "h", "hexsha": "e22963c02f96538f0a6f6173866f8371808a83b9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "cc5ea9c9dfc7e8974f3b580cbb3767354d0b9b78", "max_forks_repo_licenses": [ "BSL-1.0", "BSD-3-Clause", "OpenSSL", "MIT" ], "max_forks_repo_name": "icedac/nativecoin-cpp", "max_forks_repo_path": "src/nc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "cc5ea9c9dfc7e8974f3b580cbb3767354d0b9b78", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSL-1.0", "BSD-3-Clause", "OpenSSL", "MIT" ], "max_issues_repo_name": "icedac/nativecoin-cpp", "max_issues_repo_path": "src/nc.h", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "cc5ea9c9dfc7e8974f3b580cbb3767354d0b9b78", "max_stars_repo_licenses": [ "BSL-1.0", "BSD-3-Clause", "OpenSSL", "MIT" ], "max_stars_repo_name": "icedac/nativecoin-cpp", "max_stars_repo_path": "src/nc.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 812, "size": 3446 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C code for structures representing a waveform as a list of modes in amplitude/phase form. * */ #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "struct.h" /* Call a function that references an object */ double ObjectFunctionCall(const ObjectFunction* this,double f){return this->function(this->object,f);}; /**************************************************************/ /* Functions computing the max and min between two int */ int max (int a, int b) { return a > b ? a : b; } int min (int a, int b) { return a < b ? a : b; } /************** GSL error handling and I/O ********************/ /* GSL error handler */ void Err_Handler(const char *reason, const char *file, int line, int gsl_errno) { printf("gsl: %s:%d: %s - %d\n", file, line, reason, gsl_errno); exit(1); } /* Functions to read binary data from files */ int Read_Vector(const char dir[], const char fname[], gsl_vector *v) { char *path=malloc(strlen(dir)+64); sprintf(path,"%s/%s", dir, fname); FILE *f = fopen(path, "rb"); if (!f) { fprintf(stderr, "Error reading data from %s\n", path); free(path); return(FAILURE); } int ret = gsl_vector_fread(f, v); if (ret != 0) { fprintf(stderr, "Error reading data from %s.\n",path); free(path); return(FAILURE); } fclose(f); free(path); return(SUCCESS); } int Read_Matrix(const char dir[], const char fname[], gsl_matrix *m) { char *path=malloc(strlen(dir)+64); sprintf(path,"%s/%s", dir, fname); FILE *f = fopen(path, "rb"); if (!f) { fprintf(stderr, "Error reading data from %s\n", path); free(path); return(FAILURE); } int ret = gsl_matrix_fread(f, m); if (ret != 0) { fprintf(stderr, "Error reading data from %s\n", path); free(path); return(FAILURE); } fclose(f); free(path); return(SUCCESS); } /* Functions to read text data from files */ int Read_Text_Vector(const char dir[], const char fname[], gsl_vector *v) { char *path=malloc(strlen(dir)+64); sprintf(path,"%s/%s", dir, fname); FILE *f = fopen(path, "rb"); if (!f) { fprintf(stderr, "Error reading data from %s\n", path); free(path); return(FAILURE); } int ret = gsl_vector_fscanf(f, v); if (ret != 0) { fprintf(stderr, "Error reading data from %s.\n",path); free(path); return(FAILURE); } fclose(f); free(path); return(SUCCESS); } int Read_Text_Matrix(const char dir[], const char fname[], gsl_matrix *m) { char *path=malloc(strlen(dir)+64); sprintf(path,"%s/%s", dir, fname); FILE *f = fopen(path, "rb"); if (!f) { fprintf(stderr, "Error reading data from %s\n", path); free(path); return(FAILURE); } int ret = gsl_matrix_fscanf(f, m); if (ret != 0) { fprintf(stderr, "Error reading data from %s.\n",path); free(path); return(FAILURE); } fclose(f); free(path); return(SUCCESS); } /* Functions to write data to files */ int Write_Vector(const char dir[], const char fname[], gsl_vector *v) { char *path=malloc(strlen(dir)+64); sprintf(path,"%s/%s", dir, fname); FILE *f = fopen(path, "w"); if (!f) { fprintf(stderr, "Error writing data to %s\n", path); free(path); return(FAILURE); } int ret = gsl_vector_fwrite(f, v); if (ret != 0) { fprintf(stderr, "Error writing data to %s\n",path); free(path); return(FAILURE); } fclose(f); free(path); return(SUCCESS); } int Write_Matrix(const char dir[], const char fname[], gsl_matrix *m) { char *path=malloc(strlen(dir)+64); sprintf(path,"%s/%s", dir, fname); FILE *f = fopen(path, "w"); if (!f) { fprintf(stderr, "Error writing data to %s\n", path); free(path); return(FAILURE); } int ret = gsl_matrix_fwrite(f, m); if (ret != 0) { fprintf(stderr, "Error writing data to %s\n", path); free(path); return(FAILURE); } fclose(f); free(path); return(SUCCESS); } /* Functions to write text data to files */ int Write_Text_Vector(const char dir[], const char fname[], gsl_vector *v) { char *path=malloc(strlen(dir)+64); sprintf(path,"%s/%s", dir, fname); FILE *f = fopen(path, "w"); if (!f) { fprintf(stderr, "Error writing data to %s\n", path); free(path); return(FAILURE); } int ret = gsl_vector_fprintf(f, v, "%.16e"); if (ret != 0) { fprintf(stderr, "Error writing data to %s\n",path); free(path); return(FAILURE); } fclose(f); free(path); return(SUCCESS); } int Write_Text_Matrix(const char dir[], const char fname[], gsl_matrix *m) { char *path=malloc(strlen(dir)+64); int ret = 0; sprintf(path,"%s/%s", dir, fname); FILE *f = fopen(path, "w"); if (!f) { fprintf(stderr, "Error writing data to %s\n",path); free(path); return(FAILURE); } int N = (int) m->size1; int M = (int) m->size2; for(int i=0; i<N; i++){ for(int j=0; j<M; j++){ ret |= (fprintf(f, "%.16e ", gsl_matrix_get(m, i, j)) < 0); } if(i < N-1) ret |= (fprintf(f, "\n") < 0); } if (ret != 0) { fprintf(stderr, "Error writing data to %s\n",path); free(path); return(FAILURE); } fclose(f); free(path); return(SUCCESS); } /******** Functions to initialize and clean up CAmpPhaseFrequencySeries structure ********/ void CAmpPhaseFrequencySeries_Init(CAmpPhaseFrequencySeries **freqseries, const int n) { if(!freqseries) exit(1); /* Create storage for structures */ if(!*freqseries) *freqseries=malloc(sizeof(CAmpPhaseFrequencySeries)); else { CAmpPhaseFrequencySeries_Cleanup(*freqseries); *freqseries=malloc(sizeof(CAmpPhaseFrequencySeries)); } gsl_set_error_handler(&Err_Handler); (*freqseries)->freq = gsl_vector_alloc(n); (*freqseries)->amp_real = gsl_vector_alloc(n); (*freqseries)->amp_imag = gsl_vector_alloc(n); (*freqseries)->phase = gsl_vector_alloc(n); } void CAmpPhaseFrequencySeries_Cleanup(CAmpPhaseFrequencySeries *freqseries) { if(freqseries->freq) gsl_vector_free(freqseries->freq); if(freqseries->amp_real) gsl_vector_free(freqseries->amp_real); if(freqseries->amp_imag) gsl_vector_free(freqseries->amp_imag); if(freqseries->phase) gsl_vector_free(freqseries->phase); free(freqseries); } /******** Functions to initialize and clean up CAmpPhaseSpline structure ********/ void CAmpPhaseSpline_Init(CAmpPhaseSpline **splines, const int n) { if(!splines) exit(1); /* Create storage for structures */ if(!*splines) *splines=malloc(sizeof(CAmpPhaseSpline)); else { CAmpPhaseSpline_Cleanup(*splines); } gsl_set_error_handler(&Err_Handler); (*splines)->spline_amp_real = gsl_matrix_alloc(n, 5); (*splines)->spline_amp_imag = gsl_matrix_alloc(n, 5); (*splines)->quadspline_phase = gsl_matrix_alloc(n, 4); } void CAmpPhaseSpline_Cleanup(CAmpPhaseSpline *splines) { if(splines->spline_amp_real) gsl_matrix_free(splines->spline_amp_real); if(splines->spline_amp_imag) gsl_matrix_free(splines->spline_amp_imag); if(splines->quadspline_phase) gsl_matrix_free(splines->quadspline_phase); free(splines); } /******** Functions to initialize and clean up CAmpPhaseGSLSpline structure ********/ void CAmpPhaseGSLSpline_Init(CAmpPhaseGSLSpline **splines, const int n) { if(!splines) exit(1); /* Create storage for structures */ if(!*splines) *splines=malloc(sizeof(CAmpPhaseGSLSpline)); else { CAmpPhaseGSLSpline_Cleanup(*splines); } gsl_set_error_handler(&Err_Handler); /* Note: for freq we won't copy the vector but simply copy the pointer to the existing one, so we don't allocate anything here */ (*splines)->spline_amp_real = gsl_spline_alloc(gsl_interp_cspline, n); (*splines)->spline_amp_imag = gsl_spline_alloc(gsl_interp_cspline, n); (*splines)->spline_phase = gsl_spline_alloc(gsl_interp_cspline, n); (*splines)->accel_amp_real = gsl_interp_accel_alloc(); (*splines)->accel_amp_imag = gsl_interp_accel_alloc(); (*splines)->accel_phase = gsl_interp_accel_alloc(); } void CAmpPhaseGSLSpline_Cleanup(CAmpPhaseGSLSpline *splines) { if(splines->spline_amp_real) gsl_spline_free(splines->spline_amp_real); if(splines->spline_amp_imag) gsl_spline_free(splines->spline_amp_imag); if(splines->spline_phase) gsl_spline_free(splines->spline_phase); if(splines->accel_amp_real) gsl_interp_accel_free(splines->accel_amp_real); if(splines->accel_amp_imag) gsl_interp_accel_free(splines->accel_amp_imag); if(splines->accel_phase) gsl_interp_accel_free(splines->accel_phase); free(splines); } /******** Functions to initialize and clean up ReImFrequencySeries structure ********/ void ReImFrequencySeries_Init(ReImFrequencySeries **freqseries, const int n) { if(!freqseries) exit(1); /* Create storage for structures */ if(!*freqseries) *freqseries=malloc(sizeof(ReImFrequencySeries)); else { ReImFrequencySeries_Cleanup(*freqseries); } gsl_set_error_handler(&Err_Handler); (*freqseries)->freq = gsl_vector_alloc(n); (*freqseries)->h_real = gsl_vector_alloc(n); (*freqseries)->h_imag = gsl_vector_alloc(n); } void ReImFrequencySeries_Cleanup(ReImFrequencySeries *freqseries) { if(freqseries->freq) gsl_vector_free(freqseries->freq); if(freqseries->h_real) gsl_vector_free(freqseries->h_real); if(freqseries->h_imag) gsl_vector_free(freqseries->h_imag); free(freqseries); } /******** Functions to initialize and clean up ReImTimeSeries structure ********/ void ReImTimeSeries_Init(ReImTimeSeries **timeseries, const int n) { if(!timeseries) exit(1); /* Create storage for structures */ if(!*timeseries) *timeseries=malloc(sizeof(ReImTimeSeries)); else { ReImTimeSeries_Cleanup(*timeseries); } gsl_set_error_handler(&Err_Handler); (*timeseries)->times = gsl_vector_alloc(n); (*timeseries)->h_real = gsl_vector_alloc(n); (*timeseries)->h_imag = gsl_vector_alloc(n); } void ReImTimeSeries_Cleanup(ReImTimeSeries *timeseries) { if(timeseries->times) gsl_vector_free(timeseries->times); if(timeseries->h_real) gsl_vector_free(timeseries->h_real); if(timeseries->h_imag) gsl_vector_free(timeseries->h_imag); free(timeseries); } /******** Functions to initialize and clean up AmpPhaseTimeSeries structure ********/ void AmpPhaseTimeSeries_Init(AmpPhaseTimeSeries **timeseries, const int n) { if(!timeseries) exit(1); /* Create storage for structures */ if(!*timeseries) *timeseries=malloc(sizeof(AmpPhaseTimeSeries)); else { AmpPhaseTimeSeries_Cleanup(*timeseries); } gsl_set_error_handler(&Err_Handler); (*timeseries)->times = gsl_vector_alloc(n); (*timeseries)->h_amp = gsl_vector_alloc(n); (*timeseries)->h_phase = gsl_vector_alloc(n); } void AmpPhaseTimeSeries_Cleanup(AmpPhaseTimeSeries *timeseries) { if(timeseries->times) gsl_vector_free(timeseries->times); if(timeseries->h_amp) gsl_vector_free(timeseries->h_amp); if(timeseries->h_phase) gsl_vector_free(timeseries->h_phase); free(timeseries); } /******** Functions to initialize and clean up RealTimeSeries structure ********/ void RealTimeSeries_Init(RealTimeSeries **timeseries, const int n) { if(!timeseries) exit(1); /* Create storage for structures */ if(!*timeseries) *timeseries=malloc(sizeof(RealTimeSeries)); else { RealTimeSeries_Cleanup(*timeseries); } gsl_set_error_handler(&Err_Handler); (*timeseries)->times = gsl_vector_alloc(n); (*timeseries)->h = gsl_vector_alloc(n); } void RealTimeSeries_Cleanup(RealTimeSeries *timeseries) { if(timeseries->times) gsl_vector_free(timeseries->times); if(timeseries->h) gsl_vector_free(timeseries->h); free(timeseries); } /***************** Functions for the ListmodesCAmpPhaseFrequencySeries structure ****************/ ListmodesCAmpPhaseFrequencySeries* ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy( ListmodesCAmpPhaseFrequencySeries* appended, /* List structure to prepend to */ CAmpPhaseFrequencySeries* freqseries, /* data to contain */ int l, /* major mode number */ int m /* minor mode number */) { ListmodesCAmpPhaseFrequencySeries* list; /* Check if the node with this mode already exists */ list = appended; while( list ){ if( l == list->l && m == list->m ){ break; } list = list->next; } if( list ){ /* We don't allow for the case where the mode already exists in the list*/ printf("Error: Tried to add an already existing mode to a ListmodesCAmpPhaseFrequencySeries "); return(NULL); } else { /* In that case, we do NOT COPY the input interpolated data, which therefore can't be used anywhere else; this will be acceptable as these operations will only be done when interpolating the initialization data */ list = malloc( sizeof(ListmodesCAmpPhaseFrequencySeries) ); } list->l = l; list->m = m; if( freqseries ){ list->freqseries = freqseries; } else { list->freqseries = NULL; } if( appended ){ list->next = appended; } else { list->next = NULL; } return list; } /* Get the element of a ListmodesCAmpPhaseFrequencySeries with a given index */ ListmodesCAmpPhaseFrequencySeries* ListmodesCAmpPhaseFrequencySeries_GetMode( ListmodesCAmpPhaseFrequencySeries* const list, /* List structure to get a particular mode from */ int l, /*< major mode number */ int m /*< minor mode number */ ) { if( !list ) return NULL; ListmodesCAmpPhaseFrequencySeries *itr = list; while( itr->l != l || itr->m != m ){ itr = itr->next; if( !itr ) return NULL; } return itr; /* The element returned is itself a pointer to a ListmodesCAmpPhaseFrequencySeries */ } void ListmodesCAmpPhaseFrequencySeries_Destroy( ListmodesCAmpPhaseFrequencySeries* list /* List structure to destroy; notice that the data is destroyed too */ ) { ListmodesCAmpPhaseFrequencySeries* pop; while( (pop = list) ){ if( pop->freqseries ){ /* Destroying the CAmpPhaseFrequencySeries data */ CAmpPhaseFrequencySeries_Cleanup( pop->freqseries ); } /* Notice that the mode indices l and m are not freed, like in SphHarmTimeSeries struct indices l and m */ list = pop->next; free( pop ); } } /***************** Functions for the ListmodesCAmpPhaseSpline structure ****************/ ListmodesCAmpPhaseSpline* ListmodesCAmpPhaseSpline_AddModeNoCopy( ListmodesCAmpPhaseSpline* appended, /* List structure to prepend to */ CAmpPhaseSpline* splines, /* data to contain */ int l, /* major mode number */ int m /* minor mode number */) { ListmodesCAmpPhaseSpline* list; /* Check if the node with this mode already exists */ list = appended; while( list ){ if( l == list->l && m == list->m ){ break; } list = list->next; } if( list ){ /* We don't allow for the case where the mode already exists in the list*/ printf("Error: Tried to add an already existing mode to a ListmodesCAmpPhaseSpline "); return(NULL); } else { /* In that case, we do NOT COPY the input interpolated data, which therefore can't be used anywhere else; this will be acceptable as these operations will only be done when interpolating the initialization data */ list = malloc( sizeof(ListmodesCAmpPhaseSpline) ); } list->l = l; list->m = m; if( splines ){ list->splines = splines; } else { list->splines = NULL; } if( appended ){ list->next = appended; } else { list->next = NULL; } return list; } /* Get the element of a ListmodesCAmpPhaseSpline with a given index */ ListmodesCAmpPhaseSpline* ListmodesCAmpPhaseSpline_GetMode( ListmodesCAmpPhaseSpline* const list, /* List structure to get a particular mode from */ int l, /*< major mode number */ int m /*< minor mode number */ ) { if( !list ) return NULL; ListmodesCAmpPhaseSpline *itr = list; while( itr->l != l || itr->m != m ){ itr = itr->next; if( !itr ) return NULL; } return itr; /* The element returned is itself a pointer to a ListmodesCAmpPhaseSpline */ } void ListmodesCAmpPhaseSpline_Destroy( ListmodesCAmpPhaseSpline* list /* List structure to destroy; notice that the data is destroyed too */ ) { ListmodesCAmpPhaseSpline* pop; while( (pop = list) ){ if( pop->splines ){ /* Destroying the CAmpPhaseSpline data */ CAmpPhaseSpline_Cleanup( pop->splines ); } /* Notice that the mode indices l and m are not freed, like in SphHarmTimeSeries struct indices l and m */ list = pop->next; free( pop ); } } /***********************************************************************/ /**************** I/O functions for internal structures ****************/ /* Read waveform Real time series */ int Read_RealTimeSeries(RealTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary) { /* Initalize and read input */ int ret; gsl_matrix* inmatrix = gsl_matrix_alloc(nblines, 2); if(!binary) ret = Read_Text_Matrix(dir, file, inmatrix); else ret = Read_Matrix(dir, file, inmatrix); /* Initialize structures */ RealTimeSeries_Init(timeseries, nblines); /* Set values */ gsl_vector_view timesview = gsl_matrix_column(inmatrix, 0); gsl_vector_view hview = gsl_matrix_column(inmatrix, 1); gsl_vector_memcpy((*timeseries)->times, &timesview.vector); gsl_vector_memcpy((*timeseries)->h, &hview.vector); /* Clean up */ gsl_matrix_free(inmatrix); return ret; } /* Read waveform Amp/Phase time series */ int Read_AmpPhaseTimeSeries(AmpPhaseTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary) { /* Initalize and read input */ int ret; gsl_matrix* inmatrix = gsl_matrix_alloc(nblines, 3); if(!binary) ret = Read_Text_Matrix(dir, file, inmatrix); else ret = Read_Matrix(dir, file, inmatrix); /* Initialize structures */ AmpPhaseTimeSeries_Init(timeseries, nblines); /* Set values */ gsl_vector_view timesview = gsl_matrix_column(inmatrix, 0); gsl_vector_view hampview = gsl_matrix_column(inmatrix, 1); gsl_vector_view hphaseview = gsl_matrix_column(inmatrix, 2); gsl_vector_memcpy((*timeseries)->times, &timesview.vector); gsl_vector_memcpy((*timeseries)->h_amp, &hampview.vector); gsl_vector_memcpy((*timeseries)->h_phase, &hphaseview.vector); /* Clean up */ gsl_matrix_free(inmatrix); return ret; } /* Read waveform Re/Im time series */ int Read_ReImTimeSeries(ReImTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary) { /* Initalize and read input */ int ret; gsl_matrix* inmatrix = gsl_matrix_alloc(nblines, 3); if(!binary) ret = Read_Text_Matrix(dir, file, inmatrix); else ret = Read_Matrix(dir, file, inmatrix); /* Initialize structures */ ReImTimeSeries_Init(timeseries, nblines); /* Set values */ gsl_vector_view timesview = gsl_matrix_column(inmatrix, 0); gsl_vector_view hrealview = gsl_matrix_column(inmatrix, 1); gsl_vector_view himagview = gsl_matrix_column(inmatrix, 2); gsl_vector_memcpy((*timeseries)->times, &timesview.vector); gsl_vector_memcpy((*timeseries)->h_real, &hrealview.vector); gsl_vector_memcpy((*timeseries)->h_imag, &himagview.vector); /* Clean up */ gsl_matrix_free(inmatrix); return ret; } /* Output Re/Im frequency series */ int Write_ReImFrequencySeries(const char dir[], const char file[], ReImFrequencySeries* freqseries, const int binary) { /* Initialize output */ /* Note: assumes hplus, hcross have same length as expected */ int nbfreq = freqseries->freq->size; gsl_matrix* outmatrix = gsl_matrix_alloc(nbfreq, 3); /* Set output matrix */ gsl_matrix_set_col(outmatrix, 0, freqseries->freq); gsl_matrix_set_col(outmatrix, 1, freqseries->h_real); gsl_matrix_set_col(outmatrix, 2, freqseries->h_imag); /* Output */ int ret; if (!binary) ret = Write_Text_Matrix(dir, file, outmatrix); else ret = Write_Matrix(dir, file, outmatrix); return ret; } /* Output real time series */ int Write_RealTimeSeries(const char dir[], const char file[], RealTimeSeries* timeseries, int binary) { /* Initialize output */ int nbtimes = timeseries->times->size; gsl_matrix* outmatrix = gsl_matrix_alloc(nbtimes, 2); /* Set data */ gsl_matrix_set_col(outmatrix, 0, timeseries->times); gsl_matrix_set_col(outmatrix, 1, timeseries->h); /* Output */ int ret; if(!binary) ret = Write_Text_Matrix(dir, file, outmatrix); else ret = Write_Matrix(dir, file, outmatrix); return ret; } /* Output Amp/Phase time series */ int Write_AmpPhaseTimeSeries(const char dir[], const char file[], AmpPhaseTimeSeries* timeseries, int binary) { /* Initialize output */ int nbtimes = timeseries->times->size; gsl_matrix* outmatrix = gsl_matrix_alloc(nbtimes, 3); /* Set data */ gsl_matrix_set_col(outmatrix, 0, timeseries->times); gsl_matrix_set_col(outmatrix, 1, timeseries->h_amp); gsl_matrix_set_col(outmatrix, 2, timeseries->h_phase); /* Output */ int ret; if(!binary) ret = Write_Text_Matrix(dir, file, outmatrix); else ret = Write_Matrix(dir, file, outmatrix); return ret; } /* Output Re/Im time series */ int Write_ReImTimeSeries(const char dir[], const char file[], ReImTimeSeries* timeseries, int binary) { /* Initialize output */ int nbtimes = timeseries->times->size; gsl_matrix* outmatrix = gsl_matrix_alloc(nbtimes, 3); /* Set data */ gsl_matrix_set_col(outmatrix, 0, timeseries->times); gsl_matrix_set_col(outmatrix, 1, timeseries->h_real); gsl_matrix_set_col(outmatrix, 2, timeseries->h_imag); /* Output */ int ret; if(!binary) ret = Write_Text_Matrix(dir, file, outmatrix); else ret = Write_Matrix(dir, file, outmatrix); return ret; }
{ "alphanum_fraction": 0.6835128043, "avg_line_length": 33.0868263473, "ext": "c", "hexsha": "c7ada6c74937a020e68bf69785c32ff6be36c170", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "tools/struct.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_path": "tools/struct.c", "max_line_length": 134, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "tools/struct.c", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 5959, "size": 22102 }
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 1999-2009 Soeren Sonnenburg * Written (W) 1999-2008 Gunnar Raetsch * Written (W) 2006-2007 Mikio L. Braun * Written (W) 2008 Jochen Garcke * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #ifndef _LAPACK_H__ #define _LAPACK_H__ #include <shogun/lib/config.h> #include <shogun/lib/common.h> #ifdef HAVE_LAPACK extern "C" { #ifdef HAVE_MKL #include <mkl_cblas.h> #include <mkl_lapack.h> #elif defined(HAVE_MVEC) //FIXME: Accelerate framework's vForce.h forward declares // std::complex<> classes that causes major errors // in c++11 mode and Eigen3 // this define basically disables the include of vForce.h #ifdef HAVE_CXX11 #define __VFORCE_H 1 #endif #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #ifdef HAVE_ACML #include <acml.h> #endif #ifdef HAVE_ATLAS #include <clapack.h> #else // ACML and MKL do not provide clapack_* routines // double precision int clapack_dpotrf(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, double *A, const int lda); int clapack_dposv(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, const int NRHS, double *A, const int lda, double *B, const int ldb); int clapack_dpotri(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, double *A, const int LDA); int clapack_dpotrs(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, const int NRHS, double *A, const int lda, double *B, const int ldb); int clapack_dgetrf(const CBLAS_ORDER Order, const int M, const int N, double *A, const int lda, int *ipiv); int clapack_dgetri(const CBLAS_ORDER Order, const int N, double *A, const int lda, int *ipiv); int clapack_dgetrs(const CBLAS_ORDER Order, const CBLAS_TRANSPOSE Transpose, const int N, const int NRHS, double *A, const int lda, int *ipiv, double *B, const int ldb); #endif namespace shogun { #ifndef DOXYGEN_SHOULD_SKIP_THIS // double precision void wrap_dsyev(char jobz, char uplo, int n, double *a, int lda, double *w, int *info); void wrap_dgesvd(char jobu, char jobvt, int m, int n, double *a, int lda, double *sing, double *u, int ldu, double *vt, int ldvt, int *info); void wrap_dgeqrf(int m, int n, double *a, int lda, double *tau, int *info); void wrap_dorgqr(int m, int n, int k, double *a, int lda, double *tau, int *info); void wrap_dsyevr(char jobz, char uplo, int n, double *a, int lda, int il, int iu, double *eigenvalues, double *eigenvectors, int *info); void wrap_dsygvx(int itype, char jobz, char uplo, int n, double *a, int lda, double *b, int ldb, int il, int iu, double *eigenvalues, double *eigenvectors, int *info); void wrap_dstemr(char jobz, char range, int n, double* d__, double *e, double vl, double vu, int il, int iu, int* m, double* w, double* z__, int ldz, int nzc, int *isuppz, int tryrac, int *info); #endif } // only MKL, ACML and Mac OS vector library provide a header file for the lapack routines #if !defined(HAVE_ACML) && !defined(HAVE_MKL) && !defined(HAVE_MVEC) // double precision int dsyev_(char*, char*, int*, double*, int*, double*, double*, int*, int*); int dgesvd_(char* jobu, char* jobvt, int* m, int* n, double* a, int* lda, double* s, double* u, int* ldu, double* vt, int* ldvt, double* work, int* lwork, int* info); int dposv_(const char *uplo, const int *n, const int *nrhs, double *a, const int *lda, double *b, const int *ldb, int *info); int dpotrf_(const char *uplo, int *n, double *a, int * lda, int *info); int dpotri_(const char *uplo, int *n, double *a, int * lda, int *info); int dgetri_(int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info); int dgetrf_(int *m, int *n, double *a, int *lda, int *ipiv, int *info); int dgeqrf_(int*, int*, double*, int*, double*, double*, int*, int*); int dorgqr_(int*, int*, int*, double*, int*, double*, double*, int*, int*); int dsyevr_(const char*, const char*, const char*, int*, double*, int*, double*, double*, int*, int*, double*, int*, double*, double*, int*, int*, double*, int*, int*, int*, int*); int dgetrs_(const char*, int*, int*, double*, int*, int*, double*, int*, int*); int dpotrs_(const char*, int*, int*, double*, int*, double*, int*, int*); int dsygvx_(int*, const char*, const char*, const char*, int*, double*, int*, double*, int*, double* , double*, int*, int*, double*, int*, double*, double*, int*, double*, int*, int*, int*, int*); int dstemr_(char*, char*, int*, double*, double*, double*, double*, int*, int*, int*, double*, double*, int*, int*, int*, int*, double*, int*, int*, int*, int*); #endif } #endif //HAVE_LAPACK #endif //_LAPACK_H__
{ "alphanum_fraction": 0.6741684923, "avg_line_length": 42.1932773109, "ext": "h", "hexsha": "ca42a6c28c52cc9fddcc67123e506d6a2287f65c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "9288b6fa38e001d63c32188f7f847dadea66e2ae", "max_forks_repo_licenses": [ "Ruby", "MIT" ], "max_forks_repo_name": "waderly/shogun", "max_forks_repo_path": "src/shogun/mathematics/lapack.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9288b6fa38e001d63c32188f7f847dadea66e2ae", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Ruby", "MIT" ], "max_issues_repo_name": "waderly/shogun", "max_issues_repo_path": "src/shogun/mathematics/lapack.h", "max_line_length": 125, "max_stars_count": 1, "max_stars_repo_head_hexsha": "33c04f77a642416376521b0cd1eed29b3256ac13", "max_stars_repo_licenses": [ "Ruby", "MIT" ], "max_stars_repo_name": "srgnuclear/shogun", "max_stars_repo_path": "src/shogun/mathematics/lapack.h", "max_stars_repo_stars_event_max_datetime": "2015-11-05T18:31:14.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-05T18:31:14.000Z", "num_tokens": 1557, "size": 5021 }
/* Copyright (c) 2011-2012, Jérémy Fix. All rights reserved. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions are met: */ /* * Redistributions of source code must retain the above copyright notice, */ /* this list of conditions and the following disclaimer. */ /* * 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. */ /* * None of 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 AUTHOR 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 EKF_H #define EKF_H #include "ekf_types.h" #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> namespace ekf { void ekf_init(ekf_param &p, ekf_state &s) { // Matrices for the state s.xk = gsl_vector_alloc(p.n); gsl_vector_set_zero(s.xk); s.xkm = gsl_vector_alloc(p.n); gsl_vector_set_zero(s.xkm); s.Pxk = gsl_matrix_alloc(p.n, p.n); gsl_matrix_set_zero(s.Pxk); s.Fxk = gsl_matrix_alloc(p.n, p.n); gsl_matrix_set_zero(s.Fxk); s.Rv = gsl_matrix_alloc(p.n, p.n); gsl_matrix_set_zero(s.Rv); // Matrices for the observations s.yk = gsl_vector_alloc(p.no); gsl_vector_set_zero(s.yk); s.ino_yk = gsl_vector_alloc(p.no); gsl_vector_set_zero(s.ino_yk); s.Hyk = gsl_matrix_alloc(p.no, p.n); gsl_matrix_set_zero(s.Hyk); s.Rn = gsl_matrix_alloc(p.no, p.no); gsl_matrix_set_zero(s.Rn); // Matrices for the kalman gain and the updates s.Kk = gsl_matrix_alloc(p.n, p.no); gsl_matrix_set_zero(s.Kk); // Temporary matrices s.temp_n_n = gsl_matrix_alloc(p.n, p.n); gsl_matrix_set_zero(s.temp_n_n); s.temp_n_1 = gsl_matrix_alloc(p.n, 1); gsl_matrix_set_zero(s.temp_n_1); s.temp_no_no = gsl_matrix_alloc(p.no, p.no); gsl_matrix_set_zero(s.temp_no_no); s.temp_n_no = gsl_matrix_alloc(p.n, p.no); gsl_matrix_set_zero(s.temp_n_no); s.temp_2_n_n = gsl_matrix_alloc(p.n, p.n); gsl_matrix_set_zero(s.temp_2_n_n); s.temp_no = gsl_vector_alloc(p.no); gsl_vector_set_zero(s.temp_no); // Initialize the noises //gsl_matrix_set_identity(s.Rv); //gsl_matrix_scale(s.Rv, p.evolution_noise); p.evolution_noise->init(p, s); //printf("Evolution noise : max = %e , min = %e \n", gsl_matrix_max(s.Rv), gsl_matrix_min(s.Rv)); gsl_matrix_set_identity(s.Rn); gsl_matrix_scale(s.Rn, p.observation_noise); // Initialize the covariance of the parameters gsl_matrix_set_identity(s.Pxk); gsl_matrix_scale(s.Pxk, p.prior_pk); } void ekf_free(ekf_param &p, ekf_state &s) { gsl_vector_free(s.xk); gsl_vector_free(s.xkm); gsl_matrix_free(s.Pxk); gsl_matrix_free(s.Fxk); gsl_matrix_free(s.Rv); gsl_vector_free(s.yk); gsl_vector_free(s.ino_yk); gsl_matrix_free(s.Hyk); gsl_matrix_free(s.Rn); gsl_matrix_free(s.Kk); gsl_matrix_free(s.temp_n_n); gsl_matrix_free(s.temp_n_1); gsl_matrix_free(s.temp_no_no); gsl_matrix_free(s.temp_n_no); gsl_matrix_free(s.temp_2_n_n); gsl_vector_free(s.temp_no); } template<typename FFunc, typename DFFunc, typename HFunc, typename DHFunc> void ekf_iterate(ekf_param &p, ekf_state &s, FFunc f, DFFunc df, HFunc h, DHFunc dh, gsl_vector* yk) { /****************************/ /***** Prediction step *****/ /****************************/ // Compute the Jacobian of the evolution // Eq. 2.34 df(s.params, s.xk, s.Fxk); // Compute the predicted state mean and covariance // Eq. 2.36 // s.xk will now hold the predicted state ! f(s.params, s.xk, s.xkm); // Eq. 2.37 // s.Pxk will now hold Pxk^- gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, s.Pxk, s.Fxk, 0.0, s.temp_n_n); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Fxk, s.temp_n_n, 0.0, s.Pxk); gsl_matrix_add(s.Pxk, s.Rv); /****************************/ /***** Correction step *****/ /****************************/ // Compute the Jacobian of the observation model // Eq. 2.38 dh(s.params, s.xkm, s.Hyk); if(!p.observation_gradient_is_diagonal) { // Update the estimates // Eq 2.40 // 1 - Compute H.P^-.H^T + Rn gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, s.Pxk, s.Hyk, 0.0, s.temp_n_no); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Hyk, s.temp_n_no, 0.0, s.temp_no_no); gsl_matrix_add(s.temp_no_no, s.Rn); // 2 - Compute its inverse gsl_linalg_cholesky_decomp(s.temp_no_no); gsl_linalg_cholesky_invert(s.temp_no_no); // 3 - Compute P^-.H ^T.( H P H^T + R)^-1 gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, s.Hyk, s.temp_no_no, 0.0, s.temp_n_no); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Pxk, s.temp_n_no, 0.0, s.Kk); } else { // We can make some simplifications when computing H P H^T = H P H // and also when computing P . H . (H P H^T + R) ^-1 // Update the estimates // Eq 2.40 // 1 - Compute H.P^-.H^T + Rn for(int i = 0 ; i < p.no ; ++i) { for(int j = 0 ; j < p.no ; ++j) { gsl_matrix_set(s.temp_no_no, i, j, gsl_matrix_get(s.Hyk, i, i) * gsl_matrix_get(s.Hyk, j, j) * gsl_matrix_get(s.Pxk, i, j) + gsl_matrix_get(s.Rn, i, j)); } } // Compute its inverse : U = (H P H^T + R) ^-1 gsl_linalg_cholesky_decomp(s.temp_no_no); gsl_linalg_cholesky_invert(s.temp_no_no); // 3 - Compute P^- H^T . U // Compute H^T . U for(int i = 0 ; i < p.no; ++i) for(int j = 0 ; j < p.no ; ++j) gsl_matrix_set(s.temp_n_no, i, j, gsl_matrix_get(s.Hyk, i,i) * gsl_matrix_get(s.temp_no_no, i, j)); for(int i = p.no ; i < p.n; ++i) for(int j = 0 ; j < p.no ; ++j) gsl_matrix_set(s.temp_n_no, i, j, 0.0); // Compute P^- . (H^T . U) gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Pxk, s.temp_n_no, 0.0, s.Kk); } // Update the current estimate // Eq 2.41 // 1 - We need the observations h(s.params, s.xkm, s.yk); gsl_vector_memcpy(s.ino_yk, yk); gsl_vector_sub(s.ino_yk, s.yk); gsl_vector_memcpy(s.xk, s.xkm); gsl_blas_dgemv(CblasNoTrans, 1.0, s.Kk, s.ino_yk, 1.0,s.xk); // Update the variance/covariance matrix // Compute -Kk * Hk if(!p.observation_gradient_is_diagonal) { gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, s.Kk, s.Hyk, 0.0, s.temp_n_n); // Add identity : I - Kk * Hk for(int i = 0 ; i < p.n ; ++i) gsl_matrix_set(s.temp_n_n, i, i,gsl_matrix_get(s.temp_n_n,i,i) + 1.0); } else { // We can make some simplifications when H is diagonal for(int i = 0 ; i < p.n ; ++i) { for(int j = 0 ; j < p.no ; ++j) { gsl_matrix_set(s.temp_n_n, i, j, (i==j?1.0:0.0) - gsl_matrix_get(s.Kk, i,j) * gsl_matrix_get(s.Hyk, j,j) ); } for(int j = p.no ; j < p.n ; ++j) { gsl_matrix_set(s.temp_n_n, i, j, (i == j ? 1.0 : 0.0)); } } } gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.temp_n_n, s.Pxk, 0.0, s.temp_2_n_n); gsl_matrix_memcpy(s.Pxk, s.temp_2_n_n); /***********************************/ /***** Evolution noise update *****/ /***********************************/ p.evolution_noise->updateEvolutionNoise(p, s); } } #endif // EKF_H
{ "alphanum_fraction": 0.6379645373, "avg_line_length": 31.9147286822, "ext": "h", "hexsha": "dbe2e5b2bba39c7b5aed4e3c1306a0086e685fc6", "lang": "C", "max_forks_count": 52, "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_path": "src/ekf.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_path": "src/ekf.h", "max_line_length": 158, "max_stars_count": 101, "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_path": "src/ekf.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "num_tokens": 2622, "size": 8234 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "config.h" #include <cJSON.h> #include <platform/socket.h> #include <gsl/gsl> class NetworkInterface { public: /// Should a protocol be enabled, and if so how? enum class Protocol { Off, /// Do not enable protocol. Optional, /// Protocol should be enabled, failure is non-fatal. Required, /// Protocol must be enabled; failure is fatal. }; NetworkInterface() = default; explicit NetworkInterface(gsl::not_null<const cJSON*> json); std::string host; struct { std::string key; std::string cert; } ssl; int maxconn = 1000; int backlog = 1024; in_port_t port = 11211; Protocol ipv6 = Protocol::Optional; Protocol ipv4 = Protocol::Optional; bool tcp_nodelay = true; bool management = false; }; std::string to_string(const NetworkInterface::Protocol& proto);
{ "alphanum_fraction": 0.6689829438, "avg_line_length": 29.8679245283, "ext": "h", "hexsha": "05e0411383881b8282af0918397910182a445689", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "t3rm1n4l/kv_engine", "max_forks_repo_path": "daemon/network_interface.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "t3rm1n4l/kv_engine", "max_issues_repo_path": "daemon/network_interface.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "t3rm1n4l/kv_engine", "max_stars_repo_path": "daemon/network_interface.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 377, "size": 1583 }
/** * Various binning and weighting routines for aperture pixel tables. * */ #include <math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "spc_trace_functions.h" #include "aXe_utils.h" #include "aXe_grism.h" #include "spc_spc.h" #include "spc_driz.h" #include "aper_conf.h" #include "spce_output.h" #include "spc_optimum.h" #define SQR(x) ((x)*(x)) #define MIN(x,y) (((x)<(y))?(x):(y)) #define MAX(x,y) (((x)>(y))?(x):(y)) /* gsl_matrix * create_weightimage(ap_pixel *ap_p, const beam actbeam, const aperture_conf *conf, const double exptime, const double sky_cps) { drzstamp_dim dimension; drzstamp *modvar; gsl_matrix *weights; dimension = get_resample_dims(ap_p, actbeam); if (!dimension.resolution) return get_default_weight(); compute_model_ivar(ap_p, conf->rdnoise, exptime, sky_cps); modvar = compute_modvar(ap_p, actbeam, dimension); weights = comp_allweight(modvar); return weights; } */ /** * Function: compute_modvar * * * Parameters: * @param ap_p - the PET table * @param actbeam - beam to compute the modvar structure for * @param dimension - dimenasion of the images * @param modvar - the structure to fill */ drzstamp * compute_modvar(ap_pixel *ap_p, const beam actbeam, const drzstamp_dim dimension) { ap_pixel *cur_p; ap_pixel *tmp_p; quadrangle quad; double jacob; int jcen, icen; int jupp, iupp; int jlow, ilow; int ii, jj; int stpi, stpj; double maxarr, arr; //int iim, jjm; double value, allweig, weig; double stpc; double totweight; drzstamp *modvar; // allocate memory for the result structure modvar = alloc_drzstamp(dimension); // allocate memory tmp_p = (ap_pixel *) malloc(sizeof(ap_pixel)); // go over each pixel for (cur_p = ap_p; cur_p->p_x != -1; cur_p++) { // Skip this pixel if it was not actually used if (fabs(cur_p->dist)>actbeam.width+0.5) continue; // transfer values to the temporary pixel tmp_p->lambda = cur_p->xi; tmp_p->dist = cur_p->dist; tmp_p->dxs = cur_p->dxs; tmp_p->dlambda = 1.0; // create the quadrangle for the current pixel quad = get_quad_from_pixel(tmp_p, actbeam.orient, dimension); // get the jacobian (well, easy here) // the term "cos(cur_p->dxs)" must be there // to correct the enlargement necessary // to cover the whole lambda-crossdispersion area! // NOT COMPLETELY understood jacob = cos(cur_p->dxs); // get the central pixel (icen, jcen) of the current PET-pixel icen = (int) floor(cur_p->xi - dimension.xstart+.5); jcen = (int) floor(cur_p->dist - dimension.ystart+.5); // get the uper and lower extend of the quadrangle in x iupp = (int)floor(quad.xmax - (double)icen + 0.5)+1; ilow = (int)floor(quad.xmin - (double)icen + 0.5); // get the uper and lower extend of the quadrangle in x jupp = (int)floor(quad.ymax - (double)jcen + 0.5)+1; jlow = (int)floor(quad.ymin - (double)jcen + 0.5); maxarr=0.0; totweight = 0.0; // go over the extend in x for (ii=ilow;ii<iupp;ii++) { // go over the extend in x for (jj=jlow;jj<jupp;jj++) { // get the coordinates of the current output pixel stpi = icen+ii; stpj = jcen+jj; // check whether the current output pixel is within // the stamp image; continue if not if ((stpi>=dimension.xsize)||(stpi<0) ||(stpj>=dimension.ysize)||(stpj<0)) continue; // get the area which falls onto the current output pixel arr = boxer(stpi,stpj,quad.x,quad.y); if (arr > 0.0) { // get the already existing counts and weights stpc = gsl_matrix_get(modvar->counts,stpi,stpj); weig = gsl_matrix_get(modvar->weight,stpi,stpj); // compute the new, total weight of the current output pixel allweig = weig + arr*cur_p->weight; // do a weighted sum of the count value at the current // output pixel value = (stpc*weig + arr*cur_p->model*cur_p->weight*jacob) / (allweig); // store the new count value and the new weight gsl_matrix_set(modvar->counts,stpi,stpj,value); gsl_matrix_set(modvar->weight,stpi,stpj,allweig); } } } } // freep the temporary PET pixel free(tmp_p); // return the result return modvar; } void shift_tracelength(ap_pixel *ap_p, const double xi_shift) { ap_pixel *cur_p; // go over each PET pixel for (cur_p = ap_p; cur_p->p_x != -1; cur_p++) { // apply a shift in trace distance cur_p->xi += xi_shift; } } /** * Function: prepare_inv_variance * The function prepares the inverse model variances * for a data set containing an object and a background PET. * This is done in subroutines which compute the * theoretical inverse pixel variance following * different methods for the object and the background PET. * * Parameters: * @param ap_p - the object PET table * @param bg_p - the background PET table * @param dobck - integer indicating background subtraction * @param conf - the configuration structure * @param exptime - the exposure time * @param sky_cps - the sky background */ void prepare_inv_variance(ap_pixel *ap_p, ap_pixel *bg_p, const int dobck, const aperture_conf *conf, const double exptime, const double sky_cps, const double xi_shift) { if (dobck) { // shift both, the object and the background PET shift_tracelength(ap_p, xi_shift); shift_tracelength(bg_p, xi_shift); // compute the inverse variance for the object + background PET compute_total_ivar(bg_p, bg_p, conf->rdnoise, exptime, sky_cps); } else { // shift both, the object PET shift_tracelength(ap_p, xi_shift); // compute the inverse variance for the object PET compute_object_ivar(ap_p, conf->rdnoise, exptime, sky_cps); } } /** * Function: compute_model_ivar * The function computes for each PET pixel the * associated inverse variance value. The input * for variance and inverse variance are the * model value, the contamination value, the * constant sky background value and the readnoise. * The computed inverse variance value is stored * in the weight entry of the PET. * The function also offers the possibility to * shift the trace distance by a fixed amount. * * Parameters: * @param ap_p - the PET table * @param rdnoise - the readnoise value * @param exptime - the exposure time * @param sky_cps - the sky background * @param xi_shift - shift in trace distance */ void compute_object_ivar(ap_pixel *ap_p, const double rdnoise, const double exptime, const double sky_cps) { double variance; double sqr_rdnoise; double sqr_exptime; ap_pixel *cur_p; // square the readnoise sqr_rdnoise = rdnoise*rdnoise; // square the exposure time sqr_exptime = exptime*exptime; // go over each PET pixel for (cur_p = ap_p; cur_p->p_x != -1; cur_p++) { // compute the variance variance = ((cur_p->model + cur_p->contam + sky_cps) * exptime + sqr_rdnoise) / sqr_exptime; // store the inverse variance cur_p->weight = 1.0/variance; } } /** * Function: compute_value_ivar * The function computes for each PET pixel the * associated inverse variance value. The input * to derive the variance is the count value and * the readnoise. * The computed inverse variance value is stored * in the weight entry of the PET. * The function also offers the possibility to * shift the trace distance by a fixed amount. * * Parameters: * @param ap_p - the PET table * @param rdnoise - the readnoise value * @param exptime - the exposure time * @param sky_cps - the sky background * @param xi_shift - shift in trace distance */ void compute_total_ivar(ap_pixel *ap_p, const ap_pixel *bg_p, const double rdnoise, const double exptime, const double sky_cps) { double variance; double sqr_rdnoise; double sqr_exptime; ap_pixel *cur_p; const ap_pixel *bac_p; // square the readnoise sqr_rdnoise = rdnoise*rdnoise; // square the exposure time sqr_exptime = exptime*exptime; // go over each PET pixel bac_p = bg_p; for (cur_p = ap_p; cur_p->p_x != -1; cur_p++) { // check that the foreground and background // PET element describe the same pixel if (bac_p->x != cur_p->x || bac_p->y != cur_p->y) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PET2SPC: Background PET and Object PET " "have different pixel orders in PET's.\n"); else // compute the variance variance = ((cur_p->count + bac_p->count + sky_cps) * exptime + sqr_rdnoise) / sqr_exptime; // store the inverse variance cur_p->weight = 1.0/variance; // increase the background pointer bac_p++; } } /** * Function: alloc_drzstamp * Allocates memory for a drizzle stamp structure * according the the dimension specified in the input. * * Parameters: * @param dimension - the dimesions to allocate * * Returns: * @return ret - the drizzle stamp image allocated */ drzstamp * alloc_drzstamp(const drzstamp_dim dimension) { drzstamp *ret; gsl_matrix *counts; gsl_matrix *weight; ret = (drzstamp *) malloc(sizeof(drzstamp)); /* Allocate the stamp matrix*/ /* Fill stamp with NaN values */ counts = gsl_matrix_alloc(dimension.xsize,dimension.ysize); // gsl_matrix_set_all(counts, GSL_NAN); gsl_matrix_set_all(counts, 0.0); /* Allocate the weight matrix*/ /* Fill weight with 0.0 values */ weight = gsl_matrix_alloc(dimension.xsize,dimension.ysize); gsl_matrix_set_all(weight, 0.0); // fill the output structure ret->counts = counts; ret->weight = weight; // return the allocated structure return ret; } /** * Function: get_all_dims * The function derives the dimensional information * on the foreground and, if available, on the * background PET. The dimensions are compared, and * in case of inequality an error is thrown. * If the dimensions are equal, one of them is * returned. * * Parameters: * @param ap_p - the table of aperture pixels * @param bg_p - the table of background pixels * @param actbeam - the beam to compute the dimensions for * @param dobck - integer indicating background subtraction * * Returns: * @return ret - the dimension structure */ drzstamp_dim get_all_dims(const ap_pixel *ap_p, const ap_pixel *bg_p, const beam actbeam, const int dobck) { drzstamp_dim ret; drzstamp_dim bck; // get the aperture PET diemnsion ret = get_resample_dims(ap_p, actbeam); if (dobck) { // get the background PET dimension bck = get_resample_dims(bg_p, actbeam); // check whether the two dimensions // are equal, throw an error if not if (ret.resolution != bck.resolution || ret.xstart != bck.xstart || ret.ystart != bck.ystart || ret.xsize != bck.xsize || ret.ysize != bck.ysize) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PET2SPC: Background PET and Object PET " "do not have the same dimension.\n"); } // return one of the dimensional infos return ret; } /** * Function: get_resample_dims * The function parses through a PET table and determines * the dimension of the image in the coordinates * trace distance - cross-dispersion direction. Those * dimensions are stored in a special structure and * returned to the calling routine. * * Parameters: * @param ap_p - the table of aperture pixels * @param actbeam - the beam to compute the dimensions for * * Returns: * @return ret - the dimension structure */ drzstamp_dim get_resample_dims(const ap_pixel *ap_p, const beam actbeam) { drzstamp_dim ret; const ap_pixel *cur_p; int i_xint, i_dist; int imin_xint=0, imin_dist=0; int imax_xint=0, imax_dist=0; int npixel = 0; // immediately return empty PET's if (ap_p==NULL) return get_default_dim(); // set the tmp pixel to the table start cur_p = ap_p; // initialize some relevant numbers // based on the first pixel i_xint = floor(cur_p->xi + 0.5); i_dist = floor(cur_p->dist + 0.5); imin_xint = i_xint; imax_xint = i_xint; imin_dist = i_dist; imax_dist = i_dist; // go over all pixels, check // for new MIN's ans MAX's for (cur_p = ap_p; cur_p->p_x != -1; cur_p++) { // Skip the pixel if it was not actually used if (fabs(cur_p->dist)>actbeam.width+.5) continue; // compute the rounded value in (x,y) i_xint = floor(cur_p->xi + 0.5); i_dist = floor(cur_p->dist + 0.5); // check for extrema in x imin_xint = MIN(imin_xint, i_xint); imax_xint = MAX(imax_xint, i_xint); // check for extrema in y imin_dist = MIN(imin_dist, i_dist); imax_dist = MAX(imax_dist, i_dist); // enhance the pixel counter npixel++; } // in case there were no valid pixels, // return a dummy structure if (!npixel) return get_default_dim(); // fill the structure with the correct values ret.resolution = 1.0; ret.xstart = imin_xint - NSPARE_PIX; ret.ystart = imin_dist - NSPARE_PIX; ret.xsize = imax_xint - imin_xint + 2 * NSPARE_PIX; ret.ysize = imax_dist - imin_dist + 2 * NSPARE_PIX; // return the structure return ret; } /** * Function: get_default_dim * The function creates and returns the default * dimension structure. The dewfault dimension * structure contains a 0.0 in all fields. * * Returns: * @return res - the dimension structure */ drzstamp_dim get_default_dim() { drzstamp_dim ret; // just set everything to zero ret.resolution=0.0; ret.xstart = 0; ret.ystart = 0; ret.xsize = 0; ret.ysize = 0; // return the result return ret; } /** * Function: get_default_modvar * The function computes the default drizzle stamp * structure, which in this case is used for * tha calculation of the resampled variance and * profile image. * * Returns: * @return res - the resulting drzstamp structure */ drzstamp * get_default_modvar() { gsl_matrix *counts; gsl_matrix *weight; drzstamp *res; res = (drzstamp *) malloc(sizeof(drzstamp)); /* Create a dummy stamp image */ counts = gsl_matrix_alloc(10,10); weight = gsl_matrix_alloc(10,10); /* Fill stamp with 0.0 values */ gsl_matrix_set_all(counts, 0.0); gsl_matrix_set_all(weight, 0.0); // fill the output res->counts = counts; res->weight = weight; // return the output return res; } gsl_matrix * get_default_weight() { gsl_matrix *res; res = gsl_matrix_alloc(10,10); gsl_matrix_set_all(res, 0.0); // return the output return res; } /* * Function: comp_opt_weight * The function uses the model map and and the variance * map and computes optimale weigths according to the * Hoorne method. * Pixels outside of the extraction * area are set to 1000.0 * * Parameters: * @param mod_map - the matrix with the model values * @param var_map - the matrix with the variance values * @param ob - the object structure * * Returns: * @return weight - the matrix with the exposure time weights */ gsl_matrix * comp_allweight(drzstamp *modvar) { gsl_matrix *weight; double mod_sum, weight_sum; double contr, norm, allweight; double mod_val; double act_weight=0; //int beamInt = 0; int i, j; // allocate the weight matrix and set the default weight = gsl_matrix_alloc(modvar->counts->size1, modvar->counts->size2); gsl_matrix_set_all(weight, 1000.0); //* go over all columns for (i=0; i < (int)modvar->counts->size1; i++) { mod_sum = 0.0; contr = 0.0; allweight = 0.0; weight_sum=0.0; // determine for each column the total model counts // and the number of pixels with non-zero model_counts for (j=0; j < (int)modvar->counts->size2; j++) { mod_sum = mod_sum + gsl_matrix_get(modvar->counts, i, j); contr = contr + 1.0; } // check whether the column has model values. // normalize the model values and compute // optimal weights if yes. if (mod_sum > 0.0) { //* determine the mean model value // norm = mod_sum / contr; norm = mod_sum; // go over each row for (j=0; j < (int)modvar->counts->size2; j++) { // normalize the model counts mod_val = gsl_matrix_get(modvar->counts, i, j)/norm; // store the normalized model counts gsl_matrix_set(modvar->counts, i, j, mod_val); // add up the normalization value for the optimal weights weight_sum = weight_sum + mod_val*mod_val*gsl_matrix_get(modvar->weight, i, j); } // finally compute and write the weights: // go over each pixel for (j=0; j < (int)modvar->counts->size2; j++) { if (gsl_matrix_get(modvar->counts, i, j) > 0.0 ) { // compute and set the individual pixel weight act_weight = gsl_matrix_get(modvar->counts,i,j) *gsl_matrix_get(modvar->weight,i,j)/weight_sum; // gsl_matrix_set(weight,i,j,gsl_matrix_get(modvar->counts,i,j) // *gsl_matrix_get(modvar->weight,i,j)/weight_sum); gsl_matrix_set(weight, i, j, act_weight); allweight = allweight + gsl_matrix_get(weight, i, j); } else { // set the default value if no model value is zero gsl_matrix_set(weight, i, j,0.0); } } } // if the column does not have model values at all: else { // go over each row for (j=0; j < (int)modvar->counts->size2; j++) { // set the inside default value gsl_matrix_set(weight, i,j,1.0); allweight = allweight + gsl_matrix_get(modvar->counts, i, j); } } } // return the weight matrix return weight; }
{ "alphanum_fraction": 0.6643061878, "avg_line_length": 25.824383164, "ext": "c", "hexsha": "0e52925f417ac4e7db28d55b77bf3ce4ef26b283", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/spc_optimum.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/spc_optimum.c", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/spc_optimum.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5037, "size": 17793 }
#include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #ifndef JROBINSON_H #define JROBINSON_H #define JROBINSON_EPS (0.0000001) int jrobinson( const gsl_matrix *A, double epsilon, gsl_vector *p1, gsl_vector *p2, int &iter ); #endif
{ "alphanum_fraction": 0.756302521, "avg_line_length": 19.8333333333, "ext": "h", "hexsha": "2744b3e2c6a72401d71729d79390a49bb1a369d6", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2021-05-16T10:15:49.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-31T13:01:28.000Z", "max_forks_repo_head_hexsha": "96616b40f4173959b127011c76f3e649688e1a99", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AaronTrip/hog2", "max_forks_repo_path": "apps/coprobber/JRobinson.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "96616b40f4173959b127011c76f3e649688e1a99", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "AaronTrip/hog2", "max_issues_repo_path": "apps/coprobber/JRobinson.h", "max_line_length": 96, "max_stars_count": 5, "max_stars_repo_head_hexsha": "96616b40f4173959b127011c76f3e649688e1a99", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AaronTrip/hog2", "max_stars_repo_path": "apps/coprobber/JRobinson.h", "max_stars_repo_stars_event_max_datetime": "2022-01-11T08:28:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-03T09:43:26.000Z", "num_tokens": 78, "size": 238 }
#include <math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> #include "klp_matrix_initializers.h" #include "klp_matrix_functions.h" #include "shared/constants.h" TRANSITION_MATRIX transpose_matrix(TRANSITION_MATRIX matrix) { int i, j; TRANSITION_MATRIX transposed_matrix = init_transition_matrix(matrix.row_length, matrix.type); for (i = 0; i < matrix.row_length; ++i) { for (j = 0; j < matrix.row_length; ++j) { T_COL_ORDER(transposed_matrix, i, j) = T_ROW_ORDER(matrix, i, j); } } free_transition_matrix(matrix); return transposed_matrix; } TRANSITION_MATRIX inverse(TRANSITION_MATRIX transition_matrix) { int i, j, signum; gsl_matrix* matrix_to_invert = gsl_matrix_alloc(transition_matrix.row_length, transition_matrix.row_length); gsl_matrix* inversion_matrix = gsl_matrix_alloc(transition_matrix.row_length, transition_matrix.row_length); gsl_permutation* permutation = gsl_permutation_alloc(transition_matrix.row_length); for (i = 0; i < transition_matrix.row_length; ++i) { for (j = 0; j < transition_matrix.row_length; ++j) { gsl_matrix_set(matrix_to_invert, i, j, T_ROW_ORDER(transition_matrix, i, j)); } } gsl_linalg_LU_decomp(matrix_to_invert, permutation, &signum); gsl_linalg_LU_invert(matrix_to_invert, permutation, inversion_matrix); for (i = 0; i < transition_matrix.row_length; ++i) { for (j = 0; j < transition_matrix.row_length; ++j) { T_ROW_ORDER(transition_matrix, i, j) = gsl_matrix_get(inversion_matrix, i, j); } } gsl_matrix_free(matrix_to_invert); gsl_matrix_free(inversion_matrix); gsl_permutation_free(permutation); return transition_matrix; } TRANSITION_MATRIX convert_klp_matrix_to_transition_matrix(KLP_MATRIX* klp_matrix, KLP_PARAMS* klp_params) { int resolved; double* number_of_adjacent_moves; transition_probability probability_function = NULL; resolved = find_start_and_end_positions_in_klp_matrix(klp_matrix, klp_params); if (klp_params->max_dist) { if (!klp_params->bp_dist) { set_bp_dist_from_start_and_end_positions(*klp_matrix, klp_params, resolved); } extend_klp_matrix_to_all_possible_positions(klp_matrix, *klp_params); populate_remaining_probabilities_in_klp_matrix(klp_matrix, *klp_params); if (resolved != 2) { find_start_and_end_positions_in_klp_matrix(klp_matrix, klp_params); } } number_of_adjacent_moves = populate_number_of_adjacent_moves(*klp_matrix, *klp_params); #ifdef DEBUG int i; printf("\nFull dataset:\n"); for (i = 0; i < klp_matrix->length; ++i) { printf("%d\t%d\t%f\t%d possible move(s)\n", klp_matrix->k[i], klp_matrix->l[i], klp_matrix->p[i], (int)number_of_adjacent_moves[i]); } printf("\n"); #endif switch (10 * klp_params->hastings + klp_params->energy_based) { case 0: probability_function = &transition_rate_from_probabilities; #ifdef DEBUG printf("probability_function: transition_rate_from_probabilities\n"); #endif break; case 1: probability_function = &transition_rate_from_energies; #ifdef DEBUG printf("probability_function: transition_rate_from_energies\n"); #endif break; case 10: probability_function = &transition_rate_from_probabilities_with_hastings; #ifdef DEBUG printf("probability_function: transition_rate_from_probabilities_with_hastings\n"); #endif break; case 11: probability_function = &transition_rate_from_energies_with_hastings; #ifdef DEBUG printf("probability_function: transition_rate_from_energies_with_hastings\n"); #endif break; } return populate_transition_matrix_from_stationary_matrix(*klp_matrix, *klp_params, number_of_adjacent_moves, probability_function); } int find_start_and_end_positions_in_klp_matrix(KLP_MATRIX* klp_matrix, KLP_PARAMS* klp_params) { int i, resolved = 0; if (klp_params->start_state == -1) { for (i = 0; i < klp_matrix->length && klp_params->start_state == -1; ++i) { if (klp_matrix->k[i] == 0) { klp_params->start_state = i; resolved++; } } } else { resolved++; } if (klp_params->end_state == -1) { for (i = 0; i < klp_matrix->length && klp_params->end_state == -1; ++i) { if (klp_matrix->l[i] == 0) { klp_params->end_state = i; resolved++; } } } else { resolved++; } #ifdef DEBUG printf("\nstart_index:\t%d\n", klp_params->start_state); printf("end_index:\t%d\n", klp_params->end_state); printf("resolved:\t%d\n", resolved); #endif return resolved; } void set_bp_dist_from_start_and_end_positions(const KLP_MATRIX klp_matrix, KLP_PARAMS* klp_params, int resolved) { int distance_from_start, distance_from_end; distance_from_start = distance_from_end = -1; if (klp_params->start_state > 0) { distance_from_start = klp_matrix.l[klp_params->start_state]; } if (klp_params->end_state > 0) { distance_from_end = klp_matrix.k[klp_params->end_state]; } if (distance_from_start == distance_from_end && resolved) { klp_params->bp_dist = distance_from_start; } else if (distance_from_start >= 0 && distance_from_end == -1) { klp_params->bp_dist = distance_from_start; } else if (distance_from_end >= 0 && distance_from_start == -1) { klp_params->bp_dist = distance_from_end; } else { fprintf(stderr, "Can't infer the input structure distances for the energy grid. We found (0, %d) and (%d, 0). Consider using the -d flag to manually set the base pair distance between the two structures.\n", distance_from_end, distance_from_start); printf("-3\n"); exit(0); } #ifdef DEBUG printf("bp_dist:\t%d\n", klp_params->bp_dist); #endif } void extend_klp_matrix_to_all_possible_positions(KLP_MATRIX* klp_matrix, const KLP_PARAMS klp_params) { int i, j, m, position_in_input_data, pointer, valid_positions = 0; #ifdef DEBUG printf("\nAccessible positions (top-left is [0, 0]):\n"); #endif for (i = 0; i <= klp_params.max_dist; ++i) { for (j = 0; j <= klp_params.max_dist; ++j) { if ( i + j >= klp_params.bp_dist && i + klp_params.bp_dist >= j && j + klp_params.bp_dist >= i && (i + j) % 2 == klp_params.bp_dist % 2 ) { #ifdef DEBUG position_in_input_data = -1; for (m = 0; m < klp_matrix->length && position_in_input_data == -1; ++m) { if (klp_matrix->k[m] == i && klp_matrix->l[m] == j) { position_in_input_data = m; } } printf(position_in_input_data == -1 ? "X" : "O"); #endif valid_positions++; } else { #ifdef DEBUG printf(" "); #endif } } #ifdef DEBUG printf("\n"); #endif } klp_matrix->k = realloc(klp_matrix->k, valid_positions * sizeof(int)); klp_matrix->l = realloc(klp_matrix->l, valid_positions * sizeof(int)); klp_matrix->p = realloc(klp_matrix->p, valid_positions * sizeof(double)); pointer = klp_matrix->length; #ifdef DEBUG printf("\nInput dataset:\n"); for (i = 0; i < klp_matrix->length; ++i) { printf("%d\t%d\t%d\t%f\n", i, klp_matrix->k[i], klp_matrix->l[i], klp_matrix->p[i]); } #endif for (i = 0; i <= klp_params.max_dist; ++i) { for (j = 0; j <= klp_params.max_dist; ++j) { if ( i + j >= klp_params.bp_dist && i + klp_params.bp_dist >= j && j + klp_params.bp_dist >= i && (i + j) % 2 == klp_params.bp_dist % 2 ) { position_in_input_data = -1; for (m = 0; m < klp_matrix->length && position_in_input_data == -1; ++m) { if (klp_matrix->k[m] == i && klp_matrix->l[m] == j) { position_in_input_data = m; } } if (position_in_input_data < 0) { klp_matrix->k[pointer] = i; klp_matrix->l[pointer] = j; klp_matrix->p[pointer] = 0.; pointer++; } } } } klp_matrix->length = valid_positions; } void populate_remaining_probabilities_in_klp_matrix(KLP_MATRIX* klp_matrix, const KLP_PARAMS klp_params) { int i; double epsilon_per_cell; if (klp_params.epsilon) { // Extend the energy grid by adding an epsilon value to all 0-probability positions. epsilon_per_cell = klp_params.epsilon / klp_matrix->length; for (i = 0; i < klp_matrix->length; ++i) { if (klp_matrix->p[i] > 0) { klp_matrix->p[i] = (klp_matrix->p[i] + epsilon_per_cell) / (1. + klp_params.epsilon); } else { klp_matrix->p[i] = epsilon_per_cell / (1. + klp_params.epsilon); } } } } double* populate_number_of_adjacent_moves(const KLP_MATRIX klp_matrix, const KLP_PARAMS klp_params) { int i; double* number_of_adjacent_moves; number_of_adjacent_moves = malloc(klp_matrix.length * sizeof(double)); for (i = 0; i < klp_matrix.length; ++i) { number_of_adjacent_moves[i] = RUN_TYPE(klp_params.run_type, DIAG_MOVES_ONLY_FLAG) ? (double)number_of_permissible_single_bp_moves(klp_matrix, i) : (double)(klp_matrix.length - 1); } return number_of_adjacent_moves; } int number_of_permissible_single_bp_moves(const KLP_MATRIX klp_matrix, int i) { int j, x, y, a, b, num_moves = 0; x = klp_matrix.k[i]; y = klp_matrix.l[i]; for (j = 0; j < klp_matrix.length; ++j) { a = klp_matrix.k[j]; b = klp_matrix.l[j]; if ( // Because N(x, y) is restricted to entries in *k and *l, we *assume* the input data satisfies the triangle inequality and bounds. (int)abs(x - a) == 1 && (int)abs(y - b) == 1 ) { num_moves++; } } return num_moves; } TRANSITION_MATRIX populate_transition_matrix_from_stationary_matrix(const KLP_MATRIX klp_matrix, const KLP_PARAMS klp_params, const double* number_of_adjacent_moves, transition_probability probability_function) { int i, j; double row_sum; TRANSITION_MATRIX transition_matrix; transition_matrix = init_transition_matrix(klp_matrix.length, MATRIX_TYPE(klp_params.rate_matrix)); for (i = 0; i < transition_matrix.row_length; ++i) { row_sum = 0.; for (j = 0; j < transition_matrix.row_length; ++j) { if (i != j) { if (RUN_TYPE(klp_params.run_type, FULLY_CONNECTED_FLAG) || (RUN_TYPE(klp_params.run_type, DIAG_MOVES_ONLY_FLAG) && ONE_BP_MOVE(i, j))) { if (NONZERO_TO_NONZERO_PROB(i, j)) { T_ROW_ORDER(transition_matrix, i, j) = \ probability_function(klp_matrix, number_of_adjacent_moves, i, j, klp_params.rate_matrix); } } row_sum += T_ROW_ORDER(transition_matrix, i, j); } } T_ROW_ORDER(transition_matrix, i, i) = klp_params.rate_matrix ? -row_sum : 1 - row_sum; } return transition_matrix; } double transition_rate_from_probabilities(const KLP_MATRIX klp_matrix, const double* number_of_adjacent_moves, int i, int j, short rate_matrix) { if (rate_matrix) { return MIN(1., klp_matrix.p[j] / klp_matrix.p[i]); } else { return MIN(1., klp_matrix.p[j] / klp_matrix.p[i]) / number_of_adjacent_moves[i]; } } double transition_rate_from_energies(const KLP_MATRIX klp_matrix, const double* number_of_adjacent_moves, int i, int j, short rate_matrix) { if (rate_matrix) { return MIN(1., exp(-(klp_matrix.p[j] - klp_matrix.p[i]) / RT)); } else { return MIN(1., exp(-(klp_matrix.p[j] - klp_matrix.p[i]) / RT)) / number_of_adjacent_moves[i]; } } double transition_rate_from_probabilities_with_hastings(const KLP_MATRIX klp_matrix, const double* number_of_adjacent_moves, int i, int j, short rate_matrix) { if (rate_matrix) { return MIN(1., (number_of_adjacent_moves[i] / number_of_adjacent_moves[j]) * (klp_matrix.p[j] / klp_matrix.p[i])); } else { return MIN(1., (number_of_adjacent_moves[i] / number_of_adjacent_moves[j]) * (klp_matrix.p[j] / klp_matrix.p[i])) / number_of_adjacent_moves[i]; } } double transition_rate_from_energies_with_hastings(const KLP_MATRIX klp_matrix, const double* number_of_adjacent_moves, int i, int j, short rate_matrix) { if (rate_matrix) { return MIN(1., (number_of_adjacent_moves[i] / number_of_adjacent_moves[j]) * exp(-(klp_matrix.p[j] - klp_matrix.p[i]) / RT)); } else { return MIN(1., (number_of_adjacent_moves[i] / number_of_adjacent_moves[j]) * exp(-(klp_matrix.p[j] - klp_matrix.p[i]) / RT)) / number_of_adjacent_moves[i]; } }
{ "alphanum_fraction": 0.6704335978, "avg_line_length": 33.3609625668, "ext": "c", "hexsha": "d969dc181a115622f3aa75e4af053101dc3a68f9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "evansenter/hermes", "max_forks_repo_path": "src/klp_matrix/c/klp_matrix_functions.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "evansenter/hermes", "max_issues_repo_path": "src/klp_matrix/c/klp_matrix_functions.c", "max_line_length": 252, "max_stars_count": null, "max_stars_repo_head_hexsha": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "evansenter/hermes", "max_stars_repo_path": "src/klp_matrix/c/klp_matrix_functions.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3504, "size": 12477 }
#pragma once #include "ui_MaterialVisualizationWidget.h" #include <mitkDataNode.h> #include <vtkDataObject.h> #include <array> #include <gsl.h> namespace mitk { class DataNode; class TransferFunction; } /*! \brief A widget for editing transfer function. */ class MaterialVisualizationWidget : public QWidget { Q_OBJECT public: MaterialVisualizationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = 0); ~MaterialVisualizationWidget(); /*! * \brief Sets the data node whose transfer function is to be edited. * * \param node The data node. * \param dataSet The vtkDataSet stored in the data node (the access may differ for mitk::Surface and mitk::UnstructuredGrid). * \param tfPropertyName Name of the transfer function property used by the renderer. * \param attributeType Type of the attribute to be shown (vtkDataObject::POINT or vtkDataObject::CELL). * \param propertyStorageNode If non-null, the node where to store various transfer functions to be re-used later. If null, the 'node' will be used. */ void setDataNode(mitk::DataNode* node, vtkDataSet* dataSet, gsl::cstring_span<> tfPropertyName, vtkDataObject::AttributeTypes attributeType = vtkDataObject::POINT, mitk::DataNode* propertyStorageNode = nullptr); /*! \brief Resets the data node to null. */ void resetDataNode() { setDataNode(nullptr, nullptr, ""); } /*! \brief Gets data node. */ mitk::DataNode* getDataNode() const { return _node; } private slots: void _setCurrentArray(const QString& arrayName); void _setCurrentComponent(int comboBoxIndex); void _resetTF(); void _setNanColor(QColor c); void _setColorSpace(int colorSpace); void _loadTF(); void _saveTF(); private: void _dataNodeDeleted(); std::string _getCurrentTFPropName(); void _setupDataComboBoxes(); void _setTransferFunction(bool reset = false); static void _setupTFProperties(mitk::TransferFunction* tf, int componentIndex); static void _generateTF(mitk::TransferFunction* tf, const std::array<double, 2>& range); static void _rescaleTF(mitk::TransferFunction* tf, const std::array<double, 2>& range); QColor _getNanColor(); void _addNodeObserver(); void _removeNodeObserver(); mitk::DataNode* _node = nullptr; vtkDataSet* _dataSet = nullptr; std::string _tfPropertyName; vtkDataObject::AttributeTypes _attributeType = vtkDataObject::POINT; mitk::DataNode* _propertyStorageNode = nullptr; Ui::MaterialVisualizationWidget _UI; unsigned long _nodeObserverTag = -1; };
{ "alphanum_fraction": 0.6994780015, "avg_line_length": 36.7397260274, "ext": "h", "hexsha": "d23b6059482cac12463a847355bb5c57f6b3682d", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/MaterialVisualizationWidget.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/MaterialVisualizationWidget.h", "max_line_length": 154, "max_stars_count": 10, "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/MaterialVisualizationWidget.h", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "num_tokens": 640, "size": 2682 }
#include <stdlib.h> #include <math.h> #include <complex.h> #include <fftw3.h> #include <gsl/gsl_sf_result.h> #include <gsl/gsl_sf_gamma.h> #include "ccl.h" /**************************************************************** This is the famous FFTLog. First imlplemented by the living legend Andrew Hamilton: http://casa.colorado.edu/~ajsh/FFTLog/ This version is a C version that was adapted from the C++ version found in Copter JWG Carlson, another big loss for the cosmology community. https://github.com/jwgcarlson/Copter I've transformed this from C++ to C99 as the lowest common denominator and provided bindings for C++ and python. These are the C++ bindings *****************************************************************/ #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_LN2 #define M_LN2 0.69314718056 #endif /* This code is FFTLog, which is described in arXiv:astro-ph/9905191 */ static double complex lngamma_fftlog(double complex z) { gsl_sf_result lnr, phi; gsl_sf_lngamma_complex_e(creal(z), cimag(z), &lnr, &phi); return lnr.val + I*phi.val; } static double complex gamma_fftlog(double complex z) { return cexp(lngamma_fftlog(z)); } static double complex polar (double r, double phi) { return (r*cos(phi) +I*(r*sin(phi))); } static void lngamma_4(double x, double y, double* lnr, double* arg) { double complex w = lngamma_fftlog(x+y*I); if(lnr) *lnr = creal(w); if(arg) *arg = cimag(w); } static double goodkr(int N, double mu, double q, double L, double kr) { double xp = (mu+1+q)/2; double xm = (mu+1-q)/2; double y = M_PI*N/(2*L); double lnr, argm, argp; lngamma_4(xp, y, &lnr, &argp); lngamma_4(xm, y, &lnr, &argm); double arg = log(2/kr) * N/L + (argp + argm)/M_PI; double iarg = round(arg); if(arg != iarg) kr *= exp((arg - iarg)*L/N); return kr; } /* Pre-compute the coefficients that appear in the FFTLog implementation of * the discrete Hankel transform. The parameters N, mu, and q here are the * same as for the function fht(). The parameter L is defined (for whatever * reason) to be N times the logarithmic spacing of the input array, i.e. * L = N * log(r[N-1]/r[0])/(N-1) */ static void compute_u_coefficients(int N, double mu, double q, double L, double kcrc, double complex *u) { double y = M_PI/L; double k0r0 = kcrc * exp(-L); double t = -2*y*log(k0r0/2); if(q == 0) { double x = (mu+1)/2; double lnr, phi; for(int m = 0; m <= N/2; m++) { lngamma_4(x, m*y, &lnr, &phi); u[m] = polar(1.0,m*t + 2*phi); } } else { double xp = (mu+1+q)/2; double xm = (mu+1-q)/2; double lnrp, phip, lnrm, phim; for(int m = 0; m <= N/2; m++) { lngamma_4(xp, m*y, &lnrp, &phip); lngamma_4(xm,-m*y, &lnrm, &phim); u[m] = polar(exp(q*M_LN2 + lnrp - lnrm), m*t + phip - phim); } } for(int m = N/2+1; m < N; m++) u[m] = conj(u[N-m]); if((N % 2) == 0) u[N/2] = (creal(u[N/2]) + I*0.0); } /* Compute the discrete Hankel transform of the function a(r). See the FFTLog * documentation (or the Fortran routine of the same name in the FFTLog * sources) for a description of exactly what this function computes. * If u is NULL, the transform coefficients will be computed anew and discarded * afterwards. If you plan on performing many consecutive transforms, it is * more efficient to pre-compute the u coefficients. */ static void fht(int npk, int N, double *k, double **pk, double *r, double **xi, double dim, double mu, double q, double kcrc, int noring, double complex* u, int *status) { fftw_plan forward_plan, reverse_plan; double L = log(k[N-1]/k[0]) * N/(N-1.); double complex* ulocal = NULL; if(u == NULL) { if(noring) kcrc = goodkr(N, mu, q, L, kcrc); ulocal = malloc (sizeof(complex double)*N); if(ulocal==NULL) *status=CCL_ERROR_MEMORY; if(*status == 0) { compute_u_coefficients(N, mu, q, L, kcrc, ulocal); u = ulocal; } } fftw_complex* a_tmp; fftw_complex* b_tmp; if(*status == 0) { a_tmp = fftw_alloc_complex(N); if(a_tmp==NULL) *status=CCL_ERROR_MEMORY; } if(*status == 0) { b_tmp = fftw_alloc_complex(N); if(b_tmp==NULL) *status=CCL_ERROR_MEMORY; } if(*status == 0) { /* Compute the convolution b = a*u using FFTs */ forward_plan = fftw_plan_dft_1d(N, (fftw_complex*) a_tmp, (fftw_complex*) b_tmp, -1, FFTW_ESTIMATE); reverse_plan = fftw_plan_dft_1d(N, (fftw_complex*) b_tmp, (fftw_complex*) b_tmp, +1, FFTW_ESTIMATE); } if(*status == 0) { #pragma omp parallel default(none) \ shared(npk, N, k, pk, r, xi, \ dim, mu, q, kcrc, u, status, \ forward_plan, reverse_plan, \ L, ulocal) { int local_status = 0; double *prefac_pk=NULL; if(local_status == 0) { prefac_pk = malloc(N*sizeof(double)); if(prefac_pk==NULL) local_status=CCL_ERROR_MEMORY; } double *prefac_xi=NULL; if(local_status == 0) { prefac_xi = malloc(N*sizeof(double)); if(prefac_xi==NULL) local_status=CCL_ERROR_MEMORY; } fftw_complex* a=NULL; fftw_complex* b=NULL; if(local_status == 0) { a = fftw_alloc_complex(N); if(a==NULL) local_status=CCL_ERROR_MEMORY; } if(local_status == 0) { b = fftw_alloc_complex(N); if(b==NULL) local_status=CCL_ERROR_MEMORY; } if(local_status == 0) { for(int i = 0; i < N; i++) prefac_pk[i] = pow(k[i], dim/2-q); /* Compute k's corresponding to input r's */ double k0r0 = kcrc * exp(-L); r[0] = k0r0/k[0]; for(int n = 1; n < N; n++) r[n] = r[0] * exp(n*L/N); double one_over_2pi_dhalf = pow(2*M_PI,-dim/2); for(int i = 0; i < N; i++) prefac_xi[i] = one_over_2pi_dhalf * pow(r[i], -dim/2-q); #pragma omp for for(int j = 0; j < npk; j++) { for(int i = 0; i < N; i++) a[i] = prefac_pk[i] * pk[j][i]; fftw_execute_dft(forward_plan,a,b); for(int m = 0; m < N; m++) b[m] *= u[m] / (double)(N); // divide by N since FFTW doesn't normalize the inverse FFT fftw_execute_dft(reverse_plan,b,b); /* Reverse b array */ double complex tmp; for(int n = 0; n < N/2; n++) { tmp = b[n]; b[n] = b[N-n-1]; b[N-n-1] = tmp; } for(int i = 0; i < N; i++) xi[j][i] = prefac_xi[i] * creal(b[i]); } } free(prefac_pk); free(prefac_xi); fftw_free(a); fftw_free(b); if (local_status) { #pragma omp atomic write *status = local_status; } } //end omp parallel } if(*status == 0) { fftw_destroy_plan(forward_plan); fftw_destroy_plan(reverse_plan); } free(ulocal); //TODO: free this up fftw_free(a_tmp); fftw_free(b_tmp); } void ccl_fftlog_ComputeXi2D(double mu, double epsilon, int npk, int N, double *l,double **cl, double *th, double **xi, int *status) { fht(npk, N, l, cl, th, xi, 2., mu, epsilon, 1, 1, NULL, status); } void ccl_fftlog_ComputeXi3D(double l, double epsilon, int npk, int N, double *k, double **pk, double *r, double **xi, int *status) { fht(npk, N, k, pk, r, xi, 3., l+0.5, epsilon, 1, 1, NULL, status); }
{ "alphanum_fraction": 0.5586073501, "avg_line_length": 27.7956989247, "ext": "c", "hexsha": "8a6e1539917d3b71953c80e36d1372d4fe9678e8", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "timothydmorton/CCL", "max_forks_repo_path": "src/ccl_fftlog.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "timothydmorton/CCL", "max_issues_repo_path": "src/ccl_fftlog.c", "max_line_length": 105, "max_stars_count": null, "max_stars_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "timothydmorton/CCL", "max_stars_repo_path": "src/ccl_fftlog.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2375, "size": 7755 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include<time.h> #include <gsl/gsl_blas.h> double epsl = 0.01; typedef struct { double x, y, z; } position; typedef struct _vertex { position pos; gsl_matrix_view *C; struct _vertex *p,*l,*r; } vertex; void usage(char *exec) { printf("%s -s <input_file> <count_vertex>\n", exec); printf("%s -c <input_file>\n", exec); printf("%s -show <input_file>\n", exec); } int* ddd(char *fileName, int len){ FILE *file = NULL; if ((file = fopen(fileName, "r")) == NULL) { /* error openning the file */ perror("fopen: "); return NULL; } int n, i, j = 0, k = 0; char buff[6], buffFloat[17]; memset(buff, 0, sizeof(buff)); memset(buffFloat, 0, sizeof(buffFloat)); if (fread(buff, sizeof(char), 5, file) < 5 || strcmp(buff, "E = [")) { perror("file out of params: "); return NULL; } double **mat = (double **)calloc(len, sizeof(double *)); for (i = 0; i < len; i++) { mat[i] = (double *)calloc(3, sizeof(double *)); } i = 0; while ((n = fread(buff, sizeof(char), 1, file)) == 1) { if (buff[0] == ' ') { if (k > 0) { mat[i][j] = atof(buffFloat); memset(buffFloat, 0, sizeof(buffFloat)); k = 0; j++; } continue; } else if (buff[0] == ';') { if (k) { mat[i][j] = atof(buffFloat); memset(buffFloat, 0, sizeof(buffFloat)); k = 0; } j = 0; i++; } else { buffFloat[k++] = buff[0]; } } fclose(file); int current = 0; for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { printf(" %f ", sqrt(pow(mat[i][0] - mat[j][0], 2) + pow(mat[i][1] - mat[j][1], 2) + pow(mat[i][2] - mat[j][2], 2))); fflush(stdout); } printf("\n"); } } void printMat(double **mat, int len) { int i, j; for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { //if (mat[i][j] != 0) { printf(" %f ", mat[i][j]); fflush(stdout); //} } printf("\n"); } } double **matrixConstruct(char *fileName, int len){ FILE *file = NULL; if ((file = fopen(fileName, "r")) == NULL) { /* error openning the file */ perror("fopen: "); return NULL; } int n, i, j = 0, k = 0; char buff[6], buffFloat[17]; memset(buff, 0, sizeof(buff)); memset(buffFloat, 0, sizeof(buffFloat)); if (fread(buff, sizeof(char), 5, file) < 5 || strcmp(buff, "E = [")) { perror("file out of params: "); return NULL; } double **mat = (double **)calloc(len, sizeof(double *)); for (i = 0; i < len; i++) { mat[i] = (double *)calloc(len, sizeof(double *)); } i = 0; while ((n = fread(buff, sizeof(char), 1, file)) == 1) { if (buff[0] == ' ') { if (k > 0) { mat[i][j] = atof(buffFloat); memset(buffFloat, 0, sizeof(buffFloat)); k = 0; j++; } continue; } else if (buff[0] == ';') { if (k) { mat[i][j] = atof(buffFloat); memset(buffFloat, 0, sizeof(buffFloat)); k = 0; } j = 0; i++; } else { buffFloat[k++] = buff[0]; } } fclose(file); for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { if(pow(mat[i][j] - mat[j][i],2) > 0.0000001) return NULL; } } return mat; } double dis(double **m, int i){ if (i-1 < 0) return -1; return m[i][i-1]; } double theta(double **m, int i){ if (i-1 < 0) return -1000; return acos((pow(m[i][i+1],2) + pow(m[i][i-1],2) - pow(m[i+1][i-1],2))/(2*m[i][i+1]*m[i][i-1])); } double cosO(double **m, int i){ //printf("%f %f\n", pow(m[i][i+1], 2) + pow(m[i+1][i+3],2) - 2*m[i][i+1]*m[i+1][i+3]*cos(theta(m, i+1))*cos(theta(m, i+2)) - pow(m[i][i+3],2), 2*m[i][i+1]*m[i+1][i+3]*sin(theta(m, i+1))*sin(theta(m, i+2)) ); double theta2 = acos((pow(m[i+1][i+2],2) + pow(m[i+1][i+3],2) - pow(m[i+2][i+3],2))/(2*m[i+1][i+3]*m[i+1][i+2])); double res = (pow(m[i][i+1], 2) + pow(m[i+1][i+3],2) - 2*m[i][i+1]*m[i+1][i+3]*cos(theta(m, i+1))*cos(theta2) - pow(m[i][i+3],2))/ (2*m[i][i+1]*m[i+1][i+3]*sin(theta(m, i+1))*sin(theta2)); if (res > 1) return 1; if (res < -1) return -1; return res; } double cosOmega(double **m, int i){ if (i-3 < 0) return 1000; double Ai = (2*pow(m[i-2][i-1],2))*(pow(m[i-3][i-2],2) + pow(m[i-2][i] ,2) - pow(m[i-3][i] ,2)); double Bi = pow(m[i-3][i-2],2) + pow(m[i-2][i-1],2) - pow(m[i-3][i-1],2); double Ci = pow(m[i-2][i-1],2) + pow(m[i-2][i],2) - pow(m[i-1][i],2); double Di = sqrt( 4*pow(m[i-3][i-2],2) *pow(m[i-2][i-1],2) -pow(Bi,2) ); double Ei = sqrt(4*pow(m[i-2][i-1],2)*pow(m[i-2][i],2)-pow(Ci,2) ); double res = (Ai - Bi*Ci)/(Di*Ei); if (res > 1) return 1; if (res < -1) return -1; return res; } int isFeasible(double **mat, int len, vertex *v, int i){ if (!v) return 0; int j = i-1; double pos[i][3]; vertex *aux = v->p; while (aux) { //printf("\n\tj = %d {%f, %f, %f}\n", j, aux->pos.x, aux->pos.y, aux->pos.z); pos[j][0] = aux->pos.x; pos[j][1] = aux->pos.y; pos[j--][2] = aux->pos.z; aux = aux->p; } for (j = 0; j < i-3; j++) { if (mat[i][j] > 0) { double dij = pow(v->pos.x - pos[j][0],2)+pow(v->pos.y - pos[j][1],2)+pow(v->pos.z - pos[j][2],2); double diff = pow(mat[i][j],2)- dij; if (diff < 0) diff = diff*(-1); double dist = sqrt(diff);//pow(diff,2); //printf("{%d,%d} {%f, %f, %f}-{%f, %f, %f} \n\t%.20f- %.20f = %.20f \n %.20f \n", i, j, v->pos.x, v->pos.y, v->pos.z, pos[j][0], pos[j][1], pos[j][2], mat[i][j], dij, diff, dist); if (dist > epsl) { return 0; } } } return 1; } double LDE(double **mat, double **m, int len){ int i, j, count = 0; double dij = 0; for (i = 0; i < len; i++) { for (j = i+1; j < len; j++) { if (mat[i][j]>0){ dij = dij + pow((pow(mat[i][j],2) - (pow(m[i][0] - m[j][0], 2) + pow(m[i][1] - m[j][1], 2) + pow(m[i][2] - m[j][2], 2))),2)/mat[i][j]; count++; } } } return dij/count; } int qtd = 0; int BranchAndPrune(double **mat, int len, vertex *v, int i){ if(i < len){ double thetai = theta(mat,i-1); double cti = cos(thetai); double sti = sin(thetai); double cwi = cosOmega(mat, i); //double cwi2 = cosO(mat, i-3); //printf("%f %f \n", cwi, cwi2 ); //printf("%f %f \n", acos(cwi)*57.295779513, acos(cwi2)*57.295779513 ); if (cwi*cwi > 1){ printf("\n %f Error cwi", cwi); getchar(); } double swi = sqrt(1-pow(cwi, 2)); double di = dis(mat,i); double bi1[] = {0-cti,0-sti,0,0-di*cti, sti*cwi,0-cti*cwi,0-swi,di*sti*cwi, sti*swi,0-cti*swi,cwi,di*sti*swi, 0,0,0,1}; int j; //for (j = 0; j < 16; j++) //{ // printf("%f ", bi1[j]); //} // printf("\n"); gsl_matrix_view Bi1 = gsl_matrix_view_array(bi1, 4, 4); swi = 0-swi; double bi2[] = {0-cti,0-sti,0,0-di*cti, sti*cwi,0-cti*cwi,0-swi,di*sti*cwi, sti*swi,0-cti*swi,cwi,di*sti*swi, 0,0,0,1}; //for (j = 0; j < 16; j++) //{ // printf("%f ", bi2[j]); //} //printf("\n"); gsl_matrix_view Bi2 = gsl_matrix_view_array(bi2, 4, 4); vertex *rv = (vertex*)calloc(1, sizeof(vertex)); rv->p = v; rv->C = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view)); *(rv->C) = gsl_matrix_view_array((double*)calloc(16,sizeof(double)), 4, 4); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &(v->C->matrix), &Bi1.matrix, 0.0, &(rv->C->matrix)); vertex *lv = (vertex*)calloc(1, sizeof(vertex)); lv->p = v; lv->C = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view)); *(lv->C) = gsl_matrix_view_array((double*)calloc(16,sizeof(double)), 4, 4); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &(v->C->matrix), &Bi2.matrix, 0.0, &(lv->C->matrix)); gsl_matrix_view *Xi = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view)); *Xi = gsl_matrix_view_array((double*)calloc(4,sizeof(double)), 4, 1); double *y = (double*)calloc(4,sizeof(double)); y[3] = 1; gsl_matrix_view *Y = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view)); *Y = gsl_matrix_view_array(y, 4, 1); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &(rv->C->matrix), &(Y->matrix), 0.0, &(Xi->matrix)); rv->pos.x = Xi->matrix.data[0]; rv->pos.y = Xi->matrix.data[1]; rv->pos.z = Xi->matrix.data[2]; gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &(lv->C->matrix), &(Y->matrix), 0.0, &(Xi->matrix)); lv->pos.x = Xi->matrix.data[0]; lv->pos.y = Xi->matrix.data[1]; lv->pos.z = Xi->matrix.data[2]; free(y); free(Y); free(Xi->matrix.data); free(Xi); //printf("[ %f, %f", rv->pos.x, rv->pos.y); //printf(" %f]\n", rv->pos.z); //printf("[ %f, %f", lv->pos.x, lv->pos.y); //printf(" %f ]\n", lv->pos.z); //getchar(); int s; //printf("\n"); if (isFeasible(mat, len, rv, i)){ v->r = rv; //for (s = 0; s < i; s++) //{ // printf(">"); //} //printf("1\n"); fflush(stdout); BranchAndPrune(mat, len, rv, i+1); }else { //for (s = 0; s < i; s++) //{ // printf("<"); //} // //printf("2\n"); free(rv->C->matrix.data); free(rv->C); free(rv); v->r = NULL; } if (isFeasible(mat, len, lv, i)){ v->l = lv; //for (s = 0; s < i; s++) //{ // printf(">"); //} // //printf("3\n"); fflush(stdout); BranchAndPrune(mat, len, lv, i+1); }else { //for (s = 0; s < i; s++) //{ // printf("<"); //} // //printf("4\n"); free(lv->C->matrix.data); free(lv->C); free(lv); v->l = NULL; } }else{ //printf(" ---------------- ue\n"); //fflush(stdout); qtd++; double **mat2 = calloc(len, sizeof(double*)); int i; for (i = 0; i < len; i++) { mat2[i] = calloc(3, sizeof(double)); } i = len-1; printf("\n["); while (v) { mat2[i][0] = v->pos.x; mat2[i][1] = v->pos.y; mat2[i--][2] = v->pos.z; //printf("%f %f %f; ", v->pos.x, v->pos.y, v->pos.z); v = v->p; } double lde = LDE(mat, mat2, len); printf("\n \t LDE = %.20f\n", lde); for (i = 0; i < len; i++) { printf("%f %f %f; ", mat[i][0], mat[i][1], mat[i][2]); } printf("]\n"); return 0; } } int printGrafo(int len, vertex *v, int i){ int j = -1; if (v->l){ printf("(%d, %d),", i, i+1); j = printGrafo(len, v->l, i+1); } if (v->r){ if (j != -1){ printf("(%d, %d),", i, j); j = printGrafo(len, v->r, j); }else { printf("(%d, %d),", i, i+1); return printGrafo(len, v->r, i+1); } } if (j == -1) return i+1; return j; } vertex *resul[10]; int solve(char *fileName, int len) { double **mat = matrixConstruct(fileName, len); if(mat == NULL){ printf("Error when construct matrix\n"); fflush(stdout); return 0; } double b1[] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; gsl_matrix_view B1 = gsl_matrix_view_array(b1, 4, 4); double b2[] = {-1,0,0,0-dis(mat,1), 0,1,0,0, 0,0,-1,0, 0,0,0,1}; gsl_matrix_view B2 = gsl_matrix_view_array(b2, 4, 4); double theta2 = theta(mat,1); //printf("[ cos %f\n", theta2); double ct2 = cos(theta2); double st2 = sin(theta2); double b3[] = {0-ct2,0-st2,0,0-dis(mat,2)*ct2, st2,0-ct2,0,dis(mat,2)*st2, 0,0,1,0, 0,0,0,1}; gsl_matrix_view B3 = gsl_matrix_view_array(b3, 4, 4); vertex *v = (vertex*)calloc(1, sizeof(vertex)); v->C = &B1; //printf("[ %f, %f %f\n", v->pos.x, v->pos.y, v->pos.z); vertex *v2 = (vertex*)calloc(1, sizeof(vertex)); v->r = v2; v2->C = &B2; v2->p = v; v2->pos.x = 0-dis(mat,1); // printf("[ %f, %f %f\n", v2->pos.x, v2->pos.y, v2->pos.z); vertex *v3 = (vertex*)calloc(1, sizeof(vertex)); v2->r = v3; v3->C = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view)); *(v3->C) = gsl_matrix_view_array((double*)calloc(16,sizeof(double)), 4, 4); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &B2.matrix, &(B3.matrix), 0.0, &(v3->C->matrix)); v3->p = v2; v3->pos.x = dis(mat,2)*ct2 -dis(mat,1); v3->pos.y = dis(mat,2)*st2; //printf("[ %f, %f", v3->pos.x, v3->pos.y); // printf(" %f]\n", v3->pos.z); BranchAndPrune(mat, len, v3, 3); printf("%d", qtd); //printf("["); //printGrafo(len, v, 0); //printf("]"); return 1; } int countCols(char *fileName) { FILE *file = NULL; if ((file = fopen(fileName, "r")) == NULL) { /* error openning the file */ perror("fopen: "); return 1; } int n, j = 0, k = 0; char buff[6]; memset(buff, 0, sizeof(buff)); if (fread(buff, sizeof(char), 5, file) < 5 || strcmp(buff, "E = [")) { fclose(file); perror("file out of params: "); return 1; } while ((n = fread(buff, sizeof(char), 1, file)) == 1) { if (buff[0] == ' ') { if (k > 0) { k = 0; j++; } continue; } else if (buff[0] == ';') { if (k) j++; break; } else { k++; } } fclose(file); return j; } int main(int argc, char **argv) { double time_spent = 0.0; clock_t begin = clock(); if (argc < 3) { usage(argv[0]); } else { if (!strcmp(argv[1], "-s")) { int len; if (argc < 4) { len = countCols(argv[2]); }else { if ((len = atoi(argv[3])) == 0){ /* error openning the file */ perror("count_vertex param error: "); return 1; } } solve(argv[2], len); } else if (!strcmp(argv[1], "-c")) { printf("%d\n",countCols(argv[2])); } else if (!strcmp(argv[1], "-show")) { printMat(matrixConstruct(argv[2], countCols(argv[2])), countCols(argv[2])); } else if (!strcmp(argv[1], "-d")) { ddd(argv[2],10); } else { usage(argv[0]); } } //getchar(); clock_t end = clock(); // calculate elapsed time by finding difference (end - begin) and // divide by CLOCKS_PER_SEC to convert to seconds time_spent += (double)(end - begin) / CLOCKS_PER_SEC; printf("\nTime elpased is %.20f seconds", time_spent); fflush(stdout); }
{ "alphanum_fraction": 0.4195577926, "avg_line_length": 28.6260720412, "ext": "c", "hexsha": "e3b9850935fbdbb344b3e9a99e38be4e3ca00816", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "12b9625340ddfe77daf5ce2692f5d84d0189e7c5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "caomem/BP", "max_forks_repo_path": "BP.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "12b9625340ddfe77daf5ce2692f5d84d0189e7c5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "caomem/BP", "max_issues_repo_path": "BP.c", "max_line_length": 211, "max_stars_count": null, "max_stars_repo_head_hexsha": "12b9625340ddfe77daf5ce2692f5d84d0189e7c5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "caomem/BP", "max_stars_repo_path": "BP.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5459, "size": 16689 }
#include <stdio.h> #include <gsl/gsl_poly.h> int main(void) { /* coefficients of f(x) = -1 + x^5 */ double a[6] = {-1, 0, 0, 0, 0, 1}; printf("x = %f\n", gsl_poly_eval(a, 6, 3.0)); return 0; } // int main(void) { // int i; // /* coefficients of P(x) = -1 + x^5 */ // double a[6] = {-1, 0, 0, 0, 0, 1}; // double z[10]; // gsl_poly_complex_workspace* w = gsl_poly_complex_workspace_alloc(6); // gsl_poly_complex_solve(a, 6, w, z); // gsl_poly_complex_workspace_free(w); // for (i = 0; i < 5; i++) { // printf("z%d = %+.18f %+.18f\n", i, z[2 * i], z[2 * i + 1]); // } // return 0; // }
{ "alphanum_fraction": 0.4931087289, "avg_line_length": 27.2083333333, "ext": "c", "hexsha": "14655abcee54b2d6fcf000fda7665ce6f923be6a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "shakfu/pd-psl", "max_forks_repo_path": "tests/test4.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "shakfu/pd-psl", "max_issues_repo_path": "tests/test4.c", "max_line_length": 75, "max_stars_count": null, "max_stars_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "shakfu/pd-psl", "max_stars_repo_path": "tests/test4.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 253, "size": 653 }
#ifndef TOPICH #define TOPICH #include <gsl/gsl_vector.h> #include <math.h> #include "utils.h" #include "typedefs.h" #include "hyperparameter.h" #define MH_ETA_STDEV 0.005 #define MH_GAM_STDEV 0.005 /* === topic methods === */ /* * update the count of a word in a topic * */ void topic_update_word(topic* t, int w, double update); /* * update the document count in a topic * */ void topic_update_doc_cnt(topic* t, double update); /* * write log probability in a file * */ void topic_write_log_prob(topic* t, FILE* f); /* === tree methods === */ /* * allocate a new tree with a certain depth * */ tree* tree_new(int depth, int nwords, gsl_vector* eta, gsl_vector* gam, double scaling_shape, double scaling_scale); /* * add children to a node down to the depth of the tree; * return the leaf of that path * */ topic* tree_fill(topic* t); /* * add a child to a topic * */ topic* topic_add_child(topic* t); /* * make a new topic * */ topic* topic_new(int nwords, int level, topic* parent, tree* tr); /* * given a leaf with 0 instances, delete the leaf and all ancestors * which also have 0 instances. (!!! use asserts here) * */ void tree_prune(topic* t); /* * delete a node from the tree * */ void delete_node(topic* t); /* * write a tree to file * */ void tree_write_log_prob(tree* tree, FILE* f); /* * sample a document path from a tree * */ void populate_prob_dfs(topic* node, doc* d, double* logsum, double* pprob, int root_level); void tree_sample_doc_path(tree* tr, doc* d, short do_remove, int root_level); /* * sample a new path in the tree for a document * */ void tree_sample_path_for_doc(tree* t, doc* d); /* * update the tree from an entire document * */ void tree_update_from_doc(doc* d, double update, int root_level); /* * sample a leaf from the tree with populated probabilties * */ topic* tree_sample_path(topic* node, double logsum); topic* tree_sample_dfs(double r, topic* node, double* sum, double logsum); void tree_add_doc_to_path(topic* node, doc* d, int root_level); void tree_remove_doc_from_path(tree* tr, doc* d, int root_level); /* * write a tree to a file * */ void write_tree(tree* tf, FILE* file); void write_tree_levels(tree* tr, FILE* file); void write_tree_level_dfs(topic* t, FILE* f); void write_tree_topics_dfs(topic* t, FILE* f); /* * scores * */ double gamma_score(topic* t); double gamma_score_PY(topic* t, double gam_add); double eta_score(topic* t); double log_gamma_ratio(doc* d, topic* t, int level); double log_gamma_ratio_new(doc* d, int level, double eta, int nterms); void tree_mh_update_eta(tree* tr); void dfs_sample_scaling(topic* t); /* * copying a tree * */ void copy_topic(const topic* src, topic* dest); void copy_tree_dfs(const topic* src, topic* dest); tree * copy_tree(const tree* tr); void free_tree(tree * tr); void free_tree_dfs(topic * t); int ntopics_in_tree(tree * tr); int ntopics_in_tree_dfs(topic * t); #endif
{ "alphanum_fraction": 0.6752864157, "avg_line_length": 17.3579545455, "ext": "h", "hexsha": "03010431540e07c4fcab238456b2d57cc0085a10", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thatindiandude/PGM-Project", "max_forks_repo_path": "Algorithms/OurAlgo/hlda-c/topic.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thatindiandude/PGM-Project", "max_issues_repo_path": "Algorithms/OurAlgo/hlda-c/topic.h", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thatindiandude/PGM-Project", "max_stars_repo_path": "Algorithms/OurAlgo/hlda-c/topic.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 791, "size": 3055 }
/* Copyright [2020] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * Authors: * */ #ifndef _NUPM_OPENED_SPACE_H_ #define _NUPM_OPENED_SPACE_H_ #include <common/byte_span.h> #include <common/fd_locked.h> #include <common/logging.h> /* log_source */ #include <common/memory_mapped.h> #include <common/moveable_ptr.h> #include <common/string_view.h> #include <common/types.h> /* addr_t */ #include <gsl/pointers> #include <cassert> #include <cstddef> #include <string> #include <vector> namespace nupm { struct dax_manager; struct range_use { private: common::moveable_ptr<dax_manager> _dm; /* Note: arena_fs used multiple ranges */ std::vector<common::memory_mapped> _iovm; std::vector<common::memory_mapped> address_coverage_check(std::vector<common::memory_mapped> &&iovm); using byte = common::byte; using byte_span = common::byte_span; public: #if 0 const auto & operator[](std::size_t i) const { return _iovm.at(i).iov(); } #else byte_span operator[](std::size_t i) const { const auto &iov = _iovm.at(i).iov(); return common::make_byte_span(::base(iov), ::size(iov)); } #endif range_use(dax_manager *dm_, std::vector<common::memory_mapped> &&); range_use(const range_use &) = delete; range_use &operator=(const range_use &) = delete; range_use(range_use &&) noexcept = default; void grow(std::vector<common::memory_mapped> &&); void shrink(std::size_t size); ~range_use(); gsl::not_null<dax_manager *> dm() const { return _dm; } ::off_t size() const; }; struct space_opened : private common::log_source { private: using byte_span = common::byte_span; common::fd_locked _fd_locked; /* Note: arena_fs may someday use multiple ranges */ range_use _range; /* owns the file mapping */ std::vector<common::memory_mapped> map_dev(int fd, const addr_t base_addr); std::vector<common::memory_mapped> map_fs(int fd, const std::vector<byte_span> &mapping, ::off_t offset); public: space_opened(const common::log_source &, dax_manager * dm_, common::fd_locked && fd, const addr_t base_addr); space_opened(const common::log_source &, dax_manager * dm_, common::fd_locked && fd, const std::vector<byte_span> &mapping); space_opened(space_opened &&) noexcept = default; void shrink(std::size_t size); void grow(std::vector<byte_span> && iovv); int fd() const { return _fd_locked.fd(); } range_use &range() { return _range; } }; } #endif
{ "alphanum_fraction": 0.7219945355, "avg_line_length": 32.8988764045, "ext": "h", "hexsha": "9936d4a8658cda5c3498d483db77514acc2ae76c", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_path": "src/lib/libnupm/include/nupm/space_opened.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_path": "src/lib/libnupm/include/nupm/space_opened.h", "max_line_length": 141, "max_stars_count": 60, "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_path": "src/lib/libnupm/include/nupm/space_opened.h", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "num_tokens": 760, "size": 2928 }
#ifndef SDCA_MATH_BLAS_H #define SDCA_MATH_BLAS_H #if defined(BLAS_MKL) //#include <mkl.h> // produces warnings with -pedantic #include <mkl_cblas.h> #elif defined(BLAS_ACCELERATE) #include <Accelerate/Accelerate.h> #elif defined(BLAS_MATLAB) #include <cstddef> typedef std::ptrdiff_t ptrdiff_t; // Matlab's blas.h needs ptrdiff_t #include <blas.h> #elif defined(BLAS_DEFAULT) #include <cblas.h> #elif defined(BLAS_DEFAULT_LOCAL_HEADER) #include "cblas.h" #endif #if defined(BLAS_MATLAB) enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; #endif namespace sdca { #if defined(MKL_INT) typedef MKL_INT blas_int; #elif defined(BLAS_MATLAB) typedef ptrdiff_t blas_int; #else typedef int blas_int; #endif inline void sdca_blas_scal( const blas_int n, const float alpha, float* X ) { #if defined(sscal) blas_int inc(1); sscal(const_cast<blas_int*>(&n), const_cast<float*>(&alpha), X, &inc); #else cblas_sscal(n, alpha, X, 1); #endif } inline void sdca_blas_scal( const blas_int n, const double alpha, double* X ) { #if defined(dscal) blas_int inc(1); dscal(const_cast<blas_int*>(&n), const_cast<double*>(&alpha), X, &inc); #else cblas_dscal(n, alpha, X, 1); #endif } inline void sdca_blas_copy( const blas_int n, const float* X, float* Y ) { #if defined(scopy) blas_int inc(1); scopy(const_cast<blas_int*>(&n), const_cast<float*>(X), &inc, Y, &inc); #else cblas_scopy(n, X, 1, Y, 1); #endif } inline void sdca_blas_copy( const blas_int n, const double* X, double* Y ) { #if defined(dcopy) blas_int inc(1); dcopy(const_cast<blas_int*>(&n), const_cast<double*>(X), &inc, Y, &inc); #else cblas_dcopy(n, X, 1, Y, 1); #endif } inline void sdca_blas_swap( const blas_int n, float* X, float* Y ) { #if defined(scopy) blas_int inc(1); sswap(const_cast<blas_int*>(&n), X, &inc, Y, &inc); #else cblas_sswap(n, X, 1, Y, 1); #endif } inline void sdca_blas_swap( const blas_int n, double* X, double* Y ) { #if defined(dcopy) blas_int inc(1); dswap(const_cast<blas_int*>(&n), X, &inc, Y, &inc); #else cblas_dswap(n, X, 1, Y, 1); #endif } inline void sdca_blas_axpy( const blas_int n, const float alpha, const float* X, float* Y ) { #if defined(saxpy) blas_int inc(1); saxpy(const_cast<blas_int*>(&n), const_cast<float*>(&alpha), const_cast<float*>(X), &inc, Y, &inc); #else cblas_saxpy(n, alpha, X, 1, Y, 1); #endif } inline void sdca_blas_axpy( const blas_int n, const double alpha, const double* X, double* Y ) { #if defined(daxpy) blas_int inc(1); daxpy(const_cast<blas_int*>(&n), const_cast<double*>(&alpha), const_cast<double*>(X), &inc, Y, &inc); #else cblas_daxpy(n, alpha, X, 1, Y, 1); #endif } inline void sdca_blas_axpby( const blas_int n, const float alpha, const float* X, const float beta, float* Y ) { #if defined(cblas_saxpby) cblas_saxpby(n, alpha, X, 1, beta, Y, 1); #elif defined(sscal) blas_int inc(1); sscal(const_cast<blas_int*>(&n), const_cast<float*>(&beta), Y, &inc); saxpy(const_cast<blas_int*>(&n), const_cast<float*>(&alpha), const_cast<float*>(X), &inc, Y, &inc); #else cblas_sscal(n, beta, Y, 1); cblas_saxpy(n, alpha, X, 1, Y, 1); #endif } inline void sdca_blas_axpby( const blas_int n, const double alpha, const double* X, const double beta, double* Y ) { #if defined(cblas_daxpby) cblas_daxpby(n, alpha, X, 1, beta, Y, 1); #elif defined(dscal) blas_int inc(1); dscal(const_cast<blas_int*>(&n), const_cast<double*>(&beta), Y, &inc); daxpy(const_cast<blas_int*>(&n), const_cast<double*>(&alpha), const_cast<double*>(X), &inc, Y, &inc); #else cblas_dscal(n, beta, Y, 1); cblas_daxpy(n, alpha, X, 1, Y, 1); #endif } inline float sdca_blas_dot( const blas_int n, const float* X, const float* Y ) { #if defined(sdot) blas_int inc(1); return sdot(const_cast<blas_int*>(&n), const_cast<float*>(X), &inc, const_cast<float*>(Y), &inc); #else return cblas_sdot(n, X, 1, Y, 1); #endif } inline double sdca_blas_dot( const blas_int n, const double* X, const double* Y ) { #if defined(ddot) blas_int inc(1); return ddot(const_cast<blas_int*>(&n), const_cast<double*>(X), &inc, const_cast<double*>(Y), &inc); #else return cblas_ddot(n, X, 1, Y, 1); #endif } inline float sdca_blas_asum( const blas_int n, const float* X ) { #if defined(sasum) blas_int inc(1); return sasum(const_cast<blas_int*>(&n), const_cast<float*>(X), &inc); #else return cblas_sasum(n, X, 1); #endif } inline double sdca_blas_asum( const blas_int n, const double* X ) { #if defined(dasum) blas_int inc(1); return dasum(const_cast<blas_int*>(&n), const_cast<double*>(X), &inc); #else return cblas_dasum(n, X, 1); #endif } inline float sdca_blas_nrm2( const blas_int n, const float* X ) { #if defined(snrm2) blas_int inc(1); return snrm2(const_cast<blas_int*>(&n), const_cast<float*>(X), &inc); #else return cblas_snrm2(n, X, 1); #endif } inline double sdca_blas_nrm2( const blas_int n, const double* X ) { #if defined(dnrm2) blas_int inc(1); return dnrm2(const_cast<blas_int*>(&n), const_cast<double*>(X), &inc); #else return cblas_dnrm2(n, X, 1); #endif } inline void sdca_blas_gemv( const blas_int m, const blas_int n, const float* A, const float* X, float* Y, const CBLAS_TRANSPOSE transA = CblasNoTrans, const float alpha = 1, const float beta = 0 ) { #if defined(sgemv) blas_int inc(1); char trans((transA == CblasNoTrans) ? 'N' : 'T'); sgemv(&trans, const_cast<blas_int*>(&m), const_cast<blas_int*>(&n), const_cast<float*>(&alpha), const_cast<float*>(A), const_cast<blas_int*>(&m), const_cast<float*>(X), &inc, const_cast<float*>(&beta), Y, &inc); #else cblas_sgemv(CblasColMajor, transA, m, n, alpha, A, m, X, 1, beta, Y, 1); #endif } inline void sdca_blas_gemv( const blas_int m, const blas_int n, const double* A, const double* X, double* Y, const CBLAS_TRANSPOSE transA = CblasNoTrans, const double alpha = 1, const double beta = 0 ) { #if defined(dgemv) blas_int inc(1); char trans((transA == CblasNoTrans) ? 'N' : 'T'); dgemv(&trans, const_cast<blas_int*>(&m), const_cast<blas_int*>(&n), const_cast<double*>(&alpha), const_cast<double*>(A), const_cast<blas_int*>(&m), const_cast<double*>(X), &inc, const_cast<double*>(&beta), Y, &inc); #else cblas_dgemv(CblasColMajor, transA, m, n, alpha, A, m, X, 1, beta, Y, 1); #endif } inline void sdca_blas_ger( const blas_int m, const blas_int n, const float alpha, const float* X, const float* Y, float* A ) { #if defined(sger) blas_int inc(1); sger(const_cast<blas_int*>(&m), const_cast<blas_int*>(&n), const_cast<float*>(&alpha), const_cast<float*>(X), &inc, const_cast<float*>(Y), &inc, A, const_cast<blas_int*>(&m)); #else cblas_sger(CblasColMajor, m, n, alpha, X, 1, Y, 1, A, m); #endif } inline void sdca_blas_ger( const blas_int m, const blas_int n, const double alpha, const double* X, const double* Y, double* A ) { #if defined(dger) blas_int inc(1); dger(const_cast<blas_int*>(&m), const_cast<blas_int*>(&n), const_cast<double*>(&alpha), const_cast<double*>(X), &inc, const_cast<double*>(Y), &inc, A, const_cast<blas_int*>(&m)); #else cblas_dger(CblasColMajor, m, n, alpha, X, 1, Y, 1, A, m); #endif } inline void sdca_blas_gemm( const blas_int m, const blas_int n, const blas_int k, const float* A, const blas_int lda, const float* B, const blas_int ldb, float* C, const CBLAS_TRANSPOSE transA = CblasNoTrans, const CBLAS_TRANSPOSE transB = CblasNoTrans, const float alpha = 1, const float beta = 0 ) { #if defined(sgemm) char transa((transA == CblasNoTrans) ? 'N' : 'T'); char transb((transB == CblasNoTrans) ? 'N' : 'T'); sgemm(&transa, &transb, const_cast<blas_int*>(&m), const_cast<blas_int*>(&n), const_cast<blas_int*>(&k), const_cast<float*>(&alpha), const_cast<float*>(A), const_cast<blas_int*>(&lda), const_cast<float*>(B), const_cast<blas_int*>(&ldb), const_cast<float*>(&beta), C, const_cast<blas_int*>(&m)); #else cblas_sgemm(CblasColMajor, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, m); #endif } inline void sdca_blas_gemm( const blas_int m, const blas_int n, const blas_int k, const double* A, const blas_int lda, const double* B, const blas_int ldb, double* C, const CBLAS_TRANSPOSE transA = CblasNoTrans, const CBLAS_TRANSPOSE transB = CblasNoTrans, const double alpha = 1, const double beta = 0 ) { #if defined(dgemm) char transa((transA == CblasNoTrans) ? 'N' : 'T'); char transb((transB == CblasNoTrans) ? 'N' : 'T'); dgemm(&transa, &transb, const_cast<blas_int*>(&m), const_cast<blas_int*>(&n), const_cast<blas_int*>(&k), const_cast<double*>(&alpha), const_cast<double*>(A), const_cast<blas_int*>(&lda), const_cast<double*>(B), const_cast<blas_int*>(&ldb), const_cast<double*>(&beta), C, const_cast<blas_int*>(&m)); #else cblas_dgemm(CblasColMajor, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, m); #endif } } #endif
{ "alphanum_fraction": 0.6372209997, "avg_line_length": 22.7214285714, "ext": "h", "hexsha": "40a9606977a6174ec632ada17e91583ff7db122d", "lang": "C", "max_forks_count": 17, "max_forks_repo_forks_event_max_datetime": "2022-01-11T06:55:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-26T04:23:58.000Z", "max_forks_repo_head_hexsha": "fd5c1f18214a28360b3753ed5385c5bfa9af8264", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mlapin/libsdca", "max_forks_repo_path": "include/sdca/math/blas.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "fd5c1f18214a28360b3753ed5385c5bfa9af8264", "max_issues_repo_issues_event_max_datetime": "2019-05-09T12:14:55.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-20T15:21:41.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mlapin/libsdca", "max_issues_repo_path": "include/sdca/math/blas.h", "max_line_length": 79, "max_stars_count": 37, "max_stars_repo_head_hexsha": "fd5c1f18214a28360b3753ed5385c5bfa9af8264", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mlapin/libsdca", "max_stars_repo_path": "include/sdca/math/blas.h", "max_stars_repo_stars_event_max_datetime": "2021-08-18T06:33:32.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-21T21:43:07.000Z", "num_tokens": 3111, "size": 9543 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" void cblas_sgbmv (const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const int KL, const int KU, const float alpha, const float *A, const int lda, const float *X, const int incX, const float beta, float *Y, const int incY) { #define BASE float #include "source_gbmv_r.h" #undef BASE }
{ "alphanum_fraction": 0.6796338673, "avg_line_length": 29.1333333333, "ext": "c", "hexsha": "9f2fc7dcc5d4530374a210d5bccccc9317c296fb", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/cblas/sgbmv.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/cblas/sgbmv.c", "max_line_length": 78, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/cblas/sgbmv.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 124, "size": 437 }
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <gbpLib.h> #include <gbpRNG.h> #include <gbpMCMC.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_interp.h> void free_MCMC(MCMC_info *MCMC) { int i_P, i_DS; int i_array; MCMC_DS_info *current_DS; MCMC_DS_info *next_DS; SID_log("Freeing MCMC structure...", SID_LOG_OPEN); // Parameter arrays for(i_P = 0; i_P < MCMC->n_P; i_P++) SID_free(SID_FARG MCMC->P_names[i_P]); SID_free(SID_FARG MCMC->P_names); SID_free(SID_FARG MCMC->P_init); SID_free(SID_FARG MCMC->P_new); SID_free(SID_FARG MCMC->P_last); SID_free(SID_FARG MCMC->P_chain); SID_free(SID_FARG MCMC->P_limit_min); SID_free(SID_FARG MCMC->P_limit_max); if(MCMC->n_arrays > 0) { for(i_array = 0; i_array < MCMC->n_arrays; i_array++) { SID_free(SID_FARG MCMC->array[i_array]); SID_free(SID_FARG MCMC->array_name[i_array]); } SID_free(SID_FARG MCMC->array); SID_free(SID_FARG MCMC->array_name); } // Covariance and displacement vector free_MCMC_covariance(MCMC); // Random number generator if(MCMC->RNG != NULL) free_RNG(MCMC->RNG); // Dataset arrays free_MCMC_arrays(MCMC); free_MCMC_DS(MCMC); // Communicators SID_Comm_free(&(MCMC->comm)); SID_log("Done.", SID_LOG_CLOSE); }
{ "alphanum_fraction": 0.6415224913, "avg_line_length": 26.2727272727, "ext": "c", "hexsha": "1bb02e7e83bc55ae1d5c16de8724b79023280c06", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpMCMC/free_MCMC.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpMCMC/free_MCMC.c", "max_line_length": 63, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpMCMC/free_MCMC.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 475, "size": 1445 }
/* eigen/gensymm.c * * Copyright (C) 2007 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdlib.h> #include <config.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> /* * This module computes the eigenvalues of a real generalized * symmetric-definite eigensystem A x = \lambda B x, where A and * B are symmetric, and B is positive-definite. */ /* gsl_eigen_gensymm_alloc() Allocate a workspace for solving the generalized symmetric-definite eigenvalue problem. The size of this workspace is O(2n). Inputs: n - size of matrices Return: pointer to workspace */ gsl_eigen_gensymm_workspace * gsl_eigen_gensymm_alloc(const size_t n) { gsl_eigen_gensymm_workspace *w; if (n == 0) { GSL_ERROR_NULL ("matrix dimension must be positive integer", GSL_EINVAL); } w = (gsl_eigen_gensymm_workspace *) calloc (1, sizeof (gsl_eigen_gensymm_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->size = n; w->symm_workspace_p = gsl_eigen_symm_alloc(n); if (!w->symm_workspace_p) { gsl_eigen_gensymm_free(w); GSL_ERROR_NULL("failed to allocate space for symm workspace", GSL_ENOMEM); } return (w); } /* gsl_eigen_gensymm_alloc() */ /* gsl_eigen_gensymm_free() Free workspace w */ void gsl_eigen_gensymm_free (gsl_eigen_gensymm_workspace * w) { RETURN_IF_NULL (w); if (w->symm_workspace_p) gsl_eigen_symm_free(w->symm_workspace_p); free(w); } /* gsl_eigen_gensymm_free() */ /* gsl_eigen_gensymm() Solve the generalized symmetric-definite eigenvalue problem A x = \lambda B x for the eigenvalues \lambda. Inputs: A - real symmetric matrix B - real symmetric and positive definite matrix eval - where to store eigenvalues w - workspace Return: success or error */ int gsl_eigen_gensymm (gsl_matrix * A, gsl_matrix * B, gsl_vector * eval, gsl_eigen_gensymm_workspace * w) { const size_t N = A->size1; /* check matrix and vector sizes */ if (N != A->size2) { GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR); } else if ((N != B->size1) || (N != B->size2)) { GSL_ERROR ("B matrix dimensions must match A", GSL_EBADLEN); } else if (eval->size != N) { GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN); } else if (w->size != N) { GSL_ERROR ("matrix size does not match workspace", GSL_EBADLEN); } else { int s; /* compute Cholesky factorization of B */ s = gsl_linalg_cholesky_decomp(B); if (s != GSL_SUCCESS) return s; /* B is not positive definite */ /* transform to standard symmetric eigenvalue problem */ gsl_eigen_gensymm_standardize(A, B); s = gsl_eigen_symm(A, eval, w->symm_workspace_p); return s; } } /* gsl_eigen_gensymm() */ /* gsl_eigen_gensymm_standardize() Reduce the generalized symmetric-definite eigenproblem to the standard symmetric eigenproblem by computing C = L^{-1} A L^{-t} where L L^t is the Cholesky decomposition of B Inputs: A - (input/output) real symmetric matrix B - real symmetric, positive definite matrix in Cholesky form Return: success Notes: A is overwritten by L^{-1} A L^{-t} */ int gsl_eigen_gensymm_standardize(gsl_matrix *A, const gsl_matrix *B) { const size_t N = A->size1; size_t i; double a, b, c; for (i = 0; i < N; ++i) { /* update lower triangle of A(i:n, i:n) */ a = gsl_matrix_get(A, i, i); b = gsl_matrix_get(B, i, i); a /= b * b; gsl_matrix_set(A, i, i, a); if (i < N - 1) { gsl_vector_view ai = gsl_matrix_subcolumn(A, i, i + 1, N - i - 1); gsl_matrix_view ma = gsl_matrix_submatrix(A, i + 1, i + 1, N - i - 1, N - i - 1); gsl_vector_const_view bi = gsl_matrix_const_subcolumn(B, i, i + 1, N - i - 1); gsl_matrix_const_view mb = gsl_matrix_const_submatrix(B, i + 1, i + 1, N - i - 1, N - i - 1); gsl_blas_dscal(1.0 / b, &ai.vector); c = -0.5 * a; gsl_blas_daxpy(c, &bi.vector, &ai.vector); gsl_blas_dsyr2(CblasLower, -1.0, &ai.vector, &bi.vector, &ma.matrix); gsl_blas_daxpy(c, &bi.vector, &ai.vector); gsl_blas_dtrsv(CblasLower, CblasNoTrans, CblasNonUnit, &mb.matrix, &ai.vector); } } return GSL_SUCCESS; } /* gsl_eigen_gensymm_standardize() */
{ "alphanum_fraction": 0.6408748392, "avg_line_length": 25.4252336449, "ext": "c", "hexsha": "112dd1f7e47b1a04d35ce2dc5860c9e0d30b2fcf", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/eigen/gensymm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/eigen/gensymm.c", "max_line_length": 87, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/eigen/gensymm.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 1526, "size": 5441 }
#pragma once #include <gsl/span> #include <cstddef> namespace imageview { // Implementation of the PixelFormat concept for the 8-bit grayscale pixel // format. class PixelFormatGrayscale8 { public: using color_type = unsigned char; static constexpr int kBytesPerPixel = 1; constexpr color_type read(gsl::span<const std::byte, kBytesPerPixel> data) const; constexpr void write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const; }; constexpr PixelFormatGrayscale8::color_type PixelFormatGrayscale8::read( gsl::span<const std::byte, kBytesPerPixel> data) const { return static_cast<color_type>(data[0]); } constexpr void PixelFormatGrayscale8::write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const { data[0] = static_cast<std::byte>(color); } } // namespace imageview
{ "alphanum_fraction": 0.7553444181, "avg_line_length": 27.1612903226, "ext": "h", "hexsha": "c7fa95940211594cfbe2cc3a94e7f4ac46a8f389", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_path": "include/imageview/pixel_formats/PixelFormatGrayscale8.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_path": "include/imageview/pixel_formats/PixelFormatGrayscale8.h", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_path": "include/imageview/pixel_formats/PixelFormatGrayscale8.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 211, "size": 842 }
// Copyright Jean Pierre Cimalando 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include "keystate.h" #include "instruments/synth_fx.h" #include <gsl/gsl> #include <string> #include <vector> #include <bitset> struct Player_Song_Metadata { std::string name; std::string author; std::vector<std::string> text; char format[32] = {}; unsigned track_count = 0; }; struct Player_State { Keyboard_State kb; unsigned repeat_mode = 0; double time_position = 0; double duration = 0; double tempo = 0; unsigned speed = 100; std::string file_path; Player_Song_Metadata song_metadata; std::bitset<16> channel_enabled; float audio_levels[10] {}; int fx_parameters[Synth_Fx::Parameter_Count] {}; };
{ "alphanum_fraction": 0.6800445931, "avg_line_length": 25.6285714286, "ext": "h", "hexsha": "cefb5ec58b9ad723ed0af7629f245b6729b396f5", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_path": "sources/player/state.h", "max_issues_count": 19, "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_path": "sources/player/state.h", "max_line_length": 61, "max_stars_count": 22, "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_path": "sources/player/state.h", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "num_tokens": 228, "size": 897 }
/* * MIT License * * Copyright (c) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * * Abstract: misc util functions and macros */ #ifndef __UTIL_H__ #define __UTIL_H__ #include <algorithm> #include <gsl/span> #include <iterator> #include <sstream> #include <string> #include <vector> typedef gsl::span<const uint8_t> cbspan; #ifndef block_round #define block_round(ODD, BLK) \ ((ODD) + (((BLK) - ((ODD) & ((BLK)-1))) & ((BLK)-1))) #endif template <class TContainer> static inline bool starts_with(const TContainer& haystack, const TContainer& needle) { return haystack.size() >= needle.size() && std::equal(needle.begin(), needle.end(), haystack.begin()); } static inline void split(const std::string& s, char delim, std::vector<std::string>& result) { std::string::size_type prev_pos = 0, pos = 0; do { pos = s.find(delim, pos); if (pos == std::string::npos) { result.emplace_back(std::move(s.substr(prev_pos))); } else { result.emplace_back(std::move(s.substr(prev_pos, pos - prev_pos))); prev_pos = ++pos; } } while (pos != std::string::npos); } static inline std::vector<std::string> split(const std::string& s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } static constexpr uint64_t prime = 0x100000001B3ull; static constexpr uint64_t basis = 0xCBF29CE484222325ull; static constexpr uint64_t const_hash(const char* str, uint64_t last_value = basis) { return *str ? const_hash(str + 1, (*str ^ last_value) * prime) : last_value; } static inline uint64_t hash(const std::string& str) { uint64_t ret{basis}; for (auto i : str) { ret ^= static_cast<uint64_t>(i); ret *= prime; } return ret; } #endif /* __UTIL_H__ */
{ "alphanum_fraction": 0.6490825688, "avg_line_length": 29.9215686275, "ext": "h", "hexsha": "9a61ed2cc1e5572d180d5ec5f6c3b779cabc70a1", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-03-19T15:17:54.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-17T06:51:02.000Z", "max_forks_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Intel-BMC/mtd-util", "max_forks_repo_path": "util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Intel-BMC/mtd-util", "max_issues_repo_path": "util.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Intel-BMC/mtd-util", "max_stars_repo_path": "util.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 713, "size": 3052 }
#include "benchmark.hpp" #include <lapacke.h> int svd(double *A, int m, int n, double *U, double *s, double *V_t) { const int lda = n; const int ldu = m; const int ldvt = n; const char jobu = 'A'; const char jobvt = 'A'; const int superb_size = (m < n) ? m : n; double *superb = malloc(sizeof(double) * (superb_size - 1)); lapack_int retval = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, jobu, jobvt, m, n, A, lda, s, U, ldu, V_t, ldvt, superb); if (retval > 0) { return -1; } /* Clean up */ free(superb); return 0; } int main() { for (size_t k = 10; k <= 1000; k += 10) { size_t m = k; double *A = create_random_sq_matrix(m); double *U = malloc(sizeof(double) * m * m); double *d = malloc(sizeof(double) * m); double *V_t = malloc(sizeof(double) * m * m); sleep(0.1); struct timespec t = tic(); svd(A, m, m, U, d, V_t); printf("matrix_size: %ld\t: dgesvd: %fs\n", m, toc(&t)); free(A); free(U); free(d); free(V_t); } return 0; }
{ "alphanum_fraction": 0.3949175824, "avg_line_length": 26.4727272727, "ext": "c", "hexsha": "5768f1c4311ae3b6867bc7116839f54a0c9f4836", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-10-22T03:19:44.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-12T05:10:24.000Z", "max_forks_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "daoran/proto", "max_forks_repo_path": "proto/lib/benchmarks/bench_svd-lapacke.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_issues_repo_issues_event_max_datetime": "2021-12-21T01:10:10.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:08:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "daoran/proto", "max_issues_repo_path": "proto/lib/benchmarks/bench_svd-lapacke.c", "max_line_length": 69, "max_stars_count": 15, "max_stars_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "daoran/proto", "max_stars_repo_path": "proto/lib/benchmarks/bench_svd-lapacke.c", "max_stars_repo_stars_event_max_datetime": "2021-12-20T12:25:04.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-27T21:37:47.000Z", "num_tokens": 370, "size": 1456 }
/* err/strerror.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> const char * gsl_strerror (const int gsl_errno) { switch (gsl_errno) { case GSL_SUCCESS: return "success" ; case GSL_FAILURE: return "failure" ; case GSL_CONTINUE: return "the iteration has not converged yet"; case GSL_EDOM: return "input domain error" ; case GSL_ERANGE: return "output range error" ; case GSL_EFAULT: return "invalid pointer" ; case GSL_EINVAL: return "invalid argument supplied by user" ; case GSL_EFAILED: return "generic failure" ; case GSL_EFACTOR: return "factorization failed" ; case GSL_ESANITY: return "sanity check failed - shouldn't happen" ; case GSL_ENOMEM: return "malloc failed" ; case GSL_EBADFUNC: return "problem with user-supplied function"; case GSL_ERUNAWAY: return "iterative process is out of control"; case GSL_EMAXITER: return "exceeded max number of iterations" ; case GSL_EZERODIV: return "tried to divide by zero" ; case GSL_EBADTOL: return "specified tolerance is invalid or theoretically unattainable" ; case GSL_ETOL: return "failed to reach the specified tolerance" ; case GSL_EUNDRFLW: return "underflow" ; case GSL_EOVRFLW: return "overflow" ; case GSL_ELOSS: return "loss of accuracy" ; case GSL_EROUND: return "roundoff error" ; case GSL_EBADLEN: return "matrix/vector sizes are not conformant" ; case GSL_ENOTSQR: return "matrix not square" ; case GSL_ESING: return "singularity or extremely bad function behavior detected" ; case GSL_EDIVERGE: return "integral or series is divergent" ; case GSL_EUNSUP: return "the required feature is not supported by this hardware platform"; case GSL_EUNIMPL: return "the requested feature is not (yet) implemented"; case GSL_ECACHE: return "cache limit exceeded"; case GSL_ETABLE: return "table limit exceeded"; case GSL_ENOPROG: return "iteration is not making progress towards solution"; case GSL_ENOPROGJ: return "jacobian evaluations are not improving the solution"; case GSL_ETOLF: return "cannot reach the specified tolerance in F"; case GSL_ETOLX: return "cannot reach the specified tolerance in X"; case GSL_ETOLG: return "cannot reach the specified tolerance in gradient"; case GSL_EOF: return "end of file"; default: return "unknown error code" ; } }
{ "alphanum_fraction": 0.6878680801, "avg_line_length": 33.2941176471, "ext": "c", "hexsha": "49f57c04f05aa3b20b13a34e4f2eac1fb9d51602", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/err/strerror.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/err/strerror.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/err/strerror.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 830, "size": 3396 }
#include <lapacke.h> #include <stdio.h> /* Auxiliary routine: printing a matrix */ void print_matrix_rowmajor( char* desc, lapack_int m, lapack_int n, double* mat, lapack_int ldm ) { lapack_int i, j; printf( "\n %s\n", desc ); for( i = 0; i < m; i++ ) { for( j = 0; j < n; j++ ) printf( " %6.2f", mat[i*ldm+j] ); printf( "\n" ); } } /* Auxiliary routine: printing a matrix */ void print_matrix_colmajor( char* desc, lapack_int m, lapack_int n, double* mat, lapack_int ldm ) { lapack_int i, j; printf( "\n %s\n", desc ); for( i = 0; i < m; i++ ) { for( j = 0; j < n; j++ ) printf( " %6.2f", mat[i+j*ldm] ); printf( "\n" ); } } /* Auxiliary routine: printing a vector of integers */ void print_vector( char* desc, lapack_int n, lapack_int* vec ) { lapack_int j; printf( "\n %s\n", desc ); for( j = 0; j < n; j++ ) printf( " %6i", vec[j] ); printf( "\n" ); }
{ "alphanum_fraction": 0.5029354207, "avg_line_length": 30.0588235294, "ext": "c", "hexsha": "9b72eb620932a91c111fafab22bd8d8fba47f98f", "lang": "C", "max_forks_count": 1564, "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:12:54.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-01T01:32:27.000Z", "max_forks_repo_head_hexsha": "b54b50fe3a5ec921d18ddf5fbdb80092d1b23893", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dnoan/OpenBLAS", "max_forks_repo_path": "lapack-netlib/LAPACKE/example/lapacke_example_aux.c", "max_issues_count": 2067, "max_issues_repo_head_hexsha": "b54b50fe3a5ec921d18ddf5fbdb80092d1b23893", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:59:43.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-01T03:50:01.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dnoan/OpenBLAS", "max_issues_repo_path": "lapack-netlib/LAPACKE/example/lapacke_example_aux.c", "max_line_length": 99, "max_stars_count": 4392, "max_stars_repo_head_hexsha": "b54b50fe3a5ec921d18ddf5fbdb80092d1b23893", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dnoan/OpenBLAS", "max_stars_repo_path": "lapack-netlib/LAPACKE/example/lapacke_example_aux.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:14:38.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-02T18:15:45.000Z", "num_tokens": 325, "size": 1022 }
/* fft/hc_main.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_fft_halfcomplex.h> #include "hc_pass.h" int FUNCTION(gsl_fft_halfcomplex,backward) (BASE data[], const size_t stride, const size_t n, const TYPE(gsl_fft_halfcomplex_wavetable) * wavetable, TYPE(gsl_fft_real_workspace) * work) { int status = FUNCTION(gsl_fft_halfcomplex,transform) (data, stride, n, wavetable, work) ; return status ; } int FUNCTION(gsl_fft_halfcomplex,inverse) (BASE data[], const size_t stride, const size_t n, const TYPE(gsl_fft_halfcomplex_wavetable) * wavetable, TYPE(gsl_fft_real_workspace) * work) { int status = FUNCTION(gsl_fft_halfcomplex,transform) (data, stride, n, wavetable, work); if (status) { return status; } /* normalize inverse fft with 1/n */ { const double norm = 1.0 / n; size_t i; for (i = 0; i < n; i++) { data[stride*i] *= norm; } } return status; } int FUNCTION(gsl_fft_halfcomplex,transform) (BASE data[], const size_t stride, const size_t n, const TYPE(gsl_fft_halfcomplex_wavetable) * wavetable, TYPE(gsl_fft_real_workspace) * work) { BASE * const scratch = work->scratch; BASE * in; BASE * out; size_t istride, ostride ; size_t factor, product, q; size_t i; size_t nf; int state; int product_1; int tskip; TYPE(gsl_complex) *twiddle1, *twiddle2, *twiddle3, *twiddle4; if (n == 0) { GSL_ERROR ("length n must be positive integer", GSL_EDOM); } if (n == 1) { /* FFT of one data point is the identity */ return 0; } if (n != wavetable->n) { GSL_ERROR ("wavetable does not match length of data", GSL_EINVAL); } if (n != work->n) { GSL_ERROR ("workspace does not match length of data", GSL_EINVAL); } nf = wavetable->nf; product = 1; state = 0; for (i = 0; i < nf; i++) { factor = wavetable->factor[i]; product_1 = product; product *= factor; q = n / product; tskip = (q + 1) / 2 - 1; if (state == 0) { in = data; istride = stride; out = scratch; ostride = 1; state = 1; } else { in = scratch; istride = 1; out = data; ostride = stride; state = 0; } if (factor == 2) { twiddle1 = wavetable->twiddle[i]; FUNCTION(fft_halfcomplex,pass_2) (in, istride, out, ostride, product, n, twiddle1); } else if (factor == 3) { twiddle1 = wavetable->twiddle[i]; twiddle2 = twiddle1 + tskip; FUNCTION(fft_halfcomplex,pass_3) (in, istride, out, ostride, product, n, twiddle1, twiddle2); } else if (factor == 4) { twiddle1 = wavetable->twiddle[i]; twiddle2 = twiddle1 + tskip; twiddle3 = twiddle2 + tskip; FUNCTION(fft_halfcomplex,pass_4) (in, istride, out, ostride, product, n, twiddle1, twiddle2, twiddle3); } else if (factor == 5) { twiddle1 = wavetable->twiddle[i]; twiddle2 = twiddle1 + tskip; twiddle3 = twiddle2 + tskip; twiddle4 = twiddle3 + tskip; FUNCTION(fft_halfcomplex,pass_5) (in, istride, out, ostride, product, n, twiddle1, twiddle2, twiddle3, twiddle4); } else { twiddle1 = wavetable->twiddle[i]; FUNCTION(fft_halfcomplex,pass_n) (in, istride, out, ostride, factor, product, n, twiddle1); } } if (state == 1) /* copy results back from scratch to data */ { for (i = 0; i < n; i++) { data[stride*i] = scratch[i] ; } } return 0; }
{ "alphanum_fraction": 0.5270064663, "avg_line_length": 27.8201058201, "ext": "c", "hexsha": "591acd42eb834506934b0b43895cf2a46643308f", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/fft/hc_main.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/fft/hc_main.c", "max_line_length": 95, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/fft/hc_main.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 1345, "size": 5258 }
/** * * @file core_dparfb.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Dulceneia Becker * @date 2011-06-14 * @generated d Tue Jan 7 11:44:48 2014 * **/ #ifdef USE_MKL #include <mkl_cblas.h> #include <mkl_lapacke.h> #else #include <cblas.h> #include <lapacke.h> #endif #include "common.h" /***************************************************************************//** * * @ingroup CORE_double * * CORE_dparfb applies a complex upper triangular block reflector H * or its transpose H' to a complex rectangular matrix formed by * coupling two tiles A1 and A2. Matrix V is: * * COLUMNWISE ROWWISE * * | K | | N2-L | L | * __ _____________ __ __ _________________ __ * | | | | | \ * | | | | | \ L * M2-L | | | K |_______________|_____\ __ * | | | M2 | | * __ |____| | | | K-L * \ | | __ |______________________| __ * L \ | | * __ \|______| __ | N2 | * * | L | K-L | * ******************************************************************************* * * @param[in] side * @arg PlasmaLeft : apply Q or Q**T from the Left; * @arg PlasmaRight : apply Q or Q**T from the Right. * * @param[in] trans * @arg PlasmaNoTrans : No transpose, apply Q; * @arg PlasmaTrans : ConjTranspose, apply Q**T. * * @param[in] direct * Indicates how H is formed from a product of elementary * reflectors * @arg PlasmaForward : H = H(1) H(2) . . . H(k) (Forward) * @arg PlasmaBackward : H = H(k) . . . H(2) H(1) (Backward) * * @param[in] storev * Indicates how the vectors which define the elementary * reflectors are stored: * @arg PlasmaColumnwise * @arg PlasmaRowwise * * @param[in] M1 * The number of columns of the tile A1. M1 >= 0. * * @param[in] N1 * The number of rows of the tile A1. N1 >= 0. * * @param[in] M2 * The number of columns of the tile A2. M2 >= 0. * * @param[in] N2 * The number of rows of the tile A2. N2 >= 0. * * @param[in] K * The order of the matrix T (= the number of elementary * reflectors whose product defines the block reflector). * * @param[in] L * The size of the triangular part of V * * @param[in,out] A1 * On entry, the M1-by-N1 tile A1. * On exit, A1 is overwritten by the application of Q. * * @param[in] LDA1 * The leading dimension of the array A1. LDA1 >= max(1,N1). * * @param[in,out] A2 * On entry, the M2-by-N2 tile A2. * On exit, A2 is overwritten by the application of Q. * * @param[in] LDA2 * The leading dimension of the tile A2. LDA2 >= max(1,N2). * * @param[in] V * (LDV,K) if STOREV = 'C' * (LDV,M2) if STOREV = 'R' and SIDE = 'L' * (LDV,N2) if STOREV = 'R' and SIDE = 'R' * Matrix V. * * @param[in] LDV * The leading dimension of the array V. * If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M2); * if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N2); * if STOREV = 'R', LDV >= K. * * @param[out] T * The triangular K-by-K matrix T in the representation of the * block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] LDT * The leading dimension of the array T. LDT >= K. * * @param[in,out] WORK * * @param[in] LDWORK * The dimension of the array WORK. * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if -i, the i-th argument had an illegal value * ******************************************************************************/ /* This kernel is never traced so return type on previous line for convert2eztrace.pl script */ int CORE_dparfb(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum direct, PLASMA_enum storev, int M1, int N1, int M2, int N2, int K, int L, double *A1, int LDA1, double *A2, int LDA2, const double *V, int LDV, const double *T, int LDT, double *WORK, int LDWORK) { static double zone = 1.0; static double mzone = -1.0; int j; /* Check input arguments */ if ((side != PlasmaLeft) && (side != PlasmaRight)) { coreblas_error(1, "Illegal value of side"); return -1; } if ((trans != PlasmaNoTrans) && (trans != PlasmaTrans)) { coreblas_error(2, "Illegal value of trans"); return -2; } if ((direct != PlasmaForward) && (direct != PlasmaBackward)) { coreblas_error(3, "Illegal value of direct"); return -3; } if ((storev != PlasmaColumnwise) && (storev != PlasmaRowwise)) { coreblas_error(4, "Illegal value of storev"); return -4; } if (M1 < 0) { coreblas_error(5, "Illegal value of M1"); return -5; } if (N1 < 0) { coreblas_error(6, "Illegal value of N1"); return -6; } if ((M2 < 0) || ( (side == PlasmaRight) && (M1 != M2) ) ) { coreblas_error(7, "Illegal value of M2"); return -7; } if ((N2 < 0) || ( (side == PlasmaLeft) && (N1 != N2) ) ) { coreblas_error(8, "Illegal value of N2"); return -8; } if (K < 0) { coreblas_error(9, "Illegal value of K"); return -9; } /* Quick return */ if ((M1 == 0) || (N1 == 0) || (M2 == 0) || (N2 == 0) || (K == 0)) return PLASMA_SUCCESS; if (direct == PlasmaForward) { if (side == PlasmaLeft) { /* * Column or Rowwise / Forward / Left * ---------------------------------- * * Form H * A or H' * A where A = ( A1 ) * ( A2 ) */ /* W = A1 + op(V) * A2 */ CORE_dpamm( PlasmaW, PlasmaLeft, storev, K, N1, M2, L, A1, LDA1, A2, LDA2, V, LDV, WORK, LDWORK); /* W = op(T) * W */ cblas_dtrmm( CblasColMajor, CblasLeft, CblasUpper, (CBLAS_TRANSPOSE)trans, CblasNonUnit, K, N2, (zone), T, LDT, WORK, LDWORK); /* A1 = A1 - W */ for(j = 0; j < N1; j++) { cblas_daxpy( K, (mzone), &WORK[LDWORK*j], 1, &A1[LDA1*j], 1); } /* A2 = A2 - op(V) * W */ /* W also changes: W = V * W, A2 = A2 - W */ CORE_dpamm( PlasmaA2, PlasmaLeft, storev, M2, N2, K, L, A1, LDA1, A2, LDA2, V, LDV, WORK, LDWORK); } else { /* * Column or Rowwise / Forward / Right * ----------------------------------- * * Form H * A or H' * A where A = ( A1 A2 ) * */ /* W = A1 + A2 * op(V) */ CORE_dpamm( PlasmaW, PlasmaRight, storev, M1, K, N2, L, A1, LDA1, A2, LDA2, V, LDV, WORK, LDWORK); /* W = W * op(T) */ cblas_dtrmm( CblasColMajor, CblasRight, CblasUpper, (CBLAS_TRANSPOSE)trans, CblasNonUnit, M2, K, (zone), T, LDT, WORK, LDWORK); /* A1 = A1 - W */ for(j = 0; j < K; j++) { cblas_daxpy( M1, (mzone), &WORK[LDWORK*j], 1, &A1[LDA1*j], 1); } /* A2 = A2 - W * op(V) */ /* W also changes: W = W * V', A2 = A2 - W */ CORE_dpamm( PlasmaA2, PlasmaRight, storev, M2, N2, K, L, A1, LDA1, A2, LDA2, V, LDV, WORK, LDWORK); } } else { coreblas_error(3, "Not implemented (Backward / Left or Right)"); return PLASMA_ERR_NOT_SUPPORTED; } return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.4277790104, "avg_line_length": 31.1903114187, "ext": "c", "hexsha": "c87003d425abc53ecfd95afca3a935ca20fc257c", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z", "max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "tianyi93/hpxMP_mirror", "max_forks_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/core_dparfb.c", "max_issues_count": 25, "max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z", "max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "tianyi93/hpxMP_mirror", "max_issues_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/core_dparfb.c", "max_line_length": 95, "max_stars_count": 22, "max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "tianyi93/hpxMP_mirror", "max_stars_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/core_dparfb.c", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z", "num_tokens": 2476, "size": 9014 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <gsl.h> #include <nlohmann/json_fwd.hpp> #include <cstdint> #include <string> namespace cb { namespace crypto { enum class Algorithm { MD5, SHA1, SHA256, SHA512 }; bool isSupported(Algorithm algorithm); const int MD5_DIGEST_SIZE = 16; const int SHA1_DIGEST_SIZE = 20; const int SHA256_DIGEST_SIZE = 32; const int SHA512_DIGEST_SIZE = 64; /** * Generate a HMAC digest of the key and data by using the given * algorithm * * @throws std::invalid_argument - unsupported algorithm * std::runtime_error - Failures generating the HMAC */ std::string HMAC(Algorithm algorithm, std::string_view key, std::string_view data); /** * Generate a PBKDF2_HMAC digest of the key and data by using the given * algorithm * * @throws std::invalid_argument - unsupported algorithm * std::runtime_error - Failures generating the HMAC */ std::string PBKDF2_HMAC(Algorithm algorithm, const std::string& pass, std::string_view salt, unsigned int iterationCount); /** * Generate a digest by using the requested algorithm */ std::string digest(Algorithm algorithm, std::string_view data); enum class Cipher { AES_256_cbc }; Cipher to_cipher(const std::string& str); /** * Encrypt the specified data by using a given cipher * * @param cipher The cipher to use * @param key The key used for encryption * @param ivec The IV to use for encryption * @param data The Pointer to the data to encrypt * @return The encrypted data */ std::string encrypt(Cipher cipher, std::string_view key, std::string_view iv, std::string_view data); /** * Encrypt the specified data * * { * "cipher" : "name of the cipher", * "key" : "base64 of the raw key", * "iv" : "base64 of the raw iv" * } * * @param meta the json description of the encryption to use * @param data Pointer to the data to encrypt * @param length the length of the data to encrypt * @return The encrypted data */ std::string encrypt(const nlohmann::json& json, std::string_view data); /** * Decrypt the specified data by using a given cipher * * @param cipher The cipher to use * @param key The key used for encryption * @param ivec The IV to use for encryption * @param data The data to decrypt * @return The decrypted data */ std::string decrypt(Cipher cipher, std::string_view key, std::string_view iv, std::string_view data); /** * Decrypt the specified data * * { * "cipher" : "name of the cipher", * "key" : "base64 of the raw key", * "iv" : "base64 of the raw iv" * } * * @param meta the json description of the encryption to use * @param data Pointer to the data to decrypt * @param length the length of the data to decrypt * @return The decrypted data */ std::string decrypt(const nlohmann::json& json, std::string_view data); } // namespace crypto } // namespace cb
{ "alphanum_fraction": 0.6615097359, "avg_line_length": 29.0620155039, "ext": "h", "hexsha": "2e72bb5938f049b43078c436c318ef8a465fb23f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z", "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z", "max_forks_repo_head_hexsha": "17680c38a77d3a67fda55f763cc2631f924ed42d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "rualso/kv_engine", "max_forks_repo_path": "include/cbcrypto/cbcrypto.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "17680c38a77d3a67fda55f763cc2631f924ed42d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "rualso/kv_engine", "max_issues_repo_path": "include/cbcrypto/cbcrypto.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "17680c38a77d3a67fda55f763cc2631f924ed42d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "rualso/kv_engine", "max_stars_repo_path": "include/cbcrypto/cbcrypto.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 884, "size": 3749 }
#ifndef PCH_H #define PCH_H #define ISOLATION_AWARE_ENABLED 1 /* Only put files that never change or are rarely changed in this file. An include graph will be provided for some headers that were not explicit added. VC++ is a requirement. We don't care about warnings for library files. */ #pragma warning(push) #pragma warning(disable : 4091 4191 4365 4464 4571 4619 4623 4625 4626 4768 4774 5026 5027 5039 5045) /* Windows Stuff */ #include "windows_nodefines.h" #include <ShlObj.h> // CommCtrl #include <WindowsX.h> #include <atlbase.h> // atldef.h (Windows.h), atlcore.h (tchar.h), Shlwapi.h #include <direct.h> #include <io.h> #include <wincodec.h> #if WIN32_LEAN_AND_MEAN #include <CommDlg.h> #include <MMSystem.h> #include <ShellAPI.h> #endif // WIN32_LEAN_AND_MEAN /* Nuke WinAPI #defines - anything including this file should be using the ra versions. */ #undef CreateDirectory #undef GetMessage /* C Stuff */ #include <cctype> /* STL Stuff */ #include <array> // algorithm, iterator, tuple #include <atomic> #include <fstream> #include <iomanip> #include <map> #include <memory> #include <mutex> // chrono (time.h), functional, thread, utility #include <queue> // deque, vector, algorithm #include <set> #include <sstream> // string #include <stack> #include <unordered_map> #include <variant> #pragma warning(push) // Look at this file if you want to know what they are and what they mean #include "pch_cppcorecheck_suppressions.h" #include "pch_microsoft_suppressions.h" /* RapidJSON Stuff */ #define RAPIDJSON_HAS_STDSTRING 1 #define RAPIDJSON_NOMEMBERITERATORCLASS 1 #include <rapidjson\document.h> // has reader.h #include <rapidjson\error\en.h> #include <rapidjson\istreamwrapper.h> #include <rapidjson\ostreamwrapper.h> #include <rapidjson\writer.h> // has stringbuffer.h /* gsl stuff */ #define GSL_THROW_ON_CONTRACT_VIOLATION #include <gsl\gsl> // the default GSL Expects() macro throws an exception, which we don't try to catch anywhere. // replace it with our custom handler, which will log and report the error before throwing it. #ifndef RA_UTEST #ifdef NDEBUG extern void __gsl_contract_handler(const char* const file, unsigned int line); #undef Expects #define Expects(cond) (GSL_LIKELY(cond) ? static_cast<void>(0) : __gsl_contract_handler(__FILE__, __LINE__)) #else extern void __gsl_contract_handler(const char* const file, unsigned int line, const char* const error); #undef Expects #define Expects(cond) (GSL_LIKELY(cond) ? static_cast<void>(0) : __gsl_contract_handler(__FILE__, __LINE__, GSL_STRINGIFY(cond))) #endif #endif #pragma warning(pop) #if RA_UTEST #include <CodeAnalysis\Warnings.h> #pragma warning(push) #pragma warning(disable : ALL_CPPCORECHECK_WARNINGS) #include "CppUnitTest.h" #pragma warning(pop) #endif /* RA_UTEST */ /* rcheevos stuff */ #pragma warning(push) #pragma warning(disable : 4201) // nameless struct #include <rcheevos.h> #pragma warning(pop) #pragma warning(pop) #endif /* !PCH_H */
{ "alphanum_fraction": 0.7475825275, "avg_line_length": 28.5619047619, "ext": "h", "hexsha": "02ed11f3ecaa8f96ed8b43c1127a81003a10a881", "lang": "C", "max_forks_count": 17, "max_forks_repo_forks_event_max_datetime": "2022-03-04T08:49:03.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-17T16:09:31.000Z", "max_forks_repo_head_hexsha": "ccf3dea24d81aefdcf51535f073889d03272b259", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Jamiras/RAIntegration", "max_forks_repo_path": "src/pch.h", "max_issues_count": 309, "max_issues_repo_head_hexsha": "ccf3dea24d81aefdcf51535f073889d03272b259", "max_issues_repo_issues_event_max_datetime": "2022-01-22T20:13:04.000Z", "max_issues_repo_issues_event_min_datetime": "2018-04-15T12:10:59.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Jamiras/RAIntegration", "max_issues_repo_path": "src/pch.h", "max_line_length": 131, "max_stars_count": 71, "max_stars_repo_head_hexsha": "ccf3dea24d81aefdcf51535f073889d03272b259", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Jamiras/RAIntegration", "max_stars_repo_path": "src/pch.h", "max_stars_repo_stars_event_max_datetime": "2022-03-26T11:19:18.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-15T13:02:43.000Z", "num_tokens": 790, "size": 2999 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_errno.h> #include "ccl.h" /*----- ROUTINE: dc_NakamuraSuto ----- INPUT: cosmology, scale factor TASK: Computes the peak threshold: delta_c(z) assuming LCDM. Cosmology dependence of the critical linear density according to the spherical-collapse model. Fitting function from Nakamura & Suto (1997; arXiv:astro-ph/9710107). */ double dc_NakamuraSuto(ccl_cosmology *cosmo, double a, int *status){ double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status); double dc0 = (3./20.)*pow(12.*M_PI,2./3.); double dc = dc0*(1.+0.012299*log10(Om_mz)); return dc; } /*----- ROUTINE: Dv_BryanNorman ----- INPUT: cosmology, scale factor TASK: Computes the virial collapse density contrast with respect to the matter density assuming LCDM. Cosmology dependence of the virial collapse density according to the spherical-collapse model Fitting function from Bryan & Norman (1998; arXiv:astro-ph/9710107) */ double Dv_BryanNorman(ccl_cosmology *cosmo, double a, int *status){ double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status); double x = Om_mz-1.; double Dv0 = 18.*pow(M_PI,2); double Dv = (Dv0+82.*x-39.*pow(x,2))/Om_mz; return Dv; } static double sigmaM_m2r(ccl_cosmology *cosmo, double halomass, int *status) { double rho_m, smooth_radius; // Comoving matter density rho_m = ccl_rho_x(cosmo, 1., ccl_species_m_label, 1, status); smooth_radius = pow((3.0*halomass) / (4*M_PI*rho_m), (1.0/3.0)); return smooth_radius; } void ccl_cosmology_compute_sigma(ccl_cosmology *cosmo, ccl_f2d_t *psp, int *status) { if(cosmo->computed_sigma) return; int na = cosmo->spline_params.A_SPLINE_NA_SM + cosmo->spline_params.A_SPLINE_NLOG_SM - 1; int nm = cosmo->spline_params.LOGM_SPLINE_NM; double *m = NULL; double *y = NULL; double *aa = NULL; // create linearly-spaced values of log-mass. m = ccl_linear_spacing(cosmo->spline_params.LOGM_SPLINE_MIN, cosmo->spline_params.LOGM_SPLINE_MAX, nm); if (m == NULL || (fabs(m[0]-cosmo->spline_params.LOGM_SPLINE_MIN)>1e-5) || (fabs(m[nm-1]-cosmo->spline_params.LOGM_SPLINE_MAX)>1e-5) || (m[nm-1]>10E17)) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_massfunc.c: ccl_cosmology_compute_sigma(): " "Error creating linear spacing in m\n"); } // create scale factor array if (*status == 0) { aa = ccl_linlog_spacing(cosmo->spline_params.A_SPLINE_MINLOG_SM, cosmo->spline_params.A_SPLINE_MIN_SM, cosmo->spline_params.A_SPLINE_MAX, cosmo->spline_params.A_SPLINE_NLOG_SM, cosmo->spline_params.A_SPLINE_NA_SM); if (aa == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_massfunc.c: ccl_cosmology_compute_sigma(): " "Error creating scale factor array\n"); } } // create space for y, to be filled with sigma if (*status == 0) { y = malloc(sizeof(double)*nm*na); if (y == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_massfunc.c: ccl_cosmology_compute_sigma(): " "memory allocation\n"); } } // fill in sigma, if no errors have been triggered at this time. if (*status == 0) { #pragma omp parallel shared(na, aa, nm, m, y, status, cosmo, psp) \ default(none) { int i, j; double a_sf, smooth_radius; int local_status = *status; #pragma omp for for (j=0; j<na; j++) { a_sf = aa[j]; for (i=0; i<nm; i++) { smooth_radius = sigmaM_m2r(cosmo, pow(10,m[i]), &local_status); y[j*nm + i] = log(ccl_sigmaR(cosmo, smooth_radius, a_sf, psp, &local_status)); } } //end omp for if (local_status) { #pragma omp atomic write *status = local_status; } } //end omp parallel } gsl_spline2d *lsM = NULL; if (*status == 0) { lsM = gsl_spline2d_alloc(gsl_interp2d_bicubic, nm, na); if (lsM == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_massfunc.c: ccl_cosmology_compute_sigma(): " "error allocating 2D spline\n"); } } if(*status == 0) { int s2dstatus=gsl_spline2d_init(lsM, m, aa, y, nm, na); if (s2dstatus) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_massfunc.c: ccl_cosmology_compute_sigma(): " "error initializing spline\n"); } } if (*status == 0) { cosmo->computed_sigma = true; cosmo->data.logsigma = lsM; } else gsl_spline2d_free(lsM); free(aa); free(m); free(y); } /*----- ROUTINE: ccl_sigma_M ----- INPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor TASK: returns sigma from the sigmaM interpolation. Also computes the sigma interpolation if necessary. */ double ccl_sigmaM(ccl_cosmology *cosmo, double log_halomass, double a, int *status) { // Check if sigma has already been calculated if (!cosmo->computed_sigma) { *status = CCL_ERROR_SIGMA_INIT; ccl_cosmology_set_status_message(cosmo, "ccl_massfunc.c: ccl_sigmaM(): " "sigma(M) spline has not been computed!"); return NAN; } double lgsigmaM; int gslstatus = gsl_spline2d_eval_e(cosmo->data.logsigma, log_halomass, a, NULL, NULL, &lgsigmaM); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_massfunc.c: ccl_sigmaM():"); *status |= gslstatus; } return exp(lgsigmaM); } /*----- ROUTINE: ccl_dlnsigM_dlogM ----- INPUT: ccl_cosmology *cosmo, double halo mass in units of Msun TASK: returns the value of the derivative of ln(sigma^-1) with respect to log10 in halo mass. */ double ccl_dlnsigM_dlogM(ccl_cosmology *cosmo, double log_halomass, double a, int *status) { // Check if sigma has already been calculated if (!cosmo->computed_sigma) { *status = CCL_ERROR_SIGMA_INIT; ccl_cosmology_set_status_message(cosmo, "ccl_massfunc.c: ccl_dlnsigM_dlogM(): " "sigma(M) spline has not been computed!"); return NAN; } double dlsdlgm; int gslstatus = gsl_spline2d_eval_deriv_x_e(cosmo->data.logsigma, log_halomass, a, NULL, NULL, &dlsdlgm); if(gslstatus) { ccl_raise_gsl_warning(gslstatus, "ccl_massfunc.c: ccl_dlnsigM_dlogM():"); *status |= gslstatus; } return -dlsdlgm; }
{ "alphanum_fraction": 0.6098301809, "avg_line_length": 33.0730593607, "ext": "c", "hexsha": "47fac82ba3738ff586f1c3e711528bf571b6469f", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "src/ccl_massfunc.c", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "src/ccl_massfunc.c", "max_line_length": 101, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "src/ccl_massfunc.c", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 2048, "size": 7243 }
#ifndef S3D_CV_UTILITIES_CV_H #define S3D_CV_UTILITIES_CV_H #include "s3d/image/image.h" #include "s3d/utilities/random_color_generator.h" #include "s3d/video/video_frame.h" #include "s3d/video/video_types.h" #include "s3d/utilities/eigen.h" #include <opencv/cxeigen.hpp> #include <opencv2/opencv.hpp> #include <cstdint> #include <gsl/gsl> #include <cassert> #include <cmath> #include <tuple> namespace s3d { inline Image<uint8_t> cv2image(cv::Mat cvImg) { Image<uint8_t> img(Size(cvImg.cols, cvImg.rows)); cv::cv2eigen(cvImg, img); return img; } inline cv::Mat image2cv(const Image<uint8_t>& img) { cv::Mat cvImg; cv::eigen2cv(img, cvImg); return cvImg; } inline int nbChannelsToMatType(int nbChannels) { int imgType = CV_8U; switch (nbChannels) { case 1: imgType = CV_8U; break; case 2: imgType = CV_8UC2; break; case 3: imgType = CV_8UC3; break; case 4: imgType = CV_8UC4; break; default: break; } return imgType; } inline cv::Mat dataToMat(Size size, VideoPixelFormat pixelFormat, const gsl::span<const uint8_t>& data) { auto nbChannels = static_cast<int>(VideoFrame::NumBytesPerPixel(pixelFormat)); return cv::Mat(size.getHeight(), size.getWidth(), nbChannelsToMatType(nbChannels), const_cast<uchar*>(data.data())); } // does not copy data, to copy use resizeMat(...).clone(); inline void resizeMat(gsl::not_null<cv::Mat*> mat, float colsRatio, float rowsRatio) { float cols = mat->cols; float rows = mat->rows; // todo: use linear if upsampling, inter_area is good for down sampling cv::resize(*mat, *mat, cv::Size2f(cols * colsRatio, rows * rowsRatio), cv::INTER_AREA); } inline void resizeMat(gsl::not_null<cv::Mat*> mat, float ratio) { resizeMat(mat, ratio, ratio); } inline void displayInNewWindow(const std::string& name, cv::InputArray src) { cv::namedWindow(name, cv::WINDOW_AUTOSIZE); cv::imshow(name, src); } template <class T> void displayMatches(const std::string& title, const cv::Mat& left, const cv::Mat& right, const std::vector<Eigen::Matrix<T, 2, 1>>& featuresLeft, const std::vector<Eigen::Matrix<T, 2, 1>>& featuresRight) { cv::Mat leftRight(left.rows, left.cols * 2, left.type()); cv::hconcat(left, right, leftRight); // convert to color if (left.depth() == 1) { cv::cvtColor(leftRight, leftRight, cv::COLOR_GRAY2BGR); } // for random color RandomColorGenerator<cv::Scalar> colorGenerator; for (size_t i = 0; i < featuresLeft.size(); ++i) { // random color cv::Scalar color = colorGenerator.randomColor(); // discretize features const Eigen::Vector2i featureLeft = featuresLeft[i].template cast<int>(); const Eigen::Vector2i featureRight = featuresRight[i].template cast<int>() + Eigen::Vector2i(left.cols, 0.0f); const cv::Point ptLeft(featureLeft.x(), featureLeft.y()); const cv::Point ptRight(featureRight.x(), featureRight.y()); cv::line(leftRight, ptLeft, ptRight, color, 1, CV_AA); cv::circle(leftRight, ptLeft, 3, color, 1, CV_AA); cv::circle(leftRight, ptRight, 3, color, 1, CV_AA); } displayInNewWindow(title, leftRight); } template <class T> std::vector<cv::Point_<T>> eigenPointsToCV(std::vector<Eigen::Matrix<T, 2, 1>> points) { std::vector<cv::Point_<T>> pointsCV; for (auto point : points) { pointsCV.emplace_back(point.x(), point.y()); } return pointsCV; } template <class T, int N, int M> cv::Matx<T, N, M> eigenMatToCV(Eigen::Matrix<T, N, M> mat) { cv::Matx<T, 3, 3> matCV; cv::eigen2cv(mat, matCV); return matCV; }; template <typename T> static float distancePointLine(const cv::Point_<T> point, const cv::Vec<T, 3>& line) { // Line is given as a*x + b*y + c = 0 return std::abs(line(0) * point.x + line(1) * point.y + line(2)) / std::sqrt(line(0) * line(0) + line(1) * line(1)); } /** * \brief Compute and draw the epipolar lines in two images * associated to each other by a fundamental matrix * * \param title Title of the window to display * \param F Fundamental matrix * \param img1 First image * \param img2 Second image * \param points1 Set of points in the first image * \param points2 Set of points in the second image matching to the first set * \param inlierDistance Points with a high distance to the epipolar lines are * not displayed. If it is negative, all points are displayed **/ template <typename T1, typename T2> static std::tuple<cv::Mat, cv::Mat> drawEpipolarLines(const cv::Matx<T1, 3, 3> F, const cv::Mat& img1, const cv::Mat& img2, const std::vector<cv::Point_<T2>>& points1, const std::vector<cv::Point_<T2>>& points2, const float inlierDistance = -1) { assert(img1.size() == img2.size() && img1.type() == img2.type()); assert(points1.size() == points2.size()); assert(points1.size() > 0); cv::Mat outImgLeft(img1.rows, img1.cols, CV_8UC3); cv::Mat outImgRight(img1.rows, img1.cols, CV_8UC3); // for color drawing if (img1.type() == CV_8U) { cv::cvtColor(img1, outImgLeft, CV_GRAY2BGR); cv::cvtColor(img2, outImgRight, CV_GRAY2BGR); } else { img1.copyTo(outImgLeft); img2.copyTo(outImgRight); } // compute epilines for image 1 and 2 std::vector<cv::Vec<T2, 3>> epilines1, epilines2; cv::computeCorrespondEpilines(points1, 1, F, epilines1); cv::computeCorrespondEpilines(points2, 2, F, epilines2); assert(points1.size() == points2.size() && points2.size() == epilines1.size() && epilines1.size() == epilines2.size()); s3d::RandomColorGenerator<cv::Scalar> colorGenerator; for (size_t i = 0; i < points1.size(); i++) { if (inlierDistance > 0) { if (distancePointLine(points1[i], epilines2[i]) > inlierDistance || distancePointLine(points2[i], epilines1[i]) > inlierDistance) { // The point match is no inlier continue; } } // epipolar lines of the 1st point set are drawn in the 2nd image and vice-versa cv::Scalar color = colorGenerator.randomColor(); cv::line( outImgRight, cv::Point(0, -epilines1[i][2] / epilines1[i][1]), cv::Point(img1.cols, -(epilines1[i][2] + epilines1[i][0] * img1.cols) / epilines1[i][1]), color, 1, CV_AA); cv::circle(outImgLeft, points1[i], 3, color, -1, CV_AA); cv::line( outImgLeft, cv::Point(0, -epilines2[i][2] / epilines2[i][1]), cv::Point(img2.cols, -(epilines2[i][2] + epilines2[i][0] * img2.cols) / epilines2[i][1]), color, 1, CV_AA); cv::circle(outImgRight, points2[i], 3, color, -1, CV_AA); } return std::tuple<cv::Mat, cv::Mat>(outImgLeft, outImgRight); } /** * \brief Compute and draw the epipolar lines in two images * associated to each other by a fundamental matrix * * \param title Title of the window to display * \param F Fundamental matrix * \param img1 First image * \param img2 Second image * \param points1 Set of points in the first image * \param points2 Set of points in the second image matching to the first set **/ template <typename T1, typename T2> static void displayEpipolarLines(const std::string& title, const cv::Matx<T1, 3, 3> F, const cv::Mat& img1, const cv::Mat& img2, const std::vector<cv::Point_<T2>>& points1, const std::vector<cv::Point_<T2>>& points2) { assert(img1.size() == img2.size() && img1.type() == img2.type()); cv::Mat imgLeftEpilines, imgRightEpilines; std::tie(imgLeftEpilines, imgRightEpilines) = s3d::drawEpipolarLines(F, img1, img2, points1, points2); // horizontal concat cv::Mat outImg(img1.rows, img1.cols * 2, CV_8UC3); cv::hconcat(imgLeftEpilines, imgRightEpilines, outImg); cv::imshow(title, outImg); cv::waitKey(1); } } // namespace s3d #endif // S3D_CV_UTILITIES_CV_H
{ "alphanum_fraction": 0.6171326591, "avg_line_length": 33.0905511811, "ext": "h", "hexsha": "eb1cc14ee51c964683a1358401652a390d9fe1ef", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_path": "src/core/cv/include/s3d/cv/utilities/cv.h", "max_issues_count": 40, "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_path": "src/core/cv/include/s3d/cv/utilities/cv.h", "max_line_length": 105, "max_stars_count": 8, "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_path": "src/core/cv/include/s3d/cv/utilities/cv.h", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "num_tokens": 2438, "size": 8405 }
/** * VGMTrans (c) - 2002-2021 * Licensed under the zlib license * See the included LICENSE for more information */ #pragma once #include <vector> #include <fluidsynth.h> #include <gsl-lite.hpp> #include <QObject> #include <QString> class VGMColl; class MusicPlayer : public QObject { Q_OBJECT public: static auto &the() { static MusicPlayer instance; return instance; } MusicPlayer(const MusicPlayer &) = delete; MusicPlayer &operator=(const MusicPlayer &) = delete; MusicPlayer(MusicPlayer &&) = delete; MusicPlayer &operator=(MusicPlayer &&) = delete; ~MusicPlayer(); /** * Toggles the status of the player * @returns true if the player is playing */ bool toggle(); /** * Stops the player (unloads resources) */ void stop(); /** * Moves the player position * @param position relative to song start */ void seek(int position); /** * Returns the title of the song currently playing * @return the song title */ [[nodiscard]] QString songTitle() const; /** * Loads a VGMColl for playback * @param collection * @return true if data was loaded correctly */ bool playCollection(VGMColl *collection); /** * Checks whether the player is playing * @return true if playing */ [[nodiscard]] bool playing() const; /** * The number of MIDI ticks elapsed since the player was started * @return number of ticks relative to song start */ [[nodiscard]] int elapsedTicks() const; /** * The total number of MIDI ticks in the song * @return total ticks in the song */ [[nodiscard]] int totalTicks() const; /** * Gets all the audio driver the player supports * @return the driver list */ [[nodiscard]] std::vector<const char *> getAvailableDrivers() const; /** * Changes the current audio driver and restarts playing * @param driver_name * @return true if the driver changed */ bool setAudioDriver(const char *driver_name); /** * Checks the value of a setting of the player corresponds to the passed value * @param setting * @param value * @return true if the value matches */ [[nodiscard]] bool checkSetting(const char *setting, const char *value) const; /** * Sets a parameter of the player to the corrisponding passed value * @param setting * @param value */ void updateSetting(const char *setting, const char *value); signals: void statusChange(bool playing); void playbackPositionChanged(int current, int max); private: MusicPlayer(); fluid_settings_t *m_settings = nullptr; fluid_synth_t *m_synth = nullptr; fluid_audio_driver_t *m_active_driver = nullptr; fluid_player_t *m_active_player = nullptr; VGMColl *m_active_coll = nullptr; void makeSettings(); void makeSynth(); void makePlayer(); };
{ "alphanum_fraction": 0.6789772727, "avg_line_length": 23.6638655462, "ext": "h", "hexsha": "9890c3199c7cc0ca6de8ee326c1bbc5099af98f0", "lang": "C", "max_forks_count": 105, "max_forks_repo_forks_event_max_datetime": "2022-03-26T14:16:42.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-07T12:22:01.000Z", "max_forks_repo_head_hexsha": "fa032cb66c63af2af2fb3c3d23fbf0582d465618", "max_forks_repo_licenses": [ "Zlib" ], "max_forks_repo_name": "DubiousDoggo/vgmtrans", "max_forks_repo_path": "src/ui/qt/MusicPlayer.h", "max_issues_count": 230, "max_issues_repo_head_hexsha": "fa032cb66c63af2af2fb3c3d23fbf0582d465618", "max_issues_repo_issues_event_max_datetime": "2022-02-28T17:25:02.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-04T14:29:06.000Z", "max_issues_repo_licenses": [ "Zlib" ], "max_issues_repo_name": "DubiousDoggo/vgmtrans", "max_issues_repo_path": "src/ui/qt/MusicPlayer.h", "max_line_length": 80, "max_stars_count": 538, "max_stars_repo_head_hexsha": "39d4c74ad2380ca9dca00535ecb8c9c1c56f5d78", "max_stars_repo_licenses": [ "Zlib" ], "max_stars_repo_name": "Sci3ntia/vgmtrans", "max_stars_repo_path": "src/ui/qt/MusicPlayer.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:57:42.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-22T22:10:31.000Z", "num_tokens": 697, "size": 2816 }
/* cheb/integ.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_chebyshev.h> int gsl_cheb_calc_integ(gsl_cheb_series * integ, const gsl_cheb_series * f) { const size_t n = f->order + 1; const double con = 0.25 * (f->b - f->a); if(integ->order != f->order) { GSL_ERROR ("order of chebyshev series must be equal", GSL_ENOMEM); } /* set the other parameters in the chebyshev struct */ integ->a = f->a; integ->b = f->b; /* FIXME: should probably set integ->f[] as well */ if(n == 1) { integ->c[0] = 0.; } else if(n == 2) { integ->c[1] = con * f->c[0]; integ->c[0] = 2.0 * integ->c[1]; } else { double sum = 0.0; double fac = 1.0; size_t i; for(i=1; i<=n-2; i++) { integ->c[i] = con * (f->c[i-1] - f->c[i+1])/((double)i); sum += fac * integ->c[i]; fac = -fac; } integ->c[n-1] = con * f->c[n-2]/(n-1.0); sum += fac * integ->c[n-1]; integ->c[0] = 2.0 * sum; } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6216802168, "avg_line_length": 27.9545454545, "ext": "c", "hexsha": "7720563080dde1b7f74315ab1bd1ee3ba93089f3", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/cheb/integ.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/cheb/integ.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/cheb/integ.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 597, "size": 1845 }
#include <stdlib.h> #include <stdio.h> #include "linterp.h" #include "qspline.h" #include "cspline.h" #include <gsl/gsl_spline.h> #define NUM_DATAPOINTS 9 /** Read a txt file with two columns seperated by tab and read all the items * into the arrays x and y. **/ void read_data(double *x, double *y){ FILE *infile = fopen("xy_data.txt", "r"); for (int i = 0; i < NUM_DATAPOINTS; ++i){ int items = fscanf(infile, "%lf\t%lf\n", &x[i], &y[i]); if (items == EOF){ break; } } fclose(infile); } void exerciseA(){ FILE *outfile = fopen("out1.txt", "w"); double *x, *y; x = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS); y = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS); read_data(x, y); gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_linear, NUM_DATAPOINTS); gsl_spline_init (spline, x, y, NUM_DATAPOINTS); double val = 0.1; do { double interp_val = linterp(NUM_DATAPOINTS, x, y, val); double interp_val_integ = linterp_integ(NUM_DATAPOINTS, x, y, val); double y_gsl = gsl_spline_eval(spline, val, acc); fprintf(outfile, "%f\t%f\t%f\t%f\n", val, interp_val, interp_val_integ, y_gsl); val += 0.1; } while (val < 8); gsl_spline_free (spline); gsl_interp_accel_free (acc); free(x), free(y); fclose(outfile); } void exerciseB(){ FILE *outfile = fopen("out2.txt", "w"); double *x, *y; x = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS); y = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS); read_data(x, y); double val = 0.1; do { double interp_val = qspline_eval(NUM_DATAPOINTS, x, y, val); double interp_val_integ = qspline_integ(NUM_DATAPOINTS, x, y, val); double interp_val_deriv = qspline_deriv(NUM_DATAPOINTS, x, y, val); fprintf(outfile, "%f\t%f\t%f\t%f\n", val, interp_val, interp_val_integ, interp_val_deriv); val += 0.1; } while (val < 8); free(x), free(y); fclose(outfile); } void exerciseC(){ FILE *outfile = fopen("out3.txt", "w"); double *x, *y; x = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS); y = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS); read_data(x, y); gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, NUM_DATAPOINTS); gsl_spline_init (spline, x, y, NUM_DATAPOINTS); double val = 0.1; do { double interp_val = cspline_eval(NUM_DATAPOINTS, x, y, val); double interp_val_integ = cspline_integ(NUM_DATAPOINTS, x, y, val); double y_gsl = gsl_spline_eval(spline, val, acc); fprintf(outfile, "%f\t%f\t%f\t%f\n", val, interp_val, interp_val_integ, y_gsl); val += 0.1; } while (val < 8); gsl_spline_free (spline); gsl_interp_accel_free (acc); free(x), free(y); fclose(outfile); } int main(){ exerciseA(); exerciseB(); exerciseC(); return 0; }
{ "alphanum_fraction": 0.616710013, "avg_line_length": 29.5769230769, "ext": "c", "hexsha": "632e773c55ada69f7d78c1d39ce08ac379e9dd58", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5311e70625223f94f23007205e718d3bc13f04e0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mads-hb/ppnm-2022", "max_forks_repo_path": "homeworks/splines/c/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5311e70625223f94f23007205e718d3bc13f04e0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mads-hb/ppnm-2022", "max_issues_repo_path": "homeworks/splines/c/main.c", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "5311e70625223f94f23007205e718d3bc13f04e0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mads-hb/ppnm-2022", "max_stars_repo_path": "homeworks/splines/c/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 881, "size": 3076 }
/* * Copyright (c) 1997-1999 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Sun Nov 7 20:43:59 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -real2hc 32 */ /* * This function contains 156 FP additions, 42 FP multiplications, * (or, 140 additions, 26 multiplications, 16 fused multiply/add), * 46 stack variables, and 64 memory accesses */ static const fftw_real K195090322 = FFTW_KONST(+0.195090322016128267848284868477022240927691618); static const fftw_real K980785280 = FFTW_KONST(+0.980785280403230449126182236134239036973933731); static const fftw_real K555570233 = FFTW_KONST(+0.555570233019602224742830813948532874374937191); static const fftw_real K831469612 = FFTW_KONST(+0.831469612302545237078788377617905756738560812); static const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562); static const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626); static const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938); /* * Generator Id's : * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $ * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $ * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $ */ void fftw_real2hc_32(const fftw_real *input, fftw_real *real_output, fftw_real *imag_output, int istride, int real_ostride, int imag_ostride) { fftw_real tmp7; fftw_real tmp135; fftw_real tmp31; fftw_real tmp83; fftw_real tmp14; fftw_real tmp148; fftw_real tmp34; fftw_real tmp82; fftw_real tmp123; fftw_real tmp143; fftw_real tmp71; fftw_real tmp99; fftw_real tmp126; fftw_real tmp144; fftw_real tmp76; fftw_real tmp100; fftw_real tmp22; fftw_real tmp136; fftw_real tmp38; fftw_real tmp80; fftw_real tmp29; fftw_real tmp137; fftw_real tmp41; fftw_real tmp79; fftw_real tmp116; fftw_real tmp140; fftw_real tmp54; fftw_real tmp96; fftw_real tmp119; fftw_real tmp141; fftw_real tmp59; fftw_real tmp97; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp1; fftw_real tmp2; fftw_real tmp3; fftw_real tmp4; fftw_real tmp5; fftw_real tmp6; ASSERT_ALIGNED_DOUBLE; tmp1 = input[0]; tmp2 = input[16 * istride]; tmp3 = tmp1 + tmp2; tmp4 = input[8 * istride]; tmp5 = input[24 * istride]; tmp6 = tmp4 + tmp5; tmp7 = tmp3 + tmp6; tmp135 = tmp3 - tmp6; tmp31 = tmp1 - tmp2; tmp83 = tmp4 - tmp5; } { fftw_real tmp10; fftw_real tmp32; fftw_real tmp13; fftw_real tmp33; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp8; fftw_real tmp9; fftw_real tmp11; fftw_real tmp12; ASSERT_ALIGNED_DOUBLE; tmp8 = input[4 * istride]; tmp9 = input[20 * istride]; tmp10 = tmp8 + tmp9; tmp32 = tmp8 - tmp9; tmp11 = input[28 * istride]; tmp12 = input[12 * istride]; tmp13 = tmp11 + tmp12; tmp33 = tmp11 - tmp12; } tmp14 = tmp10 + tmp13; tmp148 = tmp13 - tmp10; tmp34 = K707106781 * (tmp32 + tmp33); tmp82 = K707106781 * (tmp33 - tmp32); } { fftw_real tmp63; fftw_real tmp121; fftw_real tmp75; fftw_real tmp122; fftw_real tmp66; fftw_real tmp124; fftw_real tmp69; fftw_real tmp125; fftw_real tmp70; fftw_real tmp72; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp61; fftw_real tmp62; fftw_real tmp73; fftw_real tmp74; ASSERT_ALIGNED_DOUBLE; tmp61 = input[31 * istride]; tmp62 = input[15 * istride]; tmp63 = tmp61 - tmp62; tmp121 = tmp61 + tmp62; tmp73 = input[7 * istride]; tmp74 = input[23 * istride]; tmp75 = tmp73 - tmp74; tmp122 = tmp73 + tmp74; } { fftw_real tmp64; fftw_real tmp65; fftw_real tmp67; fftw_real tmp68; ASSERT_ALIGNED_DOUBLE; tmp64 = input[3 * istride]; tmp65 = input[19 * istride]; tmp66 = tmp64 - tmp65; tmp124 = tmp64 + tmp65; tmp67 = input[27 * istride]; tmp68 = input[11 * istride]; tmp69 = tmp67 - tmp68; tmp125 = tmp67 + tmp68; } tmp123 = tmp121 + tmp122; tmp143 = tmp121 - tmp122; tmp70 = K707106781 * (tmp66 + tmp69); tmp71 = tmp63 + tmp70; tmp99 = tmp63 - tmp70; tmp126 = tmp124 + tmp125; tmp144 = tmp125 - tmp124; tmp72 = K707106781 * (tmp69 - tmp66); tmp76 = tmp72 - tmp75; tmp100 = tmp75 + tmp72; } { fftw_real tmp18; fftw_real tmp36; fftw_real tmp21; fftw_real tmp37; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp16; fftw_real tmp17; fftw_real tmp19; fftw_real tmp20; ASSERT_ALIGNED_DOUBLE; tmp16 = input[2 * istride]; tmp17 = input[18 * istride]; tmp18 = tmp16 + tmp17; tmp36 = tmp16 - tmp17; tmp19 = input[10 * istride]; tmp20 = input[26 * istride]; tmp21 = tmp19 + tmp20; tmp37 = tmp19 - tmp20; } tmp22 = tmp18 + tmp21; tmp136 = tmp18 - tmp21; tmp38 = (K923879532 * tmp36) - (K382683432 * tmp37); tmp80 = (K382683432 * tmp36) + (K923879532 * tmp37); } { fftw_real tmp25; fftw_real tmp39; fftw_real tmp28; fftw_real tmp40; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp23; fftw_real tmp24; fftw_real tmp26; fftw_real tmp27; ASSERT_ALIGNED_DOUBLE; tmp23 = input[30 * istride]; tmp24 = input[14 * istride]; tmp25 = tmp23 + tmp24; tmp39 = tmp23 - tmp24; tmp26 = input[6 * istride]; tmp27 = input[22 * istride]; tmp28 = tmp26 + tmp27; tmp40 = tmp26 - tmp27; } tmp29 = tmp25 + tmp28; tmp137 = tmp25 - tmp28; tmp41 = (K923879532 * tmp39) + (K382683432 * tmp40); tmp79 = (K382683432 * tmp39) - (K923879532 * tmp40); } { fftw_real tmp46; fftw_real tmp114; fftw_real tmp58; fftw_real tmp115; fftw_real tmp49; fftw_real tmp117; fftw_real tmp52; fftw_real tmp118; fftw_real tmp53; fftw_real tmp55; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp44; fftw_real tmp45; fftw_real tmp56; fftw_real tmp57; ASSERT_ALIGNED_DOUBLE; tmp44 = input[istride]; tmp45 = input[17 * istride]; tmp46 = tmp44 - tmp45; tmp114 = tmp44 + tmp45; tmp56 = input[9 * istride]; tmp57 = input[25 * istride]; tmp58 = tmp56 - tmp57; tmp115 = tmp56 + tmp57; } { fftw_real tmp47; fftw_real tmp48; fftw_real tmp50; fftw_real tmp51; ASSERT_ALIGNED_DOUBLE; tmp47 = input[5 * istride]; tmp48 = input[21 * istride]; tmp49 = tmp47 - tmp48; tmp117 = tmp47 + tmp48; tmp50 = input[29 * istride]; tmp51 = input[13 * istride]; tmp52 = tmp50 - tmp51; tmp118 = tmp50 + tmp51; } tmp116 = tmp114 + tmp115; tmp140 = tmp114 - tmp115; tmp53 = K707106781 * (tmp49 + tmp52); tmp54 = tmp46 + tmp53; tmp96 = tmp46 - tmp53; tmp119 = tmp117 + tmp118; tmp141 = tmp118 - tmp117; tmp55 = K707106781 * (tmp52 - tmp49); tmp59 = tmp55 - tmp58; tmp97 = tmp58 + tmp55; } { fftw_real tmp15; fftw_real tmp30; fftw_real tmp131; fftw_real tmp132; fftw_real tmp133; fftw_real tmp134; ASSERT_ALIGNED_DOUBLE; tmp15 = tmp7 + tmp14; tmp30 = tmp22 + tmp29; tmp131 = tmp15 + tmp30; tmp132 = tmp116 + tmp119; tmp133 = tmp123 + tmp126; tmp134 = tmp132 + tmp133; real_output[8 * real_ostride] = tmp15 - tmp30; imag_output[8 * imag_ostride] = tmp133 - tmp132; real_output[16 * real_ostride] = tmp131 - tmp134; real_output[0] = tmp131 + tmp134; } { fftw_real tmp113; fftw_real tmp129; fftw_real tmp128; fftw_real tmp130; fftw_real tmp120; fftw_real tmp127; ASSERT_ALIGNED_DOUBLE; tmp113 = tmp7 - tmp14; tmp129 = tmp29 - tmp22; tmp120 = tmp116 - tmp119; tmp127 = tmp123 - tmp126; tmp128 = K707106781 * (tmp120 + tmp127); tmp130 = K707106781 * (tmp127 - tmp120); real_output[12 * real_ostride] = tmp113 - tmp128; real_output[4 * real_ostride] = tmp113 + tmp128; imag_output[4 * imag_ostride] = tmp129 + tmp130; imag_output[12 * imag_ostride] = tmp130 - tmp129; } { fftw_real tmp139; fftw_real tmp155; fftw_real tmp149; fftw_real tmp151; fftw_real tmp146; fftw_real tmp150; fftw_real tmp154; fftw_real tmp156; fftw_real tmp138; fftw_real tmp147; ASSERT_ALIGNED_DOUBLE; tmp138 = K707106781 * (tmp136 + tmp137); tmp139 = tmp135 + tmp138; tmp155 = tmp135 - tmp138; tmp147 = K707106781 * (tmp137 - tmp136); tmp149 = tmp147 - tmp148; tmp151 = tmp148 + tmp147; { fftw_real tmp142; fftw_real tmp145; fftw_real tmp152; fftw_real tmp153; ASSERT_ALIGNED_DOUBLE; tmp142 = (K923879532 * tmp140) + (K382683432 * tmp141); tmp145 = (K923879532 * tmp143) - (K382683432 * tmp144); tmp146 = tmp142 + tmp145; tmp150 = tmp145 - tmp142; tmp152 = (K923879532 * tmp141) - (K382683432 * tmp140); tmp153 = (K382683432 * tmp143) + (K923879532 * tmp144); tmp154 = tmp152 + tmp153; tmp156 = tmp153 - tmp152; } real_output[14 * real_ostride] = tmp139 - tmp146; real_output[2 * real_ostride] = tmp139 + tmp146; imag_output[6 * imag_ostride] = tmp149 + tmp150; imag_output[10 * imag_ostride] = tmp150 - tmp149; imag_output[2 * imag_ostride] = tmp151 + tmp154; imag_output[14 * imag_ostride] = tmp154 - tmp151; real_output[10 * real_ostride] = tmp155 - tmp156; real_output[6 * real_ostride] = tmp155 + tmp156; } { fftw_real tmp95; fftw_real tmp111; fftw_real tmp110; fftw_real tmp112; fftw_real tmp102; fftw_real tmp106; fftw_real tmp105; fftw_real tmp107; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp93; fftw_real tmp94; fftw_real tmp108; fftw_real tmp109; ASSERT_ALIGNED_DOUBLE; tmp93 = tmp31 - tmp34; tmp94 = tmp80 + tmp79; tmp95 = tmp93 + tmp94; tmp111 = tmp93 - tmp94; tmp108 = (K831469612 * tmp97) - (K555570233 * tmp96); tmp109 = (K555570233 * tmp99) + (K831469612 * tmp100); tmp110 = tmp108 + tmp109; tmp112 = tmp109 - tmp108; } { fftw_real tmp98; fftw_real tmp101; fftw_real tmp103; fftw_real tmp104; ASSERT_ALIGNED_DOUBLE; tmp98 = (K831469612 * tmp96) + (K555570233 * tmp97); tmp101 = (K831469612 * tmp99) - (K555570233 * tmp100); tmp102 = tmp98 + tmp101; tmp106 = tmp101 - tmp98; tmp103 = tmp41 - tmp38; tmp104 = tmp83 + tmp82; tmp105 = tmp103 - tmp104; tmp107 = tmp104 + tmp103; } real_output[13 * real_ostride] = tmp95 - tmp102; real_output[3 * real_ostride] = tmp95 + tmp102; imag_output[5 * imag_ostride] = tmp105 + tmp106; imag_output[11 * imag_ostride] = tmp106 - tmp105; imag_output[3 * imag_ostride] = tmp107 + tmp110; imag_output[13 * imag_ostride] = tmp110 - tmp107; real_output[11 * real_ostride] = tmp111 - tmp112; real_output[5 * real_ostride] = tmp111 + tmp112; } { fftw_real tmp43; fftw_real tmp91; fftw_real tmp90; fftw_real tmp92; fftw_real tmp78; fftw_real tmp86; fftw_real tmp85; fftw_real tmp87; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp35; fftw_real tmp42; fftw_real tmp88; fftw_real tmp89; ASSERT_ALIGNED_DOUBLE; tmp35 = tmp31 + tmp34; tmp42 = tmp38 + tmp41; tmp43 = tmp35 + tmp42; tmp91 = tmp35 - tmp42; tmp88 = (K980785280 * tmp59) - (K195090322 * tmp54); tmp89 = (K195090322 * tmp71) + (K980785280 * tmp76); tmp90 = tmp88 + tmp89; tmp92 = tmp89 - tmp88; } { fftw_real tmp60; fftw_real tmp77; fftw_real tmp81; fftw_real tmp84; ASSERT_ALIGNED_DOUBLE; tmp60 = (K980785280 * tmp54) + (K195090322 * tmp59); tmp77 = (K980785280 * tmp71) - (K195090322 * tmp76); tmp78 = tmp60 + tmp77; tmp86 = tmp77 - tmp60; tmp81 = tmp79 - tmp80; tmp84 = tmp82 - tmp83; tmp85 = tmp81 - tmp84; tmp87 = tmp84 + tmp81; } real_output[15 * real_ostride] = tmp43 - tmp78; real_output[real_ostride] = tmp43 + tmp78; imag_output[7 * imag_ostride] = tmp85 + tmp86; imag_output[9 * imag_ostride] = tmp86 - tmp85; imag_output[imag_ostride] = tmp87 + tmp90; imag_output[15 * imag_ostride] = tmp90 - tmp87; real_output[9 * real_ostride] = tmp91 - tmp92; real_output[7 * real_ostride] = tmp91 + tmp92; } } fftw_codelet_desc fftw_real2hc_32_desc = { "fftw_real2hc_32", (void (*)()) fftw_real2hc_32, 32, FFTW_FORWARD, FFTW_REAL2HC, 706, 0, (const int *) 0, };
{ "alphanum_fraction": 0.6226023476, "avg_line_length": 29.2914046122, "ext": "c", "hexsha": "fa1abac42f7e74b4c14c5618364288576d2ecd9d", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_32.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_32.c", "max_line_length": 141, "max_stars_count": 9, "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_32.c", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "num_tokens": 4477, "size": 13972 }
// A rectangular block of data of type uint8_t. A transparent block // cache is used for each instance of this class if necessary, so the // image can be much bigger than will fit in memory, and pixels can // still be accessed and written efficiently, provided subsequent // accesses are spatially correlated. A variety of useful methods are // implemented (filtering, subsetting, interpolating, etc.) // // Don't try to access the same instance concurrently. Split your // images up into separate instances if you must parallelize things. // // For many methods, arguments of type ssize_t are used, but are not // allowed to be negative. This is to help prevent people from // shooting themselves in the foor by accidently passing negative // values which don't yield warnings and can't be caught with // assertions. #ifndef UINT8_IMAGE_H #define UINT8_IMAGE_H #ifndef solaris # include <stdint.h> #endif #include "asf_meta.h" #include <stdio.h> #include <sys/types.h> #include <glib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_histogram.h> // sometimes we don't have these - choose conservative values #ifndef SSIZE_MAX #define SSIZE_MAX 32767 #endif #ifndef UINT8_MAX #define UINT8_MAX 255 #endif // Instance structure. Everything here is private and need not be // used or understood by client code, except for the size_x and size_y // fields. typedef struct { size_t size_x, size_y; // Image dimensions. size_t cache_space; // Memory cache space in bytes. size_t cache_area; // Memory cache area in pixels. size_t tile_size; // Tile size in pixels on a side. size_t cache_size_in_tiles; // Number of tiles in cache. size_t tile_count_x; // Number of tiles in image in x direction. size_t tile_count_y; // Number of tiles in image in y direction. size_t tile_count; // Total number of tiles in image. size_t tile_area; // Area of a tile, in pixels. uint8_t *cache; // Memory cache. uint8_t **tile_addresses; // Addresss of individual tiles in the cache. GQueue *tile_queue; // Queue of tile offsets kept in load order. FILE *tile_file; // File with tiles stored contiguously. GString *tile_file_name; // Filename of the tile file } UInt8Image; /////////////////////////////////////////////////////////////////////////////// // // Creating New Instances // /////////////////////////////////////////////////////////////////////////////// // Thaw out a previously frozen instance (produced with // uint8_image_freeze) using data pointed to by file_pointer. Frozen // instances aren't portable between platforms. After thawing // file_pointer points to the data immediately following the data from // the thawed instance (or to the end of the file). UInt8Image * uint8_image_thaw (FILE *file_pointer); // Create a new image filled with zero pixel values. UInt8Image * uint8_image_new (ssize_t size_x, ssize_t size_y); // Create a new image with pixels initialized to value. UInt8Image * uint8_image_new_with_value (ssize_t size_x, ssize_t size_y, uint8_t value); // Create a new image from memory. This pixels are assumed to be // layed out in memory in the usual way, i.e. contiguous rows of // pixels in the x direction are contiguous in memory. UInt8Image * uint8_image_new_from_memory (ssize_t size_x, ssize_t size_y, uint8_t *buffer); // Create a new independent copy of model. UInt8Image * uint8_image_copy (UInt8Image *model); // Form reduced resolution version of the model. The scale_factor // must be positive and odd. The new image will be round ((double) // model->size_x / scale_factor) pixels by round ((double) // model->size_y / scale_factor) pixels. Scaling is performed by // averaging blocks of pixels together, using odd pixel reflection // around the image edges (see the description of the apply_kernel // method). The average for a block of pixels is first computed as a // double precision floating point number, then rounded with the C99 // round() function. The upper and leftmost blocks of pixels averaged // together are always centered at the 0 index in the direction in // question, so reflection is always used for these edges. Whether // reflection is used for the right and lower edges depends on the // relationship between the model dimensions and the scale factor. UInt8Image * uint8_image_new_from_model_scaled (UInt8Image *model, ssize_t scale_factor); // Create a new image by copying the portion of model with upper left // corner at model coordinates (x, y), width size_x, and height // size_y. UInt8Image * uint8_image_new_subimage (UInt8Image *model, ssize_t x, ssize_t y, ssize_t size_x, ssize_t size_y); // Create a new image from data at byte offset in file. The pixel // layout in the file is assumed to be the same as for the // uint8_image_new_from_memory method. The byte order of individual // pixels in the file should be byte_order. UInt8Image * uint8_image_new_from_file (ssize_t size_x, ssize_t size_y, const char *file, off_t offset); // The method is like new_from_file, but takes a file pointer instead // of a file name, and the offset argument is with respect to the // current position in the file_pointer stream. UInt8Image * uint8_image_new_from_file_pointer (ssize_t size_x, ssize_t size_y, FILE *file_pointer, off_t offset); // Form a low quality reduced resolution version of the // original_size_x by original_size_y image in file. The new image // will be size_x by size_y pixels. This method is like new_from_file // method, but gets its data by sampling in each dimension using // bilinear interpolation, and rounding the interpolated values using // the C99 round() routine. This is a decent way of forming quick // thumbnails of images, or of scaling images down just slightly (by a // factor of say 1.5 or less), but not much else. UInt8Image * uint8_image_new_from_file_scaled (ssize_t size_x, ssize_t size_y, ssize_t original_size_x, ssize_t original_size_y, const char *file, off_t offset); // The function that does it all, generating an instance of UInt8Image // from a file and the metadata UInt8Image * uint8_image_new_from_metadata(meta_parameters *meta, const char *file); // For multi-band imagery the previous function needs to be more specific. UInt8Image * uint8_image_band_new_from_metadata(meta_parameters *meta, int band, const char *file); /////////////////////////////////////////////////////////////////////////////// // // Getting and Setting Image Pixels and Regions // /////////////////////////////////////////////////////////////////////////////// // Get pixel at 0-indexed position x, y. A cache is used so pixel // access does not usually involve the hard disk, provided subsequent // pixel lookups are spatially close together. You can probably get // away with trating this function just as if everything was in // memory. For details, see the cache control methods below. // // The x and y arguments should always be positive, ssize_t is used // only so people can't as easily shoot themselves in the foot by // accidently supplying negative arguments which get promoted in some // strange way. uint8_t uint8_image_get_pixel (UInt8Image *self, ssize_t x, ssize_t y); // Set pixel at 0-indexed position x, y to value. A cache is used to // make this fast, as for the uint8_image_get_pixel method. void uint8_image_set_pixel (UInt8Image *self, ssize_t x, ssize_t y, uint8_t value); // Get rectangular image region of size_x, size_y having upper left // corner at x, y and copy it into already allocated buffer. There is // not necessarily any caching help for this method, i.e. it may // always involve disk access and always be slow. void uint8_image_get_region (UInt8Image *self, ssize_t x, ssize_t y, ssize_t size_x, ssize_t size_y, uint8_t *buffer); // This method is analogous to uint8_image_get_region. void uint8_image_set_region (UInt8Image *self, size_t x, size_t y, size_t size_x, size_t size_y, uint8_t *buffer); // Get a full row of pixels, copying the data into already allocated // buffer. This method will be fast on the average for calls with // sequential row numbers. void uint8_image_get_row (UInt8Image *self, size_t row, uint8_t *buffer); // Get a pixel, performing odd reflection at image edges if the pixel // indicies fall outside the image. See the description of the // apply_kernel method for an explanation of reflection. uint8_t uint8_image_get_pixel_with_reflection (UInt8Image *self, ssize_t x, ssize_t y); /////////////////////////////////////////////////////////////////////////////// // // Image Analysis and Statistics // /////////////////////////////////////////////////////////////////////////////// // Default mask value when figuring image stats #define UINT8_IMAGE_DEFAULT_MASK (0.0) // Finds the minimum and maximum pixel values in the image, and the // mean and standard deviation of all pixels. This function considers // every pixel in the image when mask is NAN, otherwise it discounts // all values within .00000000001 of the mask void uint8_image_statistics (UInt8Image *self, uint8_t *min, uint8_t *max, double *mean, double *standard_deviation, gboolean use_mask_value, uint8_t mask_value); // Does the same thing as uint8_image_statistics() except that the // statistics are calculated for a particular band selection within // a UInt8Image which contains multiple bands or channels in sequential // order. Returns 1 on error, otherwise 0 int uint8_image_band_statistics (UInt8Image *self, meta_stats *stats, int line_count, int band_no, gboolean use_mask_value, uint8_t mask_value); // This method works like the statistics method, except values in the // interval [interval_start, interval_end] are not considered at all // for the purposes of determining any of the outputs. void uint8_image_statistics_with_mask_interval (UInt8Image *self, uint8_t *min, uint8_t *max, double *mean, double *standard_deviation, uint8_t interval_start, uint8_t interval_end); // Compute an efficient estimate of the mean and standard deviation of // the pixels in the image, by sampling every stride th pixel in each // dimension, beginning with pixel (0, 0). If the mask is a non-NAN // value, this function will discount all values within .00000000001 // of the mask void uint8_image_approximate_statistics (UInt8Image *self, size_t stride, double *mean, double *standard_deviation, gboolean use_mask_value, uint8_t mask_value); // This method is a logical combination of the // statistics_with_mask_interval and approximate_statistics methods. void uint8_image_approximate_statistics_with_mask_interval (UInt8Image *self, size_t stride, double *mean, double *standard_deviation, uint8_t interval_start, uint8_t interval_end); // Creates a gsl_histogram with bin_count bins evenly spaced over the // interval [min, max]. This function considers every pixel in the // image. gsl_histogram * uint8_image_gsl_histogram (UInt8Image *self, double min, double max, size_t bin_count); /////////////////////////////////////////////////////////////////////////////// // // Kernels, Interpolation, and Sampling // /////////////////////////////////////////////////////////////////////////////// // Apply kernel centerd at pixel x, y and return the value. The // kernel matrix must be have equal odd dimensions. The values in the // kernel are multiplied by the pixels, and the sum of the products // returned. When part of the kernel would fall outside the image // extents, the values used for the out-of-image pixels are the mirror // images of the corresponding in-image pixels, with the edge pixels // not duplicated, i.e. reflection about the middle of the edge pixels // is used. double uint8_image_apply_kernel (UInt8Image *self, ssize_t x, ssize_t y, gsl_matrix *kern); // Type used to specify whether disk files should be in big or little // endian byte order. // Sample method types. These dictate how nearby pixels are // considered when we want to find the approximate value for a point // which falls between pixel indicies. typedef enum { // Nearest pixel. UINT8_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR, // Linearly weited average of four nearest pixels UINT8_IMAGE_SAMPLE_METHOD_BILINEAR, // Bicubic spline interpolation (which consideres the nearest 16 pixels). UINT8_IMAGE_SAMPLE_METHOD_BICUBIC } uint8_image_sample_method_t; double uint8_image_sample (UInt8Image *self, double x, double y, uint8_image_sample_method_t sample_method); /////////////////////////////////////////////////////////////////////////////// // // Comparing Images // /////////////////////////////////////////////////////////////////////////////// // Return true iff self and other have identical sizes and pixels. gboolean uint8_image_equals (UInt8Image *self, UInt8Image *other); /////////////////////////////////////////////////////////////////////////////// // // Manipulating Images // /////////////////////////////////////////////////////////////////////////////// // Flip an image about a horizontal line through the center of the image void uint8_image_flip_y(UInt8Image *self); // Flip an image about a vertical line through the center of the image void uint8_image_flip_x(UInt8Image *self); /////////////////////////////////////////////////////////////////////////////// // // Storing Images in Files // /////////////////////////////////////////////////////////////////////////////// // Store instance self at position pointed to by file_pointer, for // later retrieval using uint8_image_thaw. The serialized version of // self is not portable between platforms. void uint8_image_freeze (UInt8Image *self, FILE *file_pointer); // Store image pixels in file. The image is stored in the usual // order, i.e. contiguous rows of pixels in the x direction are stored // contiguously in memory. Individual pixels are stored in byte order // byte_order. Returns 0 on success, nonzero on error. int uint8_image_store (UInt8Image *self, const char *file); int uint8_image_store_ext(UInt8Image *self, const char *file, int append_flag); int uint8_image_band_store(UInt8Image *self, const char *file, meta_parameters *meta, int append_flag); /////////////////////////////////////////////////////////////////////////////// // // Exporting Images in Various Image File Formats // /////////////////////////////////////////////////////////////////////////////// // Export image to fila as a gray scaled jpeg image, with largest // dimension no larger than max_dimension. The max_dimension argument // must be less than or equal to the largest dimension of the image. // The image may be scaled st its largest dimension is considerably // less than max_dimension. Scaling is performed by averaging blocks // of pixels together, using odd pixel reflection around the image // edges (see the description of the apply_kernel method), and // rounding pixel averages with the C99 round() routine. If // use_mask_value is true, then in determining the image statistics // (mean and standard deviation), values equal to mask are not // considered. This routine slurps the whole image into memory, so // beware. Returns 0 on success, nonzero on error. int uint8_image_export_as_jpeg (UInt8Image *self, const char *file, size_t max_dimension, gboolean use_mask_value, uint8_t mask_value); /////////////////////////////////////////////////////////////////////////////// // // Controlling Image Data Caching // // It probably isn't necessary to use these methods. They are // provided largely to make it clear how the cache works. The major // tunable parameter is the size of the in-memory cache to use. // // When a new image is created, the following steps are performed: // // 1. The image is divided up into square tiles st two full rows // or columns of tiles will fit in the memory cache. // // 2. A copy of the image is created on disk with the memory // layout rearranged st individual tiles are contiguous in // memory. This allows tiles to be quickly retrieved later. // // When a pixel is accessed (read or set), the following happens: // // 1. If the pixel is in a tile already loaded into the cache, // it is simply fetched or set. // // 2. Otherwise, the tile containing the pixel is loaded, // possibly displacing an already loaded tile, and then the // pixel is fetched or set. The tile displaced is the one // loaded longest ago (there is no most-recently-accessed // heuristic, as this would make pixel access too slow). // // Thus, using a larger memory cache will result in larger tiles being // used, and fewer tile loads being needed. In general, the default // behavior is pretty good, but if you know will be performing lots of // widely (but not too widely) scattered accesses, you might want to // make it bigger. // /////////////////////////////////////////////////////////////////////////////// // Get the image memory cache size setting, in bytes. Note that this // is the memory cache used per image, not the class-wide cache usage. // If you will have a lot of objects instantiated simultaneously, you // may find it necessary to use a smaller cache for each image. size_t uint8_image_get_cache_size (UInt8Image *self); // Set the image memory cache to size bytes. Changing the cache size // requires the tiling to be recomputed, the on-disk tile cache to be // regenerated, and the in memory cache to be flushed, so its slow. void uint8_image_set_cache_size (UInt8Image *self, size_t size); /////////////////////////////////////////////////////////////////////////////// // // Freeing Instances // /////////////////////////////////////////////////////////////////////////////// // Destroy self. void uint8_image_free (UInt8Image *self); #endif // #ifndef UINT8_IMAGE_H
{ "alphanum_fraction": 0.6859852476, "avg_line_length": 41.5460829493, "ext": "h", "hexsha": "4bf7817108e59c08f3972f62e4eb8b6f3ddd2710", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_raster/uint8_image.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_raster/uint8_image.h", "max_line_length": 79, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_raster/uint8_image.h", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 3969, "size": 18031 }
#include <math.h> #include <stdlib.h> #include <gsl/gsl_integration.h> //#include <stdio.h> double f(double d, void* fdata){ double * double_fdata = (double*) fdata; double par_obs = double_fdata[0]; double var_par = double_fdata[1]; double DM = double_fdata[2]; double var_DM = double_fdata[3]; double par_offset = double_fdata[4]; double L = double_fdata[5]; //printf("Data = %f, %f, %f, %f, %f\n", d, par_corrected, var_par, DM, var_DM); return pow(d, 2) * exp(-0.5 * (2*d/L + pow(par_obs - (1./d + par_offset), 2.)/var_par + pow(DM - (5*log10(d) - 5), 2.)/var_DM)); } double integrate_likelihood(const double xmin, const double xmax, double *fdata, double rel_tolerance) { gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); gsl_function F; F.function = &f; F.params = fdata; double result, err; gsl_integration_qag (&F, xmin, xmax, 0, rel_tolerance, 1000, 1, w, &result, &err); gsl_integration_workspace_free (w); return result; }
{ "alphanum_fraction": 0.652173913, "avg_line_length": 29.5714285714, "ext": "c", "hexsha": "39a501157c9988963fe9b843ae8d77d45887f03e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-07-12T10:58:47.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-12T10:58:47.000Z", "max_forks_repo_head_hexsha": "83463b58d1518f7bb970d7975092917eb2304229", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "vickyscowcroft/bayesian_pl_fitting", "max_forks_repo_path": "likelihood_function_quad.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "83463b58d1518f7bb970d7975092917eb2304229", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "vickyscowcroft/bayesian_pl_fitting", "max_issues_repo_path": "likelihood_function_quad.c", "max_line_length": 132, "max_stars_count": 2, "max_stars_repo_head_hexsha": "83463b58d1518f7bb970d7975092917eb2304229", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vickyscowcroft/bayesian_pl_fitting", "max_stars_repo_path": "likelihood_function_quad.c", "max_stars_repo_stars_event_max_datetime": "2021-06-16T10:51:28.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:10:50.000Z", "num_tokens": 317, "size": 1035 }
/* Siconos-Numerics, Copyright INRIA 2005-2018. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr */ #ifndef SiconosLAPACKE_H #define SiconosLAPACKE_H #include "SiconosBlas.h" #include <stdlib.h> #include <assert.h> #include <stdio.h> // -------- Headers and routines naming conventions for the different Lapack implementations -------- // --- Intel MKL Header --- #if defined(HAS_MKL_LAPACKE) #include <mkl_lapacke.h> #else // Standard lapacke header #include <lapacke.h> #endif // Name of the routines #define LAPACK_NAME(N) LAPACKE_##N #define LA_TRANS 'T' #define LA_NOTRANS 'N' #define LA_UP 'U' #define LA_LO 'L' #define LA_NONUNIT 'N' #define LA_UNIT 'U' #define INTEGER(X) X #define INTEGERP(X) X #define CHAR(X) X #ifndef lapack_int #define lapack_int int #endif // --- DGESVD --- #if defined(HAS_LAPACK_DGESVD) #define WRAP_DGESVD(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,INFO) \ INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12) #else #define WRAP_DGESVD(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,INFO) \ fprintf(stderr, "Your lapack version misses dgesvd function.\n"); #endif // --- DGETRS --- #define WRAP_DGETRS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO) \ INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8) // --- DGESV --- #define WRAP_DGESV(F,A1,A2,A3,A4,A5,A6,A7,INFO) \ INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7) // --- DGELS --- #if defined(HAS_LAPACK_DGELS) #define WRAP_DGELS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO) \ INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8) #else #define WRAP_DGELS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO) \ fprintf(stderr, "Your lapack version misses dgels function.\n"); #endif // --- DGETRI --- #define WRAP_DGETRI(F,A1,A2,A3,A4,INFO) \ INFO = F(CblasColMajor,A1,A2,A3,A4) // --- DPOTRF --- #define WRAP_DPOTRF(F,A1,A2,A3,A4,INFO) \ INFO = F(CblasColMajor,A1,A2,A3,A4) // --- DGETRF --- #define WRAP_DGETRF(F,A1,A2,A3,A4,A5,INFO) \ INFO = F(CblasColMajor,A1,A2,A3,A4,A5) // --- DTRTRS --- #if defined(HAS_LAPACK_DTRTRS) #define WRAP_DTRTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,INFO) \ INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8,A9) #else #define WRAP_DTRTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,INFO) \ fprintf(stderr, "Your lapack version misses dtrtrs function.\n"); #endif #endif // SICONOSLAPACKE_H
{ "alphanum_fraction": 0.6921870097, "avg_line_length": 30.6442307692, "ext": "h", "hexsha": "9e9b01811c894308dfa7e8791f0df251ec220c8c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_path": "externals/blas_lapack/SiconosLapacke.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1072, "size": 3187 }
/* rng/ranmar.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_rng.h> /* This is the RANMAR lagged fibonacci generator of Marsaglia, Zaman and Tsang. The sequence is a series of 24-bit integers, x_n, x_n = (y_n - c_n + 2^24) mod 2^24 where, y_n = (y_{n-97) - y_{n-33} + 2^24) mod 2^24 c_n = (c_{n-1} - 7654321 + 2^24 - 3) mod (2^24 - 3) The period of this generator is 2^144. The generator provides about 900 million different subsequences each of length O(10^30). Thus each seed up to 900,000,000 gives an independent sequence. Although it was good in its day this generator now has known statistical defects and has been superseded by RANLUX. From: F. James, "A Review of Pseudorandom number generators", Computer Physics Communications 60, 329 (1990). G. Marsaglia, A. Zaman and W.W. Tsang, Stat. Prob. Lett. 9, 35 (1990) */ static inline unsigned long int ranmar_get (void *vstate); static double ranmar_get_double (void *vstate); static void ranmar_set (void *state, unsigned long int s); static const unsigned long int two24 = 16777216; /* 2^24 */ typedef struct { unsigned int i; unsigned int j; long int carry; unsigned long int u[97]; } ranmar_state_t; static inline unsigned long int ranmar_get (void *vstate) { ranmar_state_t *state = (ranmar_state_t *) vstate; unsigned int i = state->i; unsigned int j = state->j; long int carry = state->carry; long int delta = state->u[i] - state->u[j]; if (delta < 0) delta += two24 ; state->u[i] = delta; if (i == 0) { i = 96; } else { i--; } state->i = i; if (j == 0) { j = 96; } else { j--; } state->j = j; carry += - 7654321 ; if (carry < 0) carry += two24 - 3; state->carry = carry ; delta += - carry ; if (delta < 0) delta += two24 ; return delta; } static double ranmar_get_double (void *vstate) { return ranmar_get (vstate) / 16777216.0 ; } static void ranmar_set (void *vstate, unsigned long int s) { ranmar_state_t *state = (ranmar_state_t *) vstate; unsigned long int ij = s / 30082 ; unsigned long int kl = s % 30082 ; int i = (ij / 177) % 177 + 2 ; int j = (ij % 177) + 2 ; int k = (kl / 169) % 178 + 1 ; int l = (kl % 169) ; int a, b; for (a = 0; a < 97; a++) { unsigned long int sum = 0 ; unsigned long int t = two24 ; for (b = 0; b < 24; b++) { unsigned long int m = (((i * j) % 179) * k) % 179 ; i = j ; j = k ; k = m ; l = (53 * l + 1) % 169 ; t >>= 1 ; if ((l * m) % 64 >= 32) sum += t ; } state->u[a] = sum ; } state->i = 96; state->j = 32; state->carry = 362436 ; } static const gsl_rng_type ranmar_type = {"ranmar", /* name */ 0x00ffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (ranmar_state_t), &ranmar_set, &ranmar_get, &ranmar_get_double}; const gsl_rng_type *gsl_rng_ranmar = &ranmar_type;
{ "alphanum_fraction": 0.6166226913, "avg_line_length": 21.7816091954, "ext": "c", "hexsha": "81c1f1e4e665b30aa055e0cca4dd58c7d4edef00", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/rng/ranmar.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/ranmar.c", "max_line_length": 76, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/ranmar.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 1230, "size": 3790 }
/* linalg/tridiag.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2002, 2004 Gerard Jungman, * Brian Gough, David Necas * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include "tridiag.h" #include <gsl/gsl_linalg.h> /* for description of method see [Engeln-Mullges + Uhlig, p. 92] * * diag[0] offdiag[0] 0 ..... * offdiag[0] diag[1] offdiag[1] ..... * 0 offdiag[1] diag[2] * 0 0 offdiag[2] ..... */ static int solve_tridiag( const double diag[], size_t d_stride, const double offdiag[], size_t o_stride, const double b[], size_t b_stride, double x[], size_t x_stride, size_t N) { int status; double *gamma = (double *) malloc (N * sizeof (double)); double *alpha = (double *) malloc (N * sizeof (double)); double *c = (double *) malloc (N * sizeof (double)); double *z = (double *) malloc (N * sizeof (double)); if (gamma == 0 || alpha == 0 || c == 0 || z == 0) { status = GSL_ENOMEM; } else { size_t i, j; /* Cholesky decomposition A = L.D.L^t lower_diag(L) = gamma diag(D) = alpha */ alpha[0] = diag[0]; gamma[0] = offdiag[0] / alpha[0]; for (i = 1; i < N - 1; i++) { alpha[i] = diag[d_stride * i] - offdiag[o_stride*(i - 1)] * gamma[i - 1]; gamma[i] = offdiag[o_stride * i] / alpha[i]; } if (N > 1) { alpha[N - 1] = diag[d_stride * (N - 1)] - offdiag[o_stride*(N - 2)] * gamma[N - 2]; } /* update RHS */ z[0] = b[0]; for (i = 1; i < N; i++) { z[i] = b[b_stride * i] - gamma[i - 1] * z[i - 1]; } for (i = 0; i < N; i++) { c[i] = z[i] / alpha[i]; } /* backsubstitution */ x[x_stride * (N - 1)] = c[N - 1]; if (N >= 2) { for (i = N - 2, j = 0; j <= N - 2; j++, i--) { x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)]; } } status = GSL_SUCCESS; } if (z != 0) free (z); if (c != 0) free (c); if (alpha != 0) free (alpha); if (gamma != 0) free (gamma); return status; } /* plain gauss elimination, only not bothering with the zeroes * * diag[0] abovediag[0] 0 ..... * belowdiag[0] diag[1] abovediag[1] ..... * 0 belowdiag[1] diag[2] * 0 0 belowdiag[2] ..... */ static int solve_tridiag_nonsym( const double diag[], size_t d_stride, const double abovediag[], size_t a_stride, const double belowdiag[], size_t b_stride, const double rhs[], size_t r_stride, double x[], size_t x_stride, size_t N) { int status; double *alpha = (double *) malloc (N * sizeof (double)); double *z = (double *) malloc (N * sizeof (double)); if (alpha == 0 || z == 0) { status = GSL_ENOMEM; } else { size_t i, j; /* Bidiagonalization (eliminating belowdiag) & rhs update diag' = alpha rhs' = z */ alpha[0] = diag[0]; z[0] = rhs[0]; for (i = 1; i < N; i++) { const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1]; alpha[i] = diag[d_stride*i] - t*abovediag[a_stride*(i - 1)]; z[i] = rhs[r_stride*i] - t*z[i-1]; /* FIXME!!! */ if (alpha[i] == 0) { status = GSL_EZERODIV; goto solve_tridiag_nonsym_END; } } /* backsubstitution */ x[x_stride * (N - 1)] = z[N - 1]/alpha[N - 1]; if (N >= 2) { for (i = N - 2, j = 0; j <= N - 2; j++, i--) { x[x_stride * i] = (z[i] - abovediag[a_stride*i] * x[x_stride * (i + 1)])/alpha[i]; } } status = GSL_SUCCESS; } solve_tridiag_nonsym_END: if (z != 0) free (z); if (alpha != 0) free (alpha); return status; } /* for description of method see [Engeln-Mullges + Uhlig, p. 96] * * diag[0] offdiag[0] 0 ..... offdiag[N-1] * offdiag[0] diag[1] offdiag[1] ..... * 0 offdiag[1] diag[2] * 0 0 offdiag[2] ..... * ... ... * offdiag[N-1] ... * */ static int solve_cyc_tridiag( const double diag[], size_t d_stride, const double offdiag[], size_t o_stride, const double b[], size_t b_stride, double x[], size_t x_stride, size_t N) { int status; double * delta = (double *) malloc (N * sizeof (double)); double * gamma = (double *) malloc (N * sizeof (double)); double * alpha = (double *) malloc (N * sizeof (double)); double * c = (double *) malloc (N * sizeof (double)); double * z = (double *) malloc (N * sizeof (double)); if (delta == 0 || gamma == 0 || alpha == 0 || c == 0 || z == 0) { status = GSL_ENOMEM; } else { size_t i, j; double sum = 0.0; /* factor */ if (N == 1) { x[0] = b[0] / diag[0]; return GSL_SUCCESS; } alpha[0] = diag[0]; gamma[0] = offdiag[0] / alpha[0]; delta[0] = offdiag[o_stride * (N-1)] / alpha[0]; for (i = 1; i < N - 2; i++) { alpha[i] = diag[d_stride * i] - offdiag[o_stride * (i-1)] * gamma[i - 1]; gamma[i] = offdiag[o_stride * i] / alpha[i]; delta[i] = -delta[i - 1] * offdiag[o_stride * (i-1)] / alpha[i]; } for (i = 0; i < N - 2; i++) { sum += alpha[i] * delta[i] * delta[i]; } alpha[N - 2] = diag[d_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * gamma[N - 3]; gamma[N - 2] = (offdiag[o_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * delta[N - 3]) / alpha[N - 2]; alpha[N - 1] = diag[d_stride * (N - 1)] - sum - alpha[(N - 2)] * gamma[N - 2] * gamma[N - 2]; /* update */ z[0] = b[0]; for (i = 1; i < N - 1; i++) { z[i] = b[b_stride * i] - z[i - 1] * gamma[i - 1]; } sum = 0.0; for (i = 0; i < N - 2; i++) { sum += delta[i] * z[i]; } z[N - 1] = b[b_stride * (N - 1)] - sum - gamma[N - 2] * z[N - 2]; for (i = 0; i < N; i++) { c[i] = z[i] / alpha[i]; } /* backsubstitution */ x[x_stride * (N - 1)] = c[N - 1]; x[x_stride * (N - 2)] = c[N - 2] - gamma[N - 2] * x[x_stride * (N - 1)]; if (N >= 3) { for (i = N - 3, j = 0; j <= N - 3; j++, i--) { x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)] - delta[i] * x[x_stride * (N - 1)]; } } status = GSL_SUCCESS; } if (z != 0) free (z); if (c != 0) free (c); if (alpha != 0) free (alpha); if (gamma != 0) free (gamma); if (delta != 0) free (delta); return status; } /* solve following system w/o the corner elements and then use * Sherman-Morrison formula to compensate for them * * diag[0] abovediag[0] 0 ..... belowdiag[N-1] * belowdiag[0] diag[1] abovediag[1] ..... * 0 belowdiag[1] diag[2] * 0 0 belowdiag[2] ..... * ... ... * abovediag[N-1] ... */ static int solve_cyc_tridiag_nonsym( const double diag[], size_t d_stride, const double abovediag[], size_t a_stride, const double belowdiag[], size_t b_stride, const double rhs[], size_t r_stride, double x[], size_t x_stride, size_t N) { int status; double *alpha = (double *) malloc (N * sizeof (double)); double *zb = (double *) malloc (N * sizeof (double)); double *zu = (double *) malloc (N * sizeof (double)); double *w = (double *) malloc (N * sizeof (double)); double beta; if (alpha == 0 || zb == 0 || zu == 0 || w == 0) { status = GSL_ENOMEM; } else { /* Bidiagonalization (eliminating belowdiag) & rhs update diag' = alpha rhs' = zb rhs' for Aq=u is zu */ zb[0] = rhs[0]; if (diag[0] != 0) beta = -diag[0]; else beta = 1; { const double q = 1 - abovediag[0]*belowdiag[0]/(diag[0]*diag[d_stride]); if (fabs(q/beta) > 0.5 && fabs(q/beta) < 2) { beta *= (fabs(q/beta) < 1) ? 0.5 : 2; } } zu[0] = beta; alpha[0] = diag[0] - beta; { size_t i; for (i = 1; i+1 < N; i++) { const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1]; alpha[i] = diag[d_stride*i] - t*abovediag[a_stride*(i - 1)]; zb[i] = rhs[r_stride*i] - t*zb[i-1]; zu[i] = -t*zu[i-1]; /* FIXME!!! */ if (alpha[i] == 0) { status = GSL_EZERODIV; goto solve_cyc_tridiag_nonsym_END; } } } { const size_t i = N-1; const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1]; alpha[i] = diag[d_stride*i] - abovediag[a_stride*i]*belowdiag[b_stride*i]/beta - t*abovediag[a_stride*(i - 1)]; zb[i] = rhs[r_stride*i] - t*zb[i-1]; zu[i] = abovediag[a_stride*i] - t*zu[i-1]; /* FIXME!!! */ if (alpha[i] == 0) { status = GSL_EZERODIV; goto solve_cyc_tridiag_nonsym_END; } } /* backsubstitution */ { size_t i, j; w[N-1] = zu[N-1]/alpha[N-1]; x[N-1] = zb[N-1]/alpha[N-1]; for (i = N - 2, j = 0; j <= N - 2; j++, i--) { w[i] = (zu[i] - abovediag[a_stride*i] * w[i+1])/alpha[i]; x[i*x_stride] = (zb[i] - abovediag[a_stride*i] * x[x_stride*(i + 1)])/alpha[i]; } } /* Sherman-Morrison */ { const double vw = w[0] + belowdiag[b_stride*(N - 1)]/beta * w[N-1]; const double vx = x[0] + belowdiag[b_stride*(N - 1)]/beta * x[x_stride*(N - 1)]; /* FIXME!!! */ if (vw + 1 == 0) { status = GSL_EZERODIV; goto solve_cyc_tridiag_nonsym_END; } { size_t i; for (i = 0; i < N; i++) x[i] -= vx/(1 + vw)*w[i]; } } status = GSL_SUCCESS; } solve_cyc_tridiag_nonsym_END: if (zb != 0) free (zb); if (zu != 0) free (zu); if (w != 0) free (w); if (alpha != 0) free (alpha); return status; } int gsl_linalg_solve_symm_tridiag( const gsl_vector * diag, const gsl_vector * offdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size) { GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN); } else if (offdiag->size != rhs->size-1) { GSL_ERROR ("size of offdiag must match rhs-1", GSL_EBADLEN); } else if (solution->size != rhs->size) { GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN); } else { return solve_tridiag(diag->data, diag->stride, offdiag->data, offdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } } int gsl_linalg_solve_tridiag( const gsl_vector * diag, const gsl_vector * abovediag, const gsl_vector * belowdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size) { GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN); } else if (abovediag->size != rhs->size-1) { GSL_ERROR ("size of abovediag must match rhs-1", GSL_EBADLEN); } else if (belowdiag->size != rhs->size-1) { GSL_ERROR ("size of belowdiag must match rhs-1", GSL_EBADLEN); } else if (solution->size != rhs->size) { GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN); } else { return solve_tridiag_nonsym(diag->data, diag->stride, abovediag->data, abovediag->stride, belowdiag->data, belowdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } } int gsl_linalg_solve_symm_cyc_tridiag( const gsl_vector * diag, const gsl_vector * offdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size) { GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN); } else if (offdiag->size != rhs->size) { GSL_ERROR ("size of offdiag must match rhs", GSL_EBADLEN); } else if (solution->size != rhs->size) { GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN); } else if (diag->size < 3) { GSL_ERROR ("size of cyclic system must be 3 or more", GSL_EBADLEN); } else { return solve_cyc_tridiag(diag->data, diag->stride, offdiag->data, offdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } } int gsl_linalg_solve_cyc_tridiag( const gsl_vector * diag, const gsl_vector * abovediag, const gsl_vector * belowdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size) { GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN); } else if (abovediag->size != rhs->size) { GSL_ERROR ("size of abovediag must match rhs", GSL_EBADLEN); } else if (belowdiag->size != rhs->size) { GSL_ERROR ("size of belowdiag must match rhs", GSL_EBADLEN); } else if (solution->size != rhs->size) { GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN); } else if (diag->size < 3) { GSL_ERROR ("size of cyclic system must be 3 or more", GSL_EBADLEN); } else { return solve_cyc_tridiag_nonsym(diag->data, diag->stride, abovediag->data, abovediag->stride, belowdiag->data, belowdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } }
{ "alphanum_fraction": 0.4900990099, "avg_line_length": 27.1019677996, "ext": "c", "hexsha": "485fdcbbbcc4be188d7a9319a52437c4b660d2c3", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/linalg/tridiag.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/linalg/tridiag.c", "max_line_length": 111, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/linalg/tridiag.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 4706, "size": 15150 }
/* * author: Achim Gaedke * created: January 2002 * file: pygsl/src/multiminmodule.c * $Id: multimin.c,v 1.6 2008/10/25 20:45:04 schnizer Exp $ */ #include <pygsl/solver.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multimin.h> #include "multiminmodule_doc.h" const char * filename = __FILE__; PyObject *module = NULL; /* * I have two different types to minimize and I am too lazy to implement the same * twice. Therefore I use unions and add a flag to the minimizer for the type */ /* The Callbacks */ double PyGSL_multimin_function_f(const gsl_vector* x, void* params) { double result; int flag; int i; FUNC_MESS_BEGIN(); PyGSL_solver *min_o; min_o = (PyGSL_solver *) params; assert(PyGSL_solver_check(min_o)); for(i = 0; i<x->size; i++){ DEBUG_MESS(2, "Got a x[%d] of %f", i, gsl_vector_get(x, i)); } assert(min_o->mstatic->n_cbs >= 1); flag = PyGSL_function_wrap_On_O(x, min_o->cbs[0], min_o->args, &result, NULL, x->size, __FUNCTION__); if (flag!= GSL_SUCCESS){ result = gsl_nan(); if(min_o->isset == 1) longjmp(min_o->buffer,flag); } DEBUG_MESS(2, "Got a result of %f", result); FUNC_MESS_END(); return result; } void PyGSL_multimin_function_df(const gsl_vector* x, void* params, gsl_vector *df) { int flag, i; PyGSL_solver *min_o; min_o = (PyGSL_solver *) params; FUNC_MESS_BEGIN(); assert(PyGSL_solver_check(min_o)); for(i = 0; i<x->size; i++){ DEBUG_MESS(2, "Got a x[%d] of %f", i, gsl_vector_get(x, i)); } assert(min_o->mstatic->n_cbs >= 2); flag = PyGSL_function_wrap_Op_On(x, df, min_o->cbs[1], min_o->args, x->size, x->size, __FUNCTION__); for(i = 0; i<df->size; i++){ DEBUG_MESS(2, "Got df x[%d] of %f", i, gsl_vector_get(df, i)); } if(flag!=GSL_SUCCESS){ if(min_o->isset == 1) longjmp(min_o->buffer,flag); } FUNC_MESS_END(); } void PyGSL_multimin_function_fdf(const gsl_vector* x, void* params, double *f, gsl_vector *df) { int flag, i; PyGSL_solver *min_o; FUNC_MESS_BEGIN(); min_o = (PyGSL_solver *) params; assert(PyGSL_solver_check(min_o)); for(i = 0; i<x->size; i++){ DEBUG_MESS(2, "Got a x[%d] of %f", i, gsl_vector_get(x, i)); } assert(min_o->mstatic->n_cbs >= 3); flag = PyGSL_function_wrap_On_O(x, min_o->cbs[2], min_o->args, f, df, x->size, __FUNCTION__); DEBUG_MESS(2, "Got a result of %f", *f); for(i = 0; i<df->size; i++){ DEBUG_MESS(2, "Got df x[%d] of %f", i, gsl_vector_get(df, i)); } if (flag!= GSL_SUCCESS){ *f = gsl_nan(); if(min_o->isset == 1) longjmp(min_o->buffer,flag); } FUNC_MESS_END(); return; } static PyObject* PyGSL_multimin_set_f(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) { PyObject* func = NULL, * args = Py_None, * x = NULL, * steps = NULL; PyArrayObject * xa = NULL, * stepsa = NULL; int n=0, flag=GSL_EFAILED; PyGSL_array_index_t stride_recalc; gsl_vector_view gsl_x; gsl_vector_view gsl_steps; gsl_multimin_function * c_sys = NULL; static const char *kwlist[] = {"f", "x0", "args", "steps", NULL}; FUNC_MESS_BEGIN(); assert(PyGSL_solver_check(self)); if (self->solver == NULL) { pygsl_error("Got a NULL Pointer of min.f", filename, __LINE__ - 3, GSL_EFAULT); return NULL; } assert(pyargs); /* arguments PyFunction, Parameters, start Vector, step Vector */ if (0==PyArg_ParseTupleAndKeywords(pyargs,kw,"OOOO", (char **)kwlist, &func, &x,&args,&steps)) return NULL; if(!PyCallable_Check(func)){ pygsl_error("First argument must be callable", filename, __LINE__ - 3, GSL_EBADFUNC); return NULL; } n=self->problem_dimensions[0]; xa = PyGSL_vector_check(x, n, PyGSL_DARRAY_INPUT(4), &stride_recalc, NULL); if (xa == NULL){ PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1); goto fail; } gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]); stepsa = PyGSL_vector_check(steps, n, PyGSL_DARRAY_INPUT(5), &stride_recalc, NULL); if (stepsa == NULL){ PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1); goto fail; } gsl_steps = gsl_vector_view_array_with_stride((double *)(stepsa->data), stride_recalc, stepsa->dimensions[0]); if (self->c_sys != NULL) { /* free the previous function and args */ c_sys = self->c_sys; } else { /* allocate function space */ c_sys=calloc(1, sizeof(gsl_multimin_function)); if (c_sys == NULL) { pygsl_error("Could not allocate the object for the minimizer function", filename, __LINE__ - 3, GSL_ENOMEM); goto fail; } } DEBUG_MESS(3, "Everything allocated args = %p", args); /* add new function and parameters */ if(PyGSL_solver_func_set(self, args, func, NULL, NULL) != GSL_SUCCESS) goto fail; /* initialize the function struct */ c_sys->n=n; c_sys->f=PyGSL_multimin_function_f; c_sys->params=(void*)self; DEBUG_MESS(3, "Setting jmp buffer isset = % d", self->isset); if((flag = setjmp(self->buffer)) == 0){ self->isset = 1; flag = gsl_multimin_fminimizer_set(self->solver,c_sys, &gsl_x.vector, &gsl_steps.vector); if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){ goto fail; } } else { goto fail; } DEBUG_MESS(4, "Set evaluated. flag = %d", flag); self->c_sys = c_sys; Py_DECREF(xa); Py_DECREF(stepsa); self->set_called = 1; Py_INCREF(Py_None); self->isset = 0; FUNC_MESS_END(); return Py_None; fail: FUNC_MESS("Fail"); PyGSL_ERROR_FLAG(flag); self->isset = 0; Py_XDECREF(xa); Py_XDECREF(stepsa); return NULL; } static PyObject* PyGSL_multimin_set_fdf(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) { PyObject * f = NULL, * df = NULL, * fdf = NULL, * args = Py_None, * x = NULL; PyArrayObject * xa = NULL; int n=0, flag=GSL_EFAILED; PyGSL_array_index_t stride_recalc=-1; double step=0.01, tol=1e-4; gsl_vector_view gsl_x; gsl_multimin_function_fdf * c_sys; static const char *kwlist[] = {"f", "df", "fdf", "x0", "args", "step", "tol", NULL}; FUNC_MESS_BEGIN(); assert(PyGSL_solver_check(self)); if (self->solver == NULL) { pygsl_error("Got a NULL Pointer of min.fdf", filename, __LINE__ - 3, GSL_EFAULT); return NULL; } /* arguments PyFunction, Parameters, start Vector, step Vector */ if (0==PyArg_ParseTupleAndKeywords(pyargs, kw, "OOOO|Odd", (char **)kwlist, &f, &df, &fdf, &x, &args, &step, &tol)) return NULL; n=self->problem_dimensions[0]; xa = PyGSL_vector_check(x, n, PyGSL_DARRAY_INPUT(4), &stride_recalc, NULL); if (xa == NULL){ PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1); goto fail; } gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]); if (self->c_sys != NULL) { /* free the previous function and args */ c_sys = self->c_sys; } else { /* allocate function space */ c_sys=malloc(sizeof(gsl_multimin_function_fdf)); if (c_sys==NULL) { pygsl_error("Could not allocate the object for the minimizer function", filename, __LINE__ - 3, GSL_ENOMEM); goto fail; } } if(PyGSL_solver_func_set(self, args, f, df, fdf) != GSL_SUCCESS) goto fail; /* initialize the function struct */ c_sys->n=n; c_sys->f =PyGSL_multimin_function_f; c_sys->df =PyGSL_multimin_function_df; c_sys->fdf=PyGSL_multimin_function_fdf; c_sys->params=(void*)self; if((flag = setjmp(self->buffer)) == 0){ self->isset = 1; flag = gsl_multimin_fdfminimizer_set(self->solver, c_sys, &gsl_x.vector, step, tol); if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){ goto fail; } }else{ goto fail; } self->c_sys = c_sys; self->isset = 0; Py_DECREF(xa); self->set_called = 1; Py_INCREF(Py_None); FUNC_MESS_END(); return Py_None; fail: PyGSL_ERROR_FLAG(flag); self->isset = 0; Py_XDECREF(xa); return NULL; } static PyObject* PyGSL_multimin_dx(PyGSL_solver *self, PyObject *args) { return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multimin_fdfminimizer_dx); } static PyObject* PyGSL_multimin_gradient(PyGSL_solver *self, PyObject *args) { return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multimin_fdfminimizer_gradient); } static PyObject* PyGSL_multimin_f_x(PyGSL_solver *self, PyObject *args) { return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multimin_fminimizer_x); } static PyObject* PyGSL_multimin_fdf_x(PyGSL_solver *self, PyObject *args) { return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multimin_fdfminimizer_x); } static PyObject* PyGSL_multimin_f_minimum(PyGSL_solver *self, PyObject *args) { return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_multimin_fminimizer_minimum); } static PyObject* PyGSL_multimin_fdf_minimum(PyGSL_solver *self, PyObject *args) { return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_multimin_fdfminimizer_minimum); } static PyObject* PyGSL_multimin_f_size(PyGSL_solver *self, PyObject *args) { return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_multimin_fminimizer_size); } static PyObject* PyGSL_multimin_test_size_method(PyGSL_solver *self, PyObject *args) { int flag=GSL_EFAILED; double epsabs; FUNC_MESS_BEGIN(); if (0==PyArg_ParseTuple(args,"d", &epsabs)) return NULL; flag = gsl_multimin_test_size(gsl_multimin_fminimizer_size(self->solver), epsabs); FUNC_MESS_END(); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyObject* PyGSL_multimin_test_gradient_method(PyGSL_solver * self, PyObject *args) { double epsabs; int flag; FUNC_MESS_BEGIN(); assert(PyGSL_solver_check(self)); if (0==PyArg_ParseTuple(args,"d", &epsabs)) return NULL; flag = gsl_multimin_test_gradient(gsl_multimin_fdfminimizer_gradient(self->solver), epsabs); FUNC_MESS_END(); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyMethodDef PyGSL_multimin_fmethods[] = { {"x", (PyCFunction)PyGSL_multimin_f_x, METH_NOARGS,(char *)multimin_x_doc, }, {"minimum", (PyCFunction)PyGSL_multimin_f_minimum,METH_NOARGS,(char *)multimin_minimum_doc,}, {"set", (PyCFunction)PyGSL_multimin_set_f, METH_VARARGS|METH_KEYWORDS, (char *)multimin_set_f_doc }, {"size", (PyCFunction)PyGSL_multimin_f_size, METH_NOARGS, (char *)multimin_size_doc }, {"test_size",(PyCFunction)PyGSL_multimin_test_size_method,METH_VARARGS, (char *)multimin_test_size_doc}, {NULL, NULL, 0, NULL} /* sentinel */ }; static PyMethodDef PyGSL_multimin_fdfmethods[] = { {"x", (PyCFunction)PyGSL_multimin_fdf_x, METH_NOARGS,(char *)multimin_x_doc, }, {"minimum", (PyCFunction)PyGSL_multimin_fdf_minimum,METH_NOARGS,(char *)multimin_minimum_doc,}, {"set", (PyCFunction)PyGSL_multimin_set_fdf, METH_VARARGS|METH_KEYWORDS, (char *)multimin_set_fdf_doc }, {"dx", (PyCFunction)PyGSL_multimin_dx, METH_NOARGS, (char *)multimin_dx_doc }, {"gradient", (PyCFunction)PyGSL_multimin_gradient, METH_NOARGS, (char *)multimin_gradient_doc }, {"test_gradient",(PyCFunction)PyGSL_multimin_test_gradient_method,METH_VARARGS, (char *)multimin_test_gradient_doc}, {NULL, NULL, 0, NULL} /* sentinel */ }; const struct _GSLMethods multimin_f = { (void_m_t) gsl_multimin_fminimizer_free, /* gsl_multimin_fminimizer_restart */ (void_m_t) NULL, (name_m_t) gsl_multimin_fminimizer_name, (int_m_t) gsl_multimin_fminimizer_iterate}; const struct _GSLMethods multimin_fdf = {(void_m_t) gsl_multimin_fdfminimizer_free, (void_m_t) gsl_multimin_fdfminimizer_restart, (name_m_t) gsl_multimin_fdfminimizer_name, (int_m_t) gsl_multimin_fdfminimizer_iterate}; static const char multimin_f_type_name[] = "F-MultiMinimizer"; static const char multimin_fdf_type_name[] = "FdF-MultiMinimizer"; const struct _SolverStatic multimin_solver_f = {{(void_m_t) gsl_multimin_fminimizer_free, (void_m_t) NULL, (name_m_t) gsl_multimin_fminimizer_name, (int_m_t) gsl_multimin_fminimizer_iterate}, 1, PyGSL_multimin_fmethods, multimin_f_type_name}, multimin_solver_fdf = {{(void_m_t) gsl_multimin_fdfminimizer_free, (void_m_t) gsl_multimin_fdfminimizer_restart, (name_m_t) gsl_multimin_fdfminimizer_name, (int_m_t) gsl_multimin_fdfminimizer_iterate}, 3, PyGSL_multimin_fdfmethods, multimin_fdf_type_name}; static PyObject* PyGSL_multimin_f_init(PyObject *self, PyObject *args, const gsl_multimin_fminimizer_type * type) { PyObject *tmp=NULL; solver_alloc_struct s = {type, (void_an_t) gsl_multimin_fminimizer_alloc, &multimin_solver_f}; FUNC_MESS_BEGIN(); tmp = PyGSL_solver_dn_init(self, args, &s, 1); FUNC_MESS_END(); return tmp; } static PyObject* PyGSL_multimin_fdf_init(PyObject *self, PyObject *args, const gsl_multimin_fdfminimizer_type * type) { PyObject *tmp=NULL; solver_alloc_struct s = {type, (void_an_t) gsl_multimin_fdfminimizer_alloc, &multimin_solver_fdf}; FUNC_MESS_BEGIN(); tmp = PyGSL_solver_dn_init(self, args, &s, 1); FUNC_MESS_END(); return tmp; } #define AMINIMIZER_F(name) \ static PyObject* PyGSL_multimin_init_ ## name (PyObject *self, PyObject *args)\ { \ PyObject *tmp = NULL; \ FUNC_MESS_BEGIN(); \ tmp = PyGSL_multimin_f_init(self, args, gsl_multimin_fminimizer_ ## name); \ if (tmp == NULL){ \ PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \ } \ FUNC_MESS_END(); \ return tmp; \ } #define AMINIMIZER_FDF(name) \ static PyObject* PyGSL_multimin_init_ ## name (PyObject *self, PyObject *args)\ { \ PyObject *tmp = NULL; \ FUNC_MESS_BEGIN(); \ tmp = PyGSL_multimin_fdf_init(self, args, gsl_multimin_fdfminimizer_ ## name); \ if (tmp == NULL){ \ PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \ } \ FUNC_MESS_END(); \ return tmp; \ } AMINIMIZER_F(nmsimplex) AMINIMIZER_FDF(steepest_descent) AMINIMIZER_FDF(vector_bfgs) AMINIMIZER_FDF(conjugate_pr) AMINIMIZER_FDF(conjugate_fr) static PyObject* PyGSL_multimin_test_size(PyObject * self, PyObject *args) { double size, epsabs; int flag = GSL_EFAILED; FUNC_MESS_BEGIN(); if (0==PyArg_ParseTuple(args,"dd", &size, &epsabs)) return NULL; flag = gsl_multimin_test_size(size, epsabs); FUNC_MESS_END(); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyObject* PyGSL_multimin_test_gradient(PyObject * self, PyObject *args) { return PyGSL_solver_vd_i (self, args, gsl_multimin_test_gradient); } static PyMethodDef mMethods[] = { /* solvers */ {"nmsimplex", PyGSL_multimin_init_nmsimplex, METH_VARARGS, (char *)nmsimplex_doc }, {"steepest_descent", PyGSL_multimin_init_steepest_descent, METH_VARARGS, (char *)steepest_descent_doc}, {"vector_bfgs", PyGSL_multimin_init_vector_bfgs, METH_VARARGS, (char *)vector_bfgs_doc }, {"conjugate_pr", PyGSL_multimin_init_conjugate_pr, METH_VARARGS, (char *)conjugate_pr_doc }, {"conjugate_fr", PyGSL_multimin_init_conjugate_fr, METH_VARARGS, (char *)conjugate_fr_doc }, /* multimin funcs */ {"test_size", PyGSL_multimin_test_size, METH_VARARGS, (char *)test_size_doc }, {"test_gradient", PyGSL_multimin_test_gradient, METH_VARARGS, (char *)test_gradient_doc }, {NULL, NULL, 0, NULL} }; void initmultimin(void) { PyObject* m, *dict, *item; FUNC_MESS_BEGIN(); m=Py_InitModule("multimin", mMethods); module = m; assert(m); dict = PyModule_GetDict(m); if(!dict) goto fail; init_pygsl() import_pygsl_solver(); assert(PyGSL_API); if (!(item = PyString_FromString((char*)PyGSL_multimin_module_doc))){ PyErr_SetString(PyExc_ImportError, "I could not generate module doc string!"); goto fail; } if (PyDict_SetItemString(dict, "__doc__", item) != 0){ PyErr_SetString(PyExc_ImportError, "I could not init doc string!"); goto fail; } FUNC_MESS_END(); fail: FUNC_MESS("FAIL"); return; }
{ "alphanum_fraction": 0.6235346656, "avg_line_length": 33.2356215213, "ext": "c", "hexsha": "c6694fc7752b83bc770296a17cd587e43da933a6", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multimin.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multimin.c", "max_line_length": 135, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multimin.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5062, "size": 17914 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * 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. * * 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. * */ /* * * * Filename: write.c * * Description: Write the data into file .dat * * Version: 1.0 * Created: 07/05/2014 22:46:50 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include "funcs.h" #include <stdio.h> #include <gsl/gsl_matrix.h> /* * FUNCTION * Name: save_integrals * Description: * */ int save_integrals ( void* params ) { /* perform the integrals */ double integrals[12] ; void* p = (void*) params ; int status = integration ( p, integrals ) ; /* write them into a file */ FILE* f_integ = fopen ( "INTEGRALS.dat", "w+" ) ; int i ; for ( i = 0 ; i < 12 ; i++ ) fprintf( f_integ, "integrals[%d]: %.9f\n", i, integrals[i] ) ; fclose( f_integ ) ; return status; } /* ----- end of function save_integrals ----- */ /* * FUNCTION * Name: save_matrices * Description: * */ int save_matrices ( void* params ) { void* p = (void *) params ; /* create the Redfield matrix and save it into a file */ gsl_matrix* red_matrix = gsl_matrix_calloc ( 4, 4 ) ; int status1 = red_mat ( red_matrix, p ) ; int status2 = mat_write ( red_matrix, "REDFIELD_MATRIX" ) ; /* create the CP matrix and save it into a file */ gsl_matrix* cp_matrix = gsl_matrix_calloc ( 4, 4 ) ; int status3 = cp_mat ( cp_matrix, p ) ; int status4 = mat_write ( cp_matrix, "CP_MATRIX" ) ; gsl_matrix_free (red_matrix) ; gsl_matrix_free (cp_matrix) ; return status1+status2+status3+status4 ; } /* ----- end of function save_matrices ----- */
{ "alphanum_fraction": 0.6783171521, "avg_line_length": 30.5940594059, "ext": "c", "hexsha": "76c00d3a72dee489b56e2cf83a59d10fa3d08f0d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "write.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_path": "write.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "write.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 801, "size": 3090 }
#include <petsc.h> int main(int argc, char **argv) { PetscErrorCode ierr; PetscMPIInt rank; PetscInt i; PetscReal localval, globalsum; PetscReal x = 1; // default value ierr = PetscInitialize(&argc, &argv, NULL, "Compute e in parallel with PETSc.\n\n"); if (ierr) return ierr; ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr); ierr = PetscOptionsBegin(PETSC_COMM_WORLD, NULL, "Maclaurin Series for exp(x)", NULL); CHKERRQ(ierr); ierr = PetscOptionsReal("-x", "input to exp(x) function", NULL, x, &x, NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); // compute x^n / n! where n = (rank of process) + 1 localval = 1.; for (i = 1; i < rank+1; i++) localval *= x/i; // sum the contributions over all processes ierr = MPI_Allreduce(&localval, &globalsum, 1, MPIU_REAL, MPIU_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr); // output estimate of e and report on work from each process ierr = PetscPrintf(PETSC_COMM_WORLD, "exp(x) is about %17.15f\n", globalsum); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_SELF, "rank %d did %d flops\n", rank, (rank > 0) ? rank-1 : 0); CHKERRQ(ierr); return PetscFinalize(); }
{ "alphanum_fraction": 0.538047138, "avg_line_length": 35.3571428571, "ext": "c", "hexsha": "bd0bfbda11beb96af26922d2744f7dfd30783399", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f7781d4c1bd0868ac31543badf1a6c4afedaf4b0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LeilaGhaffari/p4pdes", "max_forks_repo_path": "c/ch1/expx.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f7781d4c1bd0868ac31543badf1a6c4afedaf4b0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LeilaGhaffari/p4pdes", "max_issues_repo_path": "c/ch1/expx.c", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "f7781d4c1bd0868ac31543badf1a6c4afedaf4b0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LeilaGhaffari/p4pdes", "max_stars_repo_path": "c/ch1/expx.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 388, "size": 1485 }
/* ** gsl routines for double data type ** ** G.Lohmann, July 2004 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_linalg.h> #define dvset gsl_vector_set #define dvget gsl_vector_get #define dmset gsl_matrix_set #define dmget gsl_matrix_get #define fvset gsl_vector_float_set #define fvget gsl_vector_float_get #define fmset gsl_matrix_float_set #define fmget gsl_matrix_float_get #define ABS(x) ((x) > 0 ? (x) : -(x)) /* ** y = Ax */ gsl_vector * dmat_x_vector(gsl_matrix *A, gsl_vector *x, gsl_vector *y) { int i,j,nrows,ncols; double *ptr1,*ptr2,*ptr3,sum; nrows = A->size1; ncols = A->size2; if (y == NULL) { y = gsl_vector_alloc (nrows); } if (x->size != ncols || y->size != nrows) { fprintf(stderr," dmat_x_vector: incongruent dimensions\n"); exit(0); } ptr1 = A->data; ptr3 = y->data; for (i=0; i<nrows; i++) { sum = 0; ptr2 = x->data; for (j=0; j<ncols; j++) { sum += (*ptr1++) * (*ptr2++); } *ptr3++ = sum; } return y; } /* ** y = x^T A */ gsl_vector * dvector_x_mat(gsl_vector *x, gsl_matrix *A, gsl_vector *y) { int i,j,nrows,ncols; double *ptr1,*ptr2,*ptr3,sum; nrows = A->size1; ncols = A->size2; if (y == NULL) { y = gsl_vector_alloc (nrows); } if (x->size != ncols || y->size != nrows) { fprintf(stderr," dmat_x_vector: incongruent dimensions\n"); exit(0); } ptr1 = A->data; ptr3 = y->data; for (i=0; i<nrows; i++) { sum = 0; ptr2 = x->data; for (j=0; j<ncols; j++) { sum += (*ptr1++) * (*ptr2++); } *ptr3++ = sum; } return y; } /* ** z = x^T y */ double dskalarproduct(gsl_vector *x,gsl_vector *y) { int i,n; double *ptr1,*ptr2,sum; n = x->size; if (y->size != n) { fprintf(stderr," dskalarproduct: incongruent vector sizes: %d %d",n,y->size); exit(0); } ptr1 = x->data; ptr2 = y->data; sum = 0; for (i=0; i<n; i++) { sum += (*ptr1) * (*ptr2); ptr1++; ptr2++; } return sum; } /* ** B = A^-1 = A^+ */ gsl_matrix * dmat_PseudoInv(gsl_matrix *A,gsl_matrix *B) { int j,k,l,n,m; double u,x; static gsl_matrix *U=NULL,*V=NULL; static gsl_vector *w=NULL; m = A->size1; n = A->size2; if (B == NULL) { B = gsl_matrix_alloc (n,m); } else if (B->size1 != n || B->size2 != m) { gsl_matrix_free(B); B = gsl_matrix_alloc (n, m); } if (U == NULL) { U = gsl_matrix_alloc (m, n); V = gsl_matrix_alloc (n, n); w = gsl_vector_alloc (n); } else if (U->size1 != m || w->size != n) { gsl_matrix_free(U); gsl_matrix_free(V); gsl_vector_free(w); U = gsl_matrix_alloc (m, n); V = gsl_matrix_alloc (n, n); w = gsl_vector_alloc (n); } /* singular value decomposition */ gsl_matrix_memcpy(U,A); gsl_linalg_SV_decomp_jacobi(U,V,w); gsl_matrix_set_zero(B); for (k=0; k<n; k++) { for (l=0; l<m; l++) { for (j=0; j<n; j++) { u = dvget(w,j); if (ABS(u) > 1.0e-6) { x = dmget(B,k,l); x += dmget(V,k,j)*dmget(U,l,j)/u; dmset(B,k,l,x); } } } } return B; } /* ** C = A x B^T */ gsl_matrix * dmat_x_matT(gsl_matrix *A,gsl_matrix *B,gsl_matrix *C) { int i,j,k; int n,r,m; double *ptr1,*ptr2,*ptr3,sum; n = A->size1; r = A->size2; m = B->size1; if (B->size2 != r) { fprintf(stderr,"fmat_x_matT: incongruent matrix dimensions (A,B).\n"); exit(0); } if (C == NULL) { C = gsl_matrix_alloc (n,m); } else { if (C->size1 != n || C->size2 != m) { fprintf(stderr,"fmat_x_matT: incongruent matrix dimensions(C).\n"); exit(0); } } ptr1 = C->data; for (i=0; i<n; i++) { for (j=0; j<m; j++) { ptr2 = gsl_matrix_ptr (A,i,0); ptr3 = gsl_matrix_ptr (B,j,0); sum = 0; for (k=0; k<r; k++) { sum += (*ptr2) * (*ptr3); ptr2++; ptr3++; } *ptr1++ = sum; } } return C; } /* ** C = A^T x B */ gsl_matrix * dmatT_x_mat(gsl_matrix *A,gsl_matrix *B,gsl_matrix *C) { int i,j,k; int n,m,r; double *ptr1,*ptr2,*ptr3,sum; n = A->size1; r = A->size2; m = B->size2; if (B->size1 != n) { fprintf(stderr,"dmatT_x_mat: incongruent matrix dimensions (A,B).\n"); exit(0); } if (C == NULL) { C = gsl_matrix_alloc (r,m); } else { if (C->size1 != r || C->size2 != m) { fprintf(stderr,"dmatT_x_mat: incongruent matrix dimensions (C, %d %d, %d %d).\n", C->size1,C->size2,r,m); exit(0); } } ptr1 = C->data; for (i=0; i<r; i++) { for (j=0; j<m; j++) { ptr2 = gsl_matrix_ptr (A,0,i); ptr3 = gsl_matrix_ptr (B,0,j); sum = 0; for (k=0; k<n; k++) { sum += (*ptr2) * (*ptr3); ptr2 += A->tda; ptr3 += B->tda; } *ptr1++ = sum; } } return C; } /* ** C = A x B */ gsl_matrix * dmat_x_mat(gsl_matrix *A,gsl_matrix *B,gsl_matrix *C) { int i,j,k,m,n,r; int nrowsA,ncolsA; int nrowsB,ncolsB; int nrowsC,ncolsC; double *ptr1,*ptr2,*ptr3,sum; nrowsA = A->size1; ncolsA = A->size2; nrowsB = B->size1; ncolsB = B->size2; if (C == NULL) C = gsl_matrix_alloc (nrowsA,ncolsB); nrowsC = C->size1; ncolsC = C->size2; if (ncolsA != nrowsB || nrowsA != nrowsC || ncolsB != ncolsC) { fprintf(stderr,"dmat_x_mat: incongruent matrix dimensions.\n"); exit(0); } m = A->size1; n = A->size2; r = B->size2; ptr1 = C->data; for (i=0; i<m; i++) { for (j=0; j<r; j++) { ptr2 = gsl_matrix_ptr (A,i,0); ptr3 = gsl_matrix_ptr (B,0,j); sum = 0; for (k=0; k<n; k++) { sum += (*ptr2++) * (*ptr3); ptr3 += B->tda; } *ptr1++ = sum; } } return C; } gsl_matrix * dtranspose(gsl_matrix *A,gsl_matrix *B) { int i,j,n,m; n = A->size1; m = A->size2; if (B == NULL) { B = gsl_matrix_alloc(m,n); } else if (B->size1 != m || B->size2 != n) { gsl_matrix_free(B); B = gsl_matrix_alloc(m,n); } for (i=0; i<n; i++) { for (j=0; j<m; j++) { dmset(B,j,i,dmget(A,i,j)); } } return B; } /* int main (void) { int i,j; int m,n,r; gsl_matrix *a=NULL,*b=NULL,*c=NULL; double x; n = 648; a = gsl_matrix_alloc(n,n); for (i=0; i<n; i++) { for (j=0; j<n; j++) { x = i+j+1; dmset(a,i,j,x); } } b = gsl_matrix_alloc(n,n); for (i=0; i<n; i++) { for (j=0; j<n; j++) { x = i-j+1; dmset(b,i,j,x); } } c = dmat_x_mat(a,b,NULL); exit(0); } */
{ "alphanum_fraction": 0.5188379483, "avg_line_length": 16.0802919708, "ext": "c", "hexsha": "2229bc8c631a8e63aabc6d78fe5398701010c167", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/lib_viaio/gsl_dutils.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/lib_viaio/gsl_dutils.c", "max_line_length": 87, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/lib_viaio/gsl_dutils.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 2466, "size": 6609 }
/* hyper.c */ #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_sf_psi.h> static double update_hyper(double param, int *vec, int **mat, int nrow, int ncol){ double numer = 0.0; double denom = 0.0; int i, j; for(i = 0;i < nrow;i++) for(j = 0;j < ncol;j++) numer += gsl_sf_psi((double)mat[i][j] + param); numer -= (double)nrow * (double)ncol * gsl_sf_psi(param); for(i = 0;i < nrow;i++) denom += (double)ncol * gsl_sf_psi((double)vec[i] + param * (double)ncol); denom -= (double)nrow * (double)ncol * gsl_sf_psi(param * (double)ncol); return param * numer / denom; } void update_alpha(double *alpha, int *n_m, int **n_mz, int ndocs, int nclass){ double sum_alpha = 0.0; double numer = 0.0; double denom = 0.0; int d, k; for(k = 0;k < nclass;k++) sum_alpha += alpha[k]; for(d = 0;d < ndocs;d++) denom += gsl_sf_psi((double)n_m[d] + sum_alpha); denom -= (double)ndocs * gsl_sf_psi(sum_alpha); for(k = 0;k < nclass;k++){ numer = 0.0; for(d = 0;d < ndocs;d++) numer += gsl_sf_psi((double)n_mz[d][k] + alpha[k]); numer -= (double)ndocs * gsl_sf_psi(alpha[k]); alpha[k] = alpha[k] * numer / denom; } } double update_beta(double beta, int *n_z, int **n_zw, int nclass, int nlex){ double new_beta = update_hyper(beta, n_z, n_zw, nclass, nlex); return new_beta; }
{ "alphanum_fraction": 0.5662068966, "avg_line_length": 30.2083333333, "ext": "c", "hexsha": "d11d6da776d3034c53c99cb8fb9a612d06345fb3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "khigashi1987/mvsLDA", "max_forks_repo_path": "src/hyper.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "khigashi1987/mvsLDA", "max_issues_repo_path": "src/hyper.c", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "khigashi1987/mvsLDA", "max_stars_repo_path": "src/hyper.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 476, "size": 1450 }
// build commmand: // gcc -c test_fresnel.c -O2 -std=c99 -I../LISAsim -I/opt/local/include // gcc -o test_fresnel test_fresnel.o struct.o ../LISAsim/LISAnoise.o -lgsl -lgslcblas #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "struct.h" #include "splinecoeffs.h" /* Implementation of the Thomas algorithm to solve a tridiagonal system */ /* Note: assumes numerical stability (e.g. diagonal-dominated matrix) */ static void SolveTridiagThomas( gsl_vector* vectx, /* Output: solution vector, length n - already allocated */ gsl_vector* vecta, /* Diagonal of the matrix, length n */ gsl_vector* vectb, /* Lower diagonal, length n-1 */ gsl_vector* vectc, /* Upper diagonal, length n-1 */ gsl_vector* vecty, /* Right-hand-side vector, length n */ int n) /* Length of vectx, vecty */ { /* Check lengths */ if(!(vectx->size==n && vecty->size==n && vecta->size==n && vectb->size==n-1 && vectc->size==n-1)) { printf("Error: incompatible lengths in SolveTridiagThomas.\n"); exit(1); } /* Note: we modify the vectors c, y in place */ double* chat = vectc->data; double* yhat = vecty->data; double* x = vectx->data; double* a = vecta->data; double* b = vectb->data; /* Sweep forward, computing the chat and yhat values */ chat[0] = chat[0] / a[0]; yhat[0] = yhat[0] / a[0]; double factor; for(int i=1; i<=n-2; i++) { factor = 1./(a[i] - b[i-1]*chat[i-1]); chat[i] = chat[i] * factor; yhat[i] = (yhat[i] - b[i-1]*yhat[i-1]) * factor; } factor = 1./(a[n-1] - b[n-2]*chat[n-2]); yhat[n-1] = (yhat[n-1] - b[n-2]*yhat[n-2]) * factor; /* Solve for x going backward */ x[n-1] = yhat[n-1]; for(int i=n-2; i>=0; i--) { x[i] = yhat[i] - chat[i] * x[i+1]; } } void BuildNotAKnotSpline( gsl_matrix* splinecoeffs, /* Output: matrix containing all the spline coeffs (already allocated) */ gsl_vector* vectx, /* Input: vector x*/ gsl_vector* vecty, /* Input: vector y */ int n) /* Size of x, y, and of output matrix */ { /* Check lengths */ if(!(vectx->size==n && vecty->size==n && splinecoeffs->size1==n && splinecoeffs->size2==5)) { printf("Error: incompatible lengths in NotAKnotSpline.\n"); exit(1); } double* x = vectx->data; double* y = vecty->data; /* Computing vecth and vectDeltay */ gsl_vector* vecth = gsl_vector_alloc(n-1); gsl_vector* vectDeltay = gsl_vector_alloc(n-1); gsl_vector* vectDeltayoverh = gsl_vector_alloc(n-1); double* h = vecth->data; double* Deltay = vectDeltay->data; double* Deltayoverh = vectDeltayoverh->data; for(int i=0; i<n-1; i++) { h[i] = x[i+1] - x[i]; Deltay[i] = y[i+1] - y[i]; Deltayoverh[i] = Deltay[i] / h[i]; } /* Structures for the tridiagonal system */ gsl_vector* vectY = gsl_vector_alloc(n-2); gsl_vector* vecta = gsl_vector_alloc(n-2); gsl_vector* vectb = gsl_vector_alloc(n-3); gsl_vector* vectc = gsl_vector_alloc(n-3); double* Y = vectY->data; double* a = vecta->data; double* b = vectb->data; double* c = vectc->data; for(int i=0; i<=n-3; i++) { Y[i] = 3.*(Deltayoverh[i+1] - Deltayoverh[i]); a[i] = 2.*(h[i+1] + h[i]); } for(int i=0; i<=n-4; i++) { b[i] = h[i+1]; c[i] = h[i+1]; } /* Adjusting for the not-a-knot condition */ a[0] += h[0] + h[0]*h[0]/h[1]; c[0] += -h[0]*h[0]/h[1]; a[n-3] += h[n-2] + h[n-2]*h[n-2]/h[n-3]; b[n-4] += -h[n-2]*h[n-2]/h[n-3]; /* Solving the tridiagonal system */ gsl_vector* vectp2 = gsl_vector_alloc(n); gsl_vector_view viewp2trunc = gsl_vector_subvector(vectp2, 1, n-2); SolveTridiagThomas(&viewp2trunc.vector, vecta, vectb, vectc, vectY, n-2); double* p2 = vectp2->data; p2[0] = p2[1] - h[0]/h[1] * (p2[2] - p2[1]); p2[n-1] = p2[n-2] + h[n-2]/h[n-3] * (p2[n-2] - p2[n-3]); /* Deducing the p1's and the p3's */ gsl_vector* vectp1 = gsl_vector_alloc(n); gsl_vector* vectp3 = gsl_vector_alloc(n); double* p1 = vectp1->data; double* p3 = vectp3->data; for(int i=0; i<=n-2; i++) { p1[i] = Deltayoverh[i] - h[i]/3. * (p2[i+1] + 2.*p2[i]); p3[i] = (p2[i+1] - p2[i]) / (3*h[i]); } /* Note: p1[n-1], p2[n-1], p3[n-1] are set to values coherent with the derivatives of the spline at the last point, but they are not stricly speaking coefficients of the spline. */ p1[n-1] = p1[n-2] + 2.*p2[n-2]*h[n-2] + 3.*p3[n-2]*h[n-2]*h[n-2]; p3[n-1] = p3[n-2]; /* Copying the results in the output matrix */ gsl_vector_view viewx = gsl_matrix_column(splinecoeffs, 0); gsl_vector_view viewp0 = gsl_matrix_column(splinecoeffs, 1); gsl_vector_view viewp1 = gsl_matrix_column(splinecoeffs, 2); gsl_vector_view viewp2 = gsl_matrix_column(splinecoeffs, 3); gsl_vector_view viewp3 = gsl_matrix_column(splinecoeffs, 4); gsl_vector_memcpy(&viewx.vector, vectx); gsl_vector_memcpy(&viewp0.vector, vecty); gsl_vector_memcpy(&viewp1.vector, vectp1); gsl_vector_memcpy(&viewp2.vector, vectp2); gsl_vector_memcpy(&viewp3.vector, vectp3); /* Cleanup*/ gsl_vector_free(vecth); gsl_vector_free(vectDeltay); gsl_vector_free(vectDeltayoverh); gsl_vector_free(vectY); gsl_vector_free(vecta); gsl_vector_free(vectb); gsl_vector_free(vectc); gsl_vector_free(vectp1); gsl_vector_free(vectp2); gsl_vector_free(vectp3); } void BuildQuadSpline( gsl_matrix* splinecoeffs, /* Output: matrix containing all the spline coeffs (already allocated) */ gsl_vector* vectx, /* Input: vector x*/ gsl_vector* vecty, /* Input: vector y */ int n) /* Size of x, y, and of output matrix */ { /* Check lengths */ if(!(vectx->size==n && vecty->size==n && splinecoeffs->size1==n && splinecoeffs->size2==4)) { printf("Error: incompatible lengths in NotAKnotSpline.\n"); exit(1); } double* x = vectx->data; double* y = vecty->data; /* Computing vecth and vectDeltay */ gsl_vector* vecth = gsl_vector_alloc(n-1); gsl_vector* vectDeltay = gsl_vector_alloc(n-1); gsl_vector* vectDeltayoverh = gsl_vector_alloc(n-1); double* h = vecth->data; double* Deltay = vectDeltay->data; double* Deltayoverh = vectDeltayoverh->data; for(int i=0; i<n-1; i++) { h[i] = x[i+1] - x[i]; Deltay[i] = y[i+1] - y[i]; Deltayoverh[i] = Deltay[i] / h[i]; } /* Solving for p1 */ gsl_vector* vectp1 = gsl_vector_alloc(n); double* p1 = vectp1->data; double ratio = h[n-2] / h[n-3]; p1[n-3] = ((2. + ratio)*Deltayoverh[n-3] - Deltayoverh[n-2]) / (1. + ratio); p1[n-2] = -p1[n-3] + 2.*Deltayoverh[n-3]; for(int i=n-4; i>=0; i--) { p1[i] = -p1[i+1] + 2.*Deltayoverh[i]; } p1[n-1] = (1. + ratio)*p1[n-2] - ratio*p1[n-3]; /* Deducing the p2's */ gsl_vector* vectp2 = gsl_vector_alloc(n); double* p2 = vectp2->data; for(int i=0; i<=n-2; i++) { p2[i] = (p1[i+1] - p1[i]) / (2.*h[i]); } /* Note: p2[n-1] is set to values coherent with the derivatives of the spline at the last point, but not stricly speaking a coefficient of the spline. */ p2[n-1] = p2[n-2]; /* Copying the results in the output matrix */ gsl_vector_view viewx = gsl_matrix_column(splinecoeffs, 0); gsl_vector_view viewp0 = gsl_matrix_column(splinecoeffs, 1); gsl_vector_view viewp1 = gsl_matrix_column(splinecoeffs, 2); gsl_vector_view viewp2 = gsl_matrix_column(splinecoeffs, 3); gsl_vector_memcpy(&viewx.vector, vectx); gsl_vector_memcpy(&viewp0.vector, vecty); gsl_vector_memcpy(&viewp1.vector, vectp1); gsl_vector_memcpy(&viewp2.vector, vectp2); /* Cleanup*/ gsl_vector_free(vecth); gsl_vector_free(vectDeltay); gsl_vector_free(vectDeltayoverh); gsl_vector_free(vectp1); gsl_vector_free(vectp2); } void BuildSplineCoeffs( CAmpPhaseSpline** splines, /* */ CAmpPhaseFrequencySeries* freqseries) /* */ { /* Initialize output structure */ int n = (int) freqseries->freq->size; CAmpPhaseSpline_Init(splines, n); /* Build the splines */ BuildNotAKnotSpline((*splines)->spline_amp_real, freqseries->freq, freqseries->amp_real, n); BuildNotAKnotSpline((*splines)->spline_amp_imag, freqseries->freq, freqseries->amp_imag, n); BuildQuadSpline((*splines)->quadspline_phase, freqseries->freq, freqseries->phase, n); } void BuildListmodesCAmpPhaseSpline( ListmodesCAmpPhaseSpline** listspline, /* Output: list of modes of splines in matrix form */ ListmodesCAmpPhaseFrequencySeries* listh) /* Input: list of modes in amplitude/phase form */ { if(*listspline){ /* We don't allow for the case where listspline already points to something */ printf("Error: Tried to add a mode to an already existing ListmodesCAmpPhaseSpline "); exit(1); } else { ListmodesCAmpPhaseFrequencySeries* listelementh = listh; while(listelementh) { int l = listelementh->l; int m = listelementh->m; CAmpPhaseSpline* splines = NULL; BuildSplineCoeffs(&splines, listelementh->freqseries); *listspline = ListmodesCAmpPhaseSpline_AddModeNoCopy(*listspline, splines, l, m); listelementh = listelementh->next; } } } /* Note: for the spines in matrix form, the first column contains the x values, so the coeffs start at 1 */ double EvalCubic( gsl_vector* coeffs, /**/ double eps, /**/ double eps2, /**/ double eps3) /**/ { double p0 = gsl_vector_get(coeffs, 1); double p1 = gsl_vector_get(coeffs, 2); double p2 = gsl_vector_get(coeffs, 3); double p3 = gsl_vector_get(coeffs, 4); return p0 + p1*eps + p2*eps2 + p3*eps3; } double EvalQuad( gsl_vector* coeffs, /**/ double eps, /**/ double eps2) /**/ { double p0 = gsl_vector_get(coeffs, 1); double p1 = gsl_vector_get(coeffs, 2); double p2 = gsl_vector_get(coeffs, 3); return p0 + p1*eps + p2*eps2; } void EvalCAmpPhaseSpline( CAmpPhaseSpline* splines, //input CAmpPhaseFrequencySeries* freqseries) //in/out defines CAmpPhase from defined freqs { int ispline=0; //printf("Enter: n=%i\n",freqseries->freq->size); for(int i=0;i<freqseries->freq->size;i++){ double f=gsl_vector_get(freqseries->freq,i); //printf(" f:%g < %g < %g\n",gsl_matrix_get(splines->quadspline_phase, 0, 0),f,gsl_matrix_get(splines->quadspline_phase, splines->quadspline_phase->size1-1, 0)); /* Adjust the index in the spline if necessary and compute */ while(gsl_matrix_get(splines->quadspline_phase, ispline+1, 0)<f)ispline++; double eps = f - gsl_matrix_get(splines->quadspline_phase, ispline, 0); double eps2 = eps*eps; double eps3 = eps2*eps; gsl_vector_view coeffsampreal = gsl_matrix_row(splines->spline_amp_real, ispline); gsl_vector_view coeffsampimag = gsl_matrix_row(splines->spline_amp_imag, ispline); gsl_vector_view coeffsphase = gsl_matrix_row(splines->quadspline_phase, ispline); double Ar = EvalCubic(&coeffsampreal.vector, eps, eps2, eps3); double Ai = EvalCubic(&coeffsampimag.vector, eps, eps2, eps3); double Ph = EvalQuad(&coeffsphase.vector, eps, eps2); gsl_vector_set(freqseries->amp_real,i,Ar); gsl_vector_set(freqseries->amp_imag,i,Ai); gsl_vector_set(freqseries->phase,i,Ph); } };
{ "alphanum_fraction": 0.647146489, "avg_line_length": 36.2126984127, "ext": "c", "hexsha": "ca11e57d858ee3c7e4e627206d845c23e0ff3e5a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "tools/splinecoeffs.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_path": "tools/splinecoeffs.c", "max_line_length": 182, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "tools/splinecoeffs.c", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 3868, "size": 11407 }
/** * \file Component.h */ #ifndef ATK_MODELLING_COMPONENT_H #define ATK_MODELLING_COMPONENT_H #include <ATK/Modelling/config.h> #include <ATK/Modelling/Types.h> #include <gsl/gsl> #include <Eigen/Eigen> #include <tuple> #include <vector> namespace ATK { template<typename DataType_> class DynamicModellerFilter; enum class Linear { IsLinear, IsNotLinear }; /// Base class for all components template<typename DataType_> class ATK_MODELLING_EXPORT Component { public: using DataType = DataType_; protected: /// Local pins to which this component is connected to std::vector<std::tuple<PinType, gsl::index>> pins; /// dt value, not useful for every component DataType dt; /// The current modeller where the component is located DynamicModellerFilter<DataType>* modeller; public: /// Virtual destructor virtual ~Component(); Component() = default; Component(const Component&) = delete; Component& operator=(const Component&) = delete; virtual Linear isLinear() const; /** * sets the pins for the component * @params pins is the set of pins for this component */ void set_pins(std::vector<std::tuple<PinType, gsl::index>> pins); /// Returns the pins of this component const std::vector<std::tuple<PinType, gsl::index>>& get_pins() const { return pins; } /** * Used to indicate if the modeller needs to update its set of equations with those provided by this component * @param modeller the modeller to update */ virtual void update_model(DynamicModellerFilter<DataType>* modeller); /** * Update the component for its steady state condition * @param dt is the delat that will be used in following updates */ virtual void update_steady_state(DataType dt); /** * Update the component for its current state condition */ virtual void update_state(); /** * Precompute internal value before asking current and gradients * @param steady_state is a flag to indcate steady state computation (used for some components) */ virtual void precompute(bool steady_state); /** * Get current for the given pin based on the state * @param pin_index is the pin from which to compute the current * @param steady_state is a flag to indcate steady state computation (used for some components) */ virtual DataType get_current(gsl::index pin_index, bool steady_state) const = 0; /** * Get current gradient for the given pins based on the state * @param pin_index_ref is the pin of the current from which the gradient is computed * @param pin_index is the pin from which to compute the gradient of the pin_index current * @param steady_state is a flag to indcate steady state computation (used for some components) */ virtual DataType get_gradient(gsl::index pin_index_ref, gsl::index pin_index, bool steady_state) const = 0; /** * Add a new equation to the modeller * @param eq_index is equation row in the state vector and the jacobian * @param eq_number is the equation number to add * @param eqs is the state vector to update * @param jacobian is the jacobian to update * @param steady_state is a flag to indcate steady state computation (used for some components) */ virtual void add_equation(gsl::index eq_index, gsl::index eq_number, Eigen::Matrix<DataType, Eigen::Dynamic, 1>& eqs, Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>& jacobian, bool steady_state) const; virtual gsl::index get_number_parameters() const; /// Get the name of a parameter virtual std::string get_parameter_name(gsl::index identifier) const; /// Get the value of a parameter virtual DataType_ get_parameter(gsl::index identifier) const; /// Set the value of a parameter virtual void set_parameter(gsl::index identifier, DataType_ value); }; } #endif
{ "alphanum_fraction": 0.6894164194, "avg_line_length": 31.3488372093, "ext": "h", "hexsha": "71365aae37947dd2d98b5f4be3f455aba4d0e8fb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "fc22c908dc68f5a831d5f3e26e7ac4c943d0f1ff", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "AudioTK/ATK-Modelling-free", "max_forks_repo_path": "ATK/Modelling/Component.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc22c908dc68f5a831d5f3e26e7ac4c943d0f1ff", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "AudioTK/ATK-Modelling-free", "max_issues_repo_path": "ATK/Modelling/Component.h", "max_line_length": 214, "max_stars_count": 2, "max_stars_repo_head_hexsha": "fc22c908dc68f5a831d5f3e26e7ac4c943d0f1ff", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "AudioTK/ATK-Modelling-free", "max_stars_repo_path": "ATK/Modelling/Component.h", "max_stars_repo_stars_event_max_datetime": "2021-12-16T11:55:35.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-07T12:47:03.000Z", "num_tokens": 934, "size": 4044 }
#include <iostream> #include <vector> #include <stdio.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <time.h> #include <math.h> //#include <C:/Program Files (x86)/Intel/Composer XE/compiler/include/cilk/cilk.h> #ifndef _HEART_H #define _HEART_H class heart { private: int L; //sytem size length for now square std::vector<std::vector<int>> state; //value indicates whether in excited state refactory or resting std::vector<std::vector<int>> new_state; //using new_state and state to distinguish newly excited cells from previously excited std::vector<std::vector<int>> functional; //1 if functional 0 if disfunctional std::vector<std::vector<int>> bond; //1 if bond to site above current cell, 0 if no bond above site std::vector<std::vector<int>> last_excited; std::vector<std::vector<int>> last_excited_counter; // have a dummy counter so as to not interfere with APD dynamics std::vector<std::vector<int>> refractory; std::vector<std::vector<int>> total_rest; //have counter for total time cells spend in rest or refractory int heart_time; //internal clock //model parameters int tau; //refactory period int T; // pacemaker rate double nu, epsilom, delta; //probability vertical connection exists, probability of misfire given faulty and probability cell faulty //random number generator const gsl_rng_type*Type; gsl_rng*r; int total_bonds; int total_functional; int total_excited; double refractory_period; public: heart() { } heart(int _L, int _T, int _tau, double _nu, double _epsilom, double _delta) { refractory_period =0; L = _L; nu = _nu; tau = _tau; T = _T; epsilom = _epsilom; delta = _delta; heart_time = T; state.resize(L); new_state.resize(L); functional.resize(L); bond.resize(L); last_excited.resize(L); last_excited_counter.resize(L); refractory.resize(L); total_rest.resize(L); //pacemaker action for (unsigned i = 0; i<L; i++) { state[i].resize(L, 0); // all cells eligible for excitation new_state[i].resize(L, 0); functional[i].resize(L, 1);// none disfunctional at the moment bond[i].resize(L, 1); // all transverse bonds present at the moment last_excited[i].resize(L, T); last_excited_counter[i].resize(L, 0); refractory[i].resize(L, tau); total_rest[i].resize(L,0); } // total_functional = L*L; // total_bonds = L*L; total_excited = 0;//could be useful avoiding calling size of some vector //HAVE NOT USED gsl_rng in class before need to make sure is working correctly // environment variable GSL_RNG_TYPE gsl_rng_env_setup(); Type = gsl_rng_mt19937;//random number generator using the Mersenne Twister algorithm r = gsl_rng_alloc(Type); //gsl_rng_set(r, time(NULL));//random number generator seeded with time gsl_rng_set(r, 10);//random number generator seeded with time //assigning cells as having a bond above them or not and functional or not functional int healthy = 1; for (int j = 0; j<L; j++) { for (int i = 0; i<L; i++) { bond[i][j] = (gsl_rng_uniform(r)<nu); functional[i][j] = (gsl_rng_uniform(r)>delta);// inequality reversed //double x = gsl_rng_uniform(r); // std::cout <<x<< '\t' << (x<nu) << std::endl; } } gsl_rng_set(r, 20);//random number generator seeded with time } void operate()//one time step { total_excited = 0; refractory_period = 0; //Relax excited cells for (int i = 0; i < L; i++) { for (int j = 0; j<L; j++) { if (state[i][j] == 1)//searching 4 neighbours of excited cell trying to excite if resting and if don't misfire and if there is a bond { new_state[((i + 1)<L)*(i + 1)][j] += (new_state[((i + 1)<L)*(i + 1)][j]<1)*(state[((i + 1)<L)*(i + 1)][j]<1)*bond[i][j] * (1 - (1 - functional[((i + 1)<L)*(i + 1)][j])*(gsl_rng_uniform(r)<epsilom)); new_state[(i - 1)*(i>0) + (L - 1)*(i<1)][j] += (new_state[(i - 1)*(i>0) + (L - 1)*(i<1)][j]<1)*(state[(i - 1)*(i>0) + (L - 1)*(i<1)][j]<1)*bond[(i - 1)*(i>0) + (L - 1)*(i<1)][j] * (1 - (1 - functional[(i - 1)*(i>0) + (L - 1)*(i<1)][j])*(gsl_rng_uniform(r)<epsilom)); new_state[i][(j + 1)*(j<L - 1)] += (new_state[i][(j + 1)*(j<L - 1)]<1)*(j<L - 1)*(state[i][(j + 1)*(j<L - 1)]<1)*(1 - (1 - functional[i][(j + 1)*(j<L - 1)])*(gsl_rng_uniform(r)<epsilom)); new_state[i][(j - 1)*(j>0)] += (new_state[i][(j - 1)*(j>0)]<1)*(j>0)*(state[i][(j - 1)*(j>0)]<1)*(1 - (1 - functional[i][(j - 1)*(j>0)])*(gsl_rng_uniform(r)<epsilom)); refractory[i][j] = restitution(i, j); total_rest[i][j] += last_excited_counter[i][j]; } } } //end relaxing //std::vector<std::pair<int,int>> next_excited_cells; //evolving cells that were not excited previously or now (some subtlty to those possibly excited now) for (int i = 0; i<L; i++) { for (int j = 0; j<L; j++) { new_state[i][j] += (state[i][j]>0); //if state was excited or refactory before +1 states that were resting may have been newly excited or not but this ignores them new_state[i][j] *= (state[i][j]<refractory[i][j]);//promote to resting after end of refactory which is now variable total_excited += (new_state[i][j]<2)*new_state[i][j]; last_excited[i][j] += (state[i][j] < 1) + (state[i][j]>1);//counts if not excited last_excited[i][j] *= (state[i][j] < 1) + (state[i][j]>1); //cycles back to 0 if excited; old states so don't put lastexcited to 0 before calculating new refractory last_excited_counter[i][j] += (state[i][j] < 1) + (state[i][j]>1);//dummy counter last_excited_counter[i][j] *= (state[i][j] < 1) + (state[i][j]>1); //dummy counter refractory_period += refractory[i][j]; } } //SAN for (int i = 0; i<L; i++) { //new_state[i][0] += (state[i][0]<1)*(heart_time>T - 1)*(1 - (1 - functional[i][0])*(gsl_rng_uniform(r)<epsilom)); new_state[i][0] += (state[i][0]<1)*(heart_time>T - 1); } heart_time++; heart_time *= (heart_time<T + 1); //end SAN state = new_state; } int get_state(int i, int j)//perhaps have alternative for 2d array { return state[i][j]; } void set_state(int i, int j, int val) { state[i][j] = val; } int get_function(int i, int j) { return functional[i][j]; } void set_function(int i, int j, int val) { functional[i][j] = val; } int get_bond(int i, int j) { return bond[i][j]; } void set_bond(int i, int j, int val) { bond[i][j] = val; } void update_total_rest(int i, int j) { total_rest[i][j] += last_excited_counter[i][j]; } double get_total_rest(int i,int j) { return total_rest[i][j]; } void reset_total_rest(int i, int j) { total_rest[i][j] = 0; last_excited_counter[i][j] = 0; } int get_tau() { return tau; } int get_T() { return T; } int get_excited() { return total_excited; } int get_refractory(int i, int j) { return refractory[i][j]; } int get_last_excited(int i, int j) { return last_excited[i][j]; } double colour(int i, int j) { return (1 - state[i][j] / (1.0*tau))*(state[i][j]>1); //return state[i][j]/(1.0*T); } int restitution(int i, int j) { //some function of tau T and last_excited[i][j] if (last_excited[i][j] < T) { //return floor((1 - exp(-4.0*last_excited[i][j] / (1.0*T)))*tau); return tau; } else { return tau; } //if T since excited should be approx tau //if less shoud be less than tau } double get_avg_refractory() { return refractory_period/(L*L); } }; #endif
{ "alphanum_fraction": 0.606398135, "avg_line_length": 28.3860294118, "ext": "h", "hexsha": "a6887fe400314672933bcec1baed2d7ae05abddd", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "pm2111/Heart-Defibrillation-Project", "max_forks_repo_path": "standard model + apd 100% working/heart_james.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "pm2111/Heart-Defibrillation-Project", "max_issues_repo_path": "standard model + apd 100% working/heart_james.h", "max_line_length": 272, "max_stars_count": null, "max_stars_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "pm2111/Heart-Defibrillation-Project", "max_stars_repo_path": "standard model + apd 100% working/heart_james.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2511, "size": 7721 }
#include <php.h> #include <Zend/zend_interfaces.h> #include <Zend/zend_exceptions.h> #include <ext/spl/spl_iterators.h> #include <ext/spl/spl_exceptions.h> #include <cblas.h> #include <Interop/Polite/Math/Matrix.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php_rindow_openblas.h" static zend_object_handlers rindow_openblas_blas_object_handlers; // destractor static void php_rindow_openblas_blas_free_object(zend_object* object) { zend_object_std_dtor(object); } // constructor static zend_object* php_rindow_openblas_blas_create_object(zend_class_entry* class_type) /* {{{ */ { zend_object* intern = NULL; intern = (zend_object*)ecalloc(1, sizeof(zend_object) + zend_object_properties_size(class_type)); zend_object_std_init(intern, class_type); object_properties_init(intern, class_type); intern->handlers = &rindow_openblas_blas_object_handlers; return intern; } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function getNumThreads() : int {{{ */ static PHP_METHOD(Blas, getNumThreads) { int n; n = openblas_get_num_threads(); RETURN_LONG(n); } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function getNumProcs() : int {{{ */ static PHP_METHOD(Blas, getNumProcs) { int n; n = openblas_get_num_procs(); RETURN_LONG(n); } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function getConfig() : string {{{ */ static PHP_METHOD(Blas, getConfig) { char *s; s = openblas_get_config(); RETURN_STRING(s); } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function getCorename() : string {{{ */ static PHP_METHOD(Blas, getCorename) { char *s; s = openblas_get_corename(); RETURN_STRING(s); } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function scal( int $n, float $alpha, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Blas, scal) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; zval* x=NULL; zend_long offsetX; zend_long incX; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 5, 5) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_sscal((blasint)n, (float)alpha, &(((float *)buffer->data)[offsetX]), (blasint)incX); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dscal((blasint)n, (double)alpha, &(((double *)buffer->data)[offsetX]), (blasint)incX); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function axpy( int $n, float $alpha, Buffer $X, int $offsetX, int $incX, Buffer $Y, int $offsetY, int $incY ) : void {{{ */ static PHP_METHOD(Blas, axpy) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; zend_long n; double alpha; zval* x=NULL; zend_long offsetX; zend_long incX; zval* y=NULL; zend_long offsetY; zend_long incY; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 8, 8) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(incY) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) { return; } // Check Buffer Y bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferY,"y")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) { return; } // Check Buffer X and Y if(bufferX->dtype!=bufferY->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X and Y", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_saxpy((blasint)n, (float)alpha, &(((float *)bufferX->data)[offsetX]), (blasint)incX, &(((float *)bufferY->data)[offsetY]), (blasint)incY); break; case php_interop_polite_math_matrix_dtype_float64: cblas_daxpy((blasint)n, (double)alpha, &(((double *)bufferX->data)[offsetX]), (blasint)incX, &(((double *)bufferY->data)[offsetY]), (blasint)incY); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function dot( int $n, Buffer $X, int $offsetX, int $incX, Buffer $Y, int $offsetY, int $incY ) : float {{{ */ static PHP_METHOD(Blas, dot) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zval* y=NULL; zend_long offsetY; zend_long incY; double result; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 7, 7) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(incY) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) { return; } // Check Buffer Y bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferY,"y")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) { return; } // Check Buffer X and Y if(bufferX->dtype!=bufferY->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X and Y", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: result = (double)cblas_sdot((blasint)n, &(((float *)bufferX->data)[offsetX]), (blasint)incX, &(((float *)bufferY->data)[offsetY]), (blasint)incY); break; case php_interop_polite_math_matrix_dtype_float64: result = (double)cblas_ddot((blasint)n, &(((double *)bufferX->data)[offsetX]), (blasint)incX, &(((double *)bufferY->data)[offsetY]), (blasint)incY); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } RETURN_DOUBLE(result); } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function asum( int $n, Buffer $X, int $offsetX, int $incX ) : float {{{ */ static PHP_METHOD(Blas, asum) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; double result; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: result = (double)cblas_sasum((blasint)n, &(((float *)buffer->data)[offsetX]), (blasint)incX); break; case php_interop_polite_math_matrix_dtype_float64: result = (double)cblas_dasum((blasint)n, &(((double *)buffer->data)[offsetX]), (blasint)incX); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } RETURN_DOUBLE(result); } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function iamax( int $n, Buffer $X, int $offsetX, int $incX ) : int {{{ */ static PHP_METHOD(Blas, iamax) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long resultIdx; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: resultIdx = (zend_long)cblas_isamax((blasint)n, &(((float *)buffer->data)[offsetX]), (blasint)incX); break; case php_interop_polite_math_matrix_dtype_float64: resultIdx = (zend_long)cblas_idamax((blasint)n, &(((double *)buffer->data)[offsetX]), (blasint)incX); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } RETURN_LONG(resultIdx); } /* }}} */ #ifdef OPENBLAS_HAVE_IAMIN /* Method Rindow\OpenBLAS\Blas:: public function iamin( int $n, Buffer $X, int $offsetX, int $incX ) : int {{{ */ static PHP_METHOD(Blas, iamin) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long resultIdx; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: resultIdx = (zend_long)cblas_isamin((blasint)n, &(((float *)buffer->data)[offsetX]), (blasint)incX); break; case php_interop_polite_math_matrix_dtype_float64: resultIdx = (zend_long)cblas_idamin((blasint)n, &(((double *)buffer->data)[offsetX]), (blasint)incX); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } RETURN_LONG(resultIdx); } /* }}} */ #endif /* Method Rindow\OpenBLAS\Blas:: public function copy( int $n, Buffer $X, int $offsetX, int $incX, Buffer $Y, int $offsetY, int $incY ) : void {{{ */ static PHP_METHOD(Blas, copy) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zval* y=NULL; zend_long offsetY; zend_long incY; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 7, 7) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(incY) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) { return; } // Check Buffer Y bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferY,"y")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) { return; } // Check Buffer X and Y if(bufferX->dtype!=bufferY->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X and Y", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_scopy((blasint)n, &(((float *)bufferX->data)[offsetX]), (blasint)incX, &(((float *)bufferY->data)[offsetY]), (blasint)incY); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dcopy((blasint)n, &(((double *)bufferX->data)[offsetX]), (blasint)incX, &(((double *)bufferY->data)[offsetY]), (blasint)incY); break; default: { zend_long i,idX,idY; int valueSize; uint8_t *x,*y; valueSize = php_rindow_openblas_common_dtype_to_valuesize(bufferX->dtype); x = php_rindow_openblas_get_address(bufferX,offsetX,valueSize); y = php_rindow_openblas_get_address(bufferY,offsetY,valueSize); if(incX==1 && incY==1) { memcpy(y,x,valueSize*n); } else { for(i=0,idX=0,idY=0; i<n; i++,idX+=incX,idY+=incY) { memcpy(&y[valueSize*idY],&x[valueSize*idX],valueSize); } } } break; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function nrm2( int $n, Buffer $X, int $offsetX, int $incX ) : float {{{ */ static PHP_METHOD(Blas, nrm2) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; double result; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: result = (double)cblas_snrm2((blasint)n, &(((float *)buffer->data)[offsetX]), (blasint)incX); break; case php_interop_polite_math_matrix_dtype_float64: result = (double)cblas_dnrm2((blasint)n, &(((double *)buffer->data)[offsetX]), (blasint)incX); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } RETURN_DOUBLE(result); } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function rotg( Buffer $A, int $offsetA, Buffer $B, int $offsetB, Buffer $C, int $offsetC, Buffer $S, int $offsetS, ) : void {{{ */ static PHP_METHOD(Blas, rotg) { zval* a; zend_long offsetA; zval* b; zend_long offsetB; zval* c; zend_long offsetC; zval* s; zend_long offsetS; php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferB; php_interop_polite_math_matrix_linear_buffer_t* bufferC; php_interop_polite_math_matrix_linear_buffer_t* bufferS; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 8, 8) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_OBJECT(b) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetB) Z_PARAM_OBJECT(c) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetC) Z_PARAM_OBJECT(s) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetS) ZEND_PARSE_PARAMETERS_END(); // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferA,1,offsetA,1)) { return; } // Check Buffer B bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b); if(php_rindow_openblas_assert_buffer_type(bufferB,"b")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferB,1,offsetB,1)) { return; } // Check Buffer C bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c); if(php_rindow_openblas_assert_buffer_type(bufferC,"c")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferC,1,offsetC,1)) { return; } // Check Buffer S bufferS = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(s); if(php_rindow_openblas_assert_buffer_type(bufferS,"s")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferS,1,offsetS,1)) { return; } // Check Buffer A and B and C and S if(bufferA->dtype!=bufferB->dtype || bufferB->dtype!=bufferC->dtype || bufferC->dtype!=bufferS->dtype || bufferS->dtype!=bufferA->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for A,B,C and S", 0); return; } switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_srotg( &(((float *)bufferA->data)[offsetA]), &(((float *)bufferB->data)[offsetB]), &(((float *)bufferC->data)[offsetC]), &(((float *)bufferS->data)[offsetS]) ); break; case php_interop_polite_math_matrix_dtype_float64: cblas_drotg( &(((double *)bufferA->data)[offsetA]), &(((double *)bufferB->data)[offsetB]), &(((double *)bufferC->data)[offsetC]), &(((double *)bufferS->data)[offsetS]) ); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function rot( int $n, Buffer $X, int $offsetX, int $incX, Buffer $Y, int $offsetY, int $incY, Buffer $C, int $offsetC, Buffer $S, int $offsetS, ) : void {{{ */ static PHP_METHOD(Blas, rot) { zend_long n; zval* x; zend_long offsetX; zend_long incX; zval* y; zend_long offsetY; zend_long incY; zval* c; zend_long offsetC; zval* s; zend_long offsetS; php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; php_interop_polite_math_matrix_linear_buffer_t* bufferC; php_interop_polite_math_matrix_linear_buffer_t* bufferS; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 11, 11) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(incY) Z_PARAM_OBJECT(c) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetC) Z_PARAM_OBJECT(s) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetS) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) { return; } // Check Buffer Y bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferY,"y")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) { return; } // Check Buffer C bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c); if(php_rindow_openblas_assert_buffer_type(bufferC,"c")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferC,1,offsetC,1)) { return; } // Check Buffer S bufferS = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(s); if(php_rindow_openblas_assert_buffer_type(bufferS,"s")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferS,1,offsetS,1)) { return; } // Check Buffer X and Y if(bufferX->dtype!=bufferY->dtype||bufferY->dtype!=bufferC->dtype|| bufferC->dtype!=bufferS->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X,Y,C and S", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_srot((blasint)n, &(((float *)bufferX->data)[offsetX]), (blasint)incX, &(((float *)bufferY->data)[offsetY]), (blasint)incY, ((float *)bufferC->data)[offsetC], ((float *)bufferS->data)[offsetS] ); break; case php_interop_polite_math_matrix_dtype_float64: cblas_drot((blasint)n, &(((double *)bufferX->data)[offsetX]), (blasint)incX, &(((double *)bufferY->data)[offsetY]), (blasint)incY, ((double *)bufferC->data)[offsetC], ((double *)bufferS->data)[offsetS] ); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function swap( int $n, Buffer $X, int $offsetX, int $incX, Buffer $Y, int $offsetY, int $incY ) : void {{{ */ static PHP_METHOD(Blas, swap) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zval* y=NULL; zend_long offsetY; zend_long incY; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 7, 7) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(incY) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) { return; } // Check Buffer Y bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferY,"y")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) { return; } // Check Buffer X and Y if(bufferX->dtype!=bufferY->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X and Y", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_sswap((blasint)n, &(((float *)bufferX->data)[offsetX]), (blasint)incX, &(((float *)bufferY->data)[offsetY]), (blasint)incY); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dswap((blasint)n, &(((double *)bufferX->data)[offsetX]), (blasint)incX, &(((double *)bufferY->data)[offsetY]), (blasint)incY); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function gemv( int $order, int $trans, int $m, int $n, float $alpha, Buffer $A, int $offsetA, int $ldA, Buffer $X, int $offsetX, int $incX, float $beta, Buffer $Y, int $offsetY, int $incY ) : void {{{ */ static PHP_METHOD(Blas, gemv) { php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; zend_long order; zend_long trans; zend_long m; zend_long n; double alpha; zval* a=NULL; zend_long offsetA; zend_long ldA; zval* x=NULL; zend_long offsetX; zend_long incX; double beta; zval* y=NULL; zend_long offsetY; zend_long incY; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 15, 15) Z_PARAM_LONG(order) Z_PARAM_LONG(trans) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_DOUBLE(beta) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(incY) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,m,n,offsetA,ldA)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } // Check Buffer Y bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferY,"y")) { return; } // Check Buffer size X and Y { zend_long rows,cols; if(trans==CblasNoTrans || trans==CblasConjNoTrans ) { rows = m; cols = n; } else if(trans==CblasTrans || trans==CblasConjTrans) { rows = n; cols = m; } else { zend_throw_exception(spl_ce_RuntimeException, "unknown transpose mode for bufferA.", 0); return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,cols,offsetX,incX)) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,rows,offsetY,incY)) { return; } } // Check Buffer A and X and Y if(bufferA->dtype!=bufferX->dtype || bufferX->dtype!=bufferY->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for A and X and Y", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_sgemv( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (blasint)m,(blasint)n, (float)alpha, &(((float *)bufferA->data)[offsetA]), (blasint)ldA, &(((float *)bufferX->data)[offsetX]), (blasint)incX, (float)beta, &(((float *)bufferY->data)[offsetY]), (blasint)incY); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dgemv( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (blasint)m,(blasint)n, (double)alpha, &(((double *)bufferA->data)[offsetA]), (blasint)ldA, &(((double *)bufferX->data)[offsetX]), (blasint)incX, (double)beta, &(((double *)bufferY->data)[offsetY]), (blasint)incY); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function gemm( int $order, int $transA, int $transB, int $m, int $n, int $k, float $alpha, Buffer $A, int $offsetA, int $ldA, Buffer $B, int $offsetB, int $ldB, float $beta, Buffer $C, int $offsetC, int $ldC ) : void {{{ */ static PHP_METHOD(Blas, gemm) { php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferB; php_interop_polite_math_matrix_linear_buffer_t* bufferC; zend_long order; zend_long transA; zend_long transB; zend_long m; zend_long n; zend_long k; double alpha; zval* a=NULL; zend_long offsetA; zend_long ldA; zval* b=NULL; zend_long offsetB; zend_long ldB; double beta; zval* c=NULL; zend_long offsetC; zend_long ldC; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 17, 17) Z_PARAM_LONG(order) Z_PARAM_LONG(transA) Z_PARAM_LONG(transB) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_LONG(k) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) Z_PARAM_OBJECT(b) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetB) Z_PARAM_LONG(ldB) Z_PARAM_DOUBLE(beta) Z_PARAM_OBJECT(c) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetC) Z_PARAM_LONG(ldC) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_K, k)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } { zend_long rows,cols; if(transA==CblasNoTrans || transA==CblasConjNoTrans) { rows = m; cols = k; } else if(transA==CblasTrans || transA==CblasConjTrans) { rows = k; cols = m; } else { zend_throw_exception(spl_ce_RuntimeException, "unknown transpose mode for bufferA.", 0); return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,rows,cols,offsetA,ldA)) { return; } } // Check Buffer B bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b); if(php_rindow_openblas_assert_buffer_type(bufferB,"b")) { return; } { zend_long rows,cols; if(transB==CblasNoTrans || transB==CblasConjNoTrans) { rows = k; cols = n; } else if(transB==CblasTrans || transB==CblasConjTrans) { rows = n; cols = k; } else { zend_throw_exception(spl_ce_RuntimeException, "unknown transpose mode for bufferB.", 0); return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,rows,cols,offsetB,ldB)) { return; } } // Check Buffer C bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c); if(php_rindow_openblas_assert_buffer_type(bufferC,"c")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_C, bufferC,m,n,offsetC,ldC)) { return; } // Check Buffer A and B and C if(bufferA->dtype!=bufferB->dtype || bufferB->dtype!=bufferC->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for A and B and C", 0); return; } switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_sgemm( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)transA, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)transB, (blasint)m,(blasint)n,(blasint)k, (float)alpha, &(((float *)bufferA->data)[offsetA]), (blasint)ldA, &(((float *)bufferB->data)[offsetB]), (blasint)ldB, (float)beta, &(((float *)bufferC->data)[offsetC]), (blasint)ldC); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dgemm( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)transA, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)transB, (blasint)m,(blasint)n,(blasint)k, (double)alpha, &(((double *)bufferA->data)[offsetA]), (blasint)ldA, &(((double *)bufferB->data)[offsetB]), (blasint)ldB, (double)beta, &(((double *)bufferC->data)[offsetC]), (blasint)ldC); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function symm( int $order, int $side, int $uplo, int $m, int $n, float $alpha, Buffer $A, int $offsetA, int $ldA, Buffer $B, int $offsetB, int $ldB, float $beta, Buffer $C, int $offsetC, int $ldC ) : void {{{ */ static PHP_METHOD(Blas, symm) { php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferB; php_interop_polite_math_matrix_linear_buffer_t* bufferC; zend_long order; zend_long side; zend_long uplo; zend_long m; zend_long n; double alpha; zval* a=NULL; zend_long offsetA; zend_long ldA; zval* b=NULL; zend_long offsetB; zend_long ldB; double beta; zval* c=NULL; zend_long offsetC; zend_long ldC; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 16, 16) Z_PARAM_LONG(order) Z_PARAM_LONG(side) Z_PARAM_LONG(uplo) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) Z_PARAM_OBJECT(b) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetB) Z_PARAM_LONG(ldB) Z_PARAM_DOUBLE(beta) Z_PARAM_OBJECT(c) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetC) Z_PARAM_LONG(ldC) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } if(!php_interop_polite_math_matrix_is_linear_buffer(bufferA)) { zend_throw_exception(zend_ce_type_error, "invalid type.", 0); return; } { zend_long rows; if(side==CblasLeft) { rows = m; } else if(side==CblasRight) { rows = n; } else { zend_throw_exception(spl_ce_RuntimeException, "unknown side mode for bufferA.", 0); return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,rows,rows,offsetA,ldA)) { return; } } // Check Buffer B bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b); if(php_rindow_openblas_assert_buffer_type(bufferB,"b")) { return; } { if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,m,n,offsetB,ldB)) { return; } } // Check Buffer C bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c); if(php_rindow_openblas_assert_buffer_type(bufferC,"c")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_C, bufferC,m,n,offsetC,ldC)) { return; } // Check Buffer A and B and C if(bufferA->dtype!=bufferB->dtype || bufferB->dtype!=bufferC->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for A and B and C", 0); return; } switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_ssymm( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_SIDE)side, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (blasint)m,(blasint)n, (float)alpha, &(((float *)bufferA->data)[offsetA]), (blasint)ldA, &(((float *)bufferB->data)[offsetB]), (blasint)ldB, (float)beta, &(((float *)bufferC->data)[offsetC]), (blasint)ldC); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dsymm( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_SIDE)side, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (blasint)m,(blasint)n, (double)alpha, &(((double *)bufferA->data)[offsetA]), (blasint)ldA, &(((double *)bufferB->data)[offsetB]), (blasint)ldB, (double)beta, &(((double *)bufferC->data)[offsetC]), (blasint)ldC); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function syrk( int $order, int $uplo, int $trans, int $n, int $k, float $alpha, Buffer $A, int $offsetA, int $ldA, float $beta, Buffer $C, int $offsetC, int $ldC ) : void {{{ */ static PHP_METHOD(Blas, syrk) { php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferC; zend_long order; zend_long uplo; zend_long trans; zend_long n; zend_long k; double alpha; zval* a=NULL; zend_long offsetA; zend_long ldA; double beta; zval* c=NULL; zend_long offsetC; zend_long ldC; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 13, 13) Z_PARAM_LONG(order) Z_PARAM_LONG(uplo) Z_PARAM_LONG(trans) Z_PARAM_LONG(n) Z_PARAM_LONG(k) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) Z_PARAM_DOUBLE(beta) Z_PARAM_OBJECT(c) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetC) Z_PARAM_LONG(ldC) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_K, k)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } { zend_long rows,cols; if(trans==CblasNoTrans || trans==CblasConjNoTrans) { rows = n; cols = k; } else if(trans==CblasTrans || trans==CblasConjTrans) { rows = k; cols = n; } else { zend_throw_exception(spl_ce_RuntimeException, "unknown transpose mode for bufferA.", 0); return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,rows,cols,offsetA,ldA)) { return; } } // Check Buffer C bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c); if(php_rindow_openblas_assert_buffer_type(bufferC,"c")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_C, bufferC,n,n,offsetC,ldC)) { return; } // Check Buffer A and C if(bufferA->dtype!=bufferC->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for A and C", 0); return; } switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_ssyrk( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (blasint)n,(blasint)k, (float)alpha, &(((float *)bufferA->data)[offsetA]), (blasint)ldA, (float)beta, &(((float *)bufferC->data)[offsetC]), (blasint)ldC); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dsyrk( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (blasint)n,(blasint)k, (double)alpha, &(((double *)bufferA->data)[offsetA]), (blasint)ldA, (double)beta, &(((double *)bufferC->data)[offsetC]), (blasint)ldC); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function syr2k( int $order, int $uplo, int $trans, int $n, int $k, float $alpha, Buffer $A, int $offsetA, int $ldA, Buffer $B, int $offsetB, int $ldB, float $beta, Buffer $C, int $offsetC, int $ldC ) : void {{{ */ static PHP_METHOD(Blas, syr2k) { php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferB; php_interop_polite_math_matrix_linear_buffer_t* bufferC; zend_long order; zend_long uplo; zend_long trans; zend_long n; zend_long k; double alpha; zval* a=NULL; zend_long offsetA; zend_long ldA; zval* b=NULL; zend_long offsetB; zend_long ldB; double beta; zval* c=NULL; zend_long offsetC; zend_long ldC; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 16, 16) Z_PARAM_LONG(order) Z_PARAM_LONG(uplo) Z_PARAM_LONG(trans) Z_PARAM_LONG(n) Z_PARAM_LONG(k) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) Z_PARAM_OBJECT(b) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetB) Z_PARAM_LONG(ldB) Z_PARAM_DOUBLE(beta) Z_PARAM_OBJECT(c) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetC) Z_PARAM_LONG(ldC) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, k)) { return; } // Check Buffer A and B bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b); if(php_rindow_openblas_assert_buffer_type(bufferB,"b")) { return; } { zend_long rows,cols; if(trans==CblasNoTrans || trans==CblasConjNoTrans) { rows = n; cols = k; } else if(trans==CblasTrans || trans==CblasConjTrans) { rows = k; cols = n; } else { zend_throw_exception(spl_ce_RuntimeException, "unknown transpose mode for bufferA.", 0); return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,rows,cols,offsetA,ldA)) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,rows,cols,offsetB,ldB)) { return; } } // Check Buffer C bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c); if(php_rindow_openblas_assert_buffer_type(bufferC,"c")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_C, bufferC,n,n,offsetC,ldC)) { return; } // Check Buffer A and B and C if(bufferA->dtype!=bufferB->dtype || bufferB->dtype!=bufferC->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for A and B and C", 0); return; } switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_ssyr2k( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (blasint)n,(blasint)k, (float)alpha, &(((float *)bufferA->data)[offsetA]), (blasint)ldA, &(((float *)bufferB->data)[offsetB]), (blasint)ldB, (float)beta, &(((float *)bufferC->data)[offsetC]), (blasint)ldC); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dsyr2k( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (blasint)n,(blasint)k, (double)alpha, &(((double *)bufferA->data)[offsetA]), (blasint)ldA, &(((double *)bufferB->data)[offsetB]), (blasint)ldB, (double)beta, &(((double *)bufferC->data)[offsetC]), (blasint)ldC); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function trmm( int $order, int $side, int $uplo, int $trans, int $diag, int $m, int $n, float $alpha, Buffer $A, int $offsetA, int $ldA, Buffer $B, int $offsetB, int $ldB) : void {{{ */ static PHP_METHOD(Blas, trmm) { php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferB; zend_long order; zend_long side; zend_long uplo; zend_long trans; zend_long diag; zend_long m; zend_long n; double alpha; zval* a=NULL; zend_long offsetA; zend_long ldA; zval* b=NULL; zend_long offsetB; zend_long ldB; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 14, 14) Z_PARAM_LONG(order) Z_PARAM_LONG(side) Z_PARAM_LONG(uplo) Z_PARAM_LONG(trans) Z_PARAM_LONG(diag) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) Z_PARAM_OBJECT(b) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetB) Z_PARAM_LONG(ldB) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } { zend_long sizeA; if(side==CblasLeft) { sizeA = m; } else if(side==CblasRight) { sizeA = n; } else { zend_throw_exception(spl_ce_RuntimeException, "unknown transpose mode for bufferA.", 0); return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,sizeA,sizeA,offsetA,ldA)) { return; } } bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b); if(php_rindow_openblas_assert_buffer_type(bufferB,"b")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,m,n,offsetB,ldB)) { return; } // Check Buffer A and B if(bufferA->dtype!=bufferB->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for A and B", 0); return; } switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_strmm( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_SIDE)side, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (OPENBLAS_CONST enum CBLAS_DIAG)diag, (blasint)m,(blasint)n, (float)alpha, &(((float *)bufferA->data)[offsetA]), (blasint)ldA, &(((float *)bufferB->data)[offsetB]), (blasint)ldB); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dtrmm( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_SIDE)side, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (OPENBLAS_CONST enum CBLAS_DIAG)diag, (blasint)m,(blasint)n, (double)alpha, &(((double *)bufferA->data)[offsetA]), (blasint)ldA, &(((double *)bufferB->data)[offsetB]), (blasint)ldB); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Blas:: public function trsm( int $order, int $side, int $uplo, int $trans, int $diag, int $m, int $n, float $alpha, Buffer $A, int $offsetA, int $ldA, Buffer $B, int $offsetB, int $ldB) : void {{{ */ static PHP_METHOD(Blas, trsm) { php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferB; zend_long order; zend_long side; zend_long uplo; zend_long trans; zend_long diag; zend_long m; zend_long n; double alpha; zval* a=NULL; zend_long offsetA; zend_long ldA; zval* b=NULL; zend_long offsetB; zend_long ldB; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 14, 14) Z_PARAM_LONG(order) Z_PARAM_LONG(side) Z_PARAM_LONG(uplo) Z_PARAM_LONG(trans) Z_PARAM_LONG(diag) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) Z_PARAM_OBJECT(b) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetB) Z_PARAM_LONG(ldB) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } { zend_long sizeA; if(side==CblasLeft) { sizeA = m; } else if(side==CblasRight) { sizeA = n; } else { zend_throw_exception(spl_ce_RuntimeException, "unknown transpose mode for bufferA.", 0); return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,sizeA,sizeA,offsetA,ldA)) { return; } } bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b); if(php_rindow_openblas_assert_buffer_type(bufferB,"b")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,m,n,offsetB,ldB)) { return; } // Check Buffer A and B if(bufferA->dtype!=bufferB->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for A and B", 0); return; } switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: cblas_strsm( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_SIDE)side, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (OPENBLAS_CONST enum CBLAS_DIAG)diag, (blasint)m,(blasint)n, (float)alpha, &(((float *)bufferA->data)[offsetA]), (blasint)ldA, &(((float *)bufferB->data)[offsetB]), (blasint)ldB); break; case php_interop_polite_math_matrix_dtype_float64: cblas_dtrsm( (OPENBLAS_CONST enum CBLAS_ORDER)order, (OPENBLAS_CONST enum CBLAS_SIDE)side, (OPENBLAS_CONST enum CBLAS_UPLO)uplo, (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans, (OPENBLAS_CONST enum CBLAS_DIAG)diag, (blasint)m,(blasint)n, (double)alpha, &(((double *)bufferA->data)[offsetA]), (blasint)ldA, &(((double *)bufferB->data)[offsetB]), (blasint)ldB); break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ ZEND_BEGIN_ARG_INFO_EX(ai_Blas_scal, 0, 0, 5) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_axpy, 0, 0, 8) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_dot, 0, 0, 7) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_asum, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_iamax, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() #ifdef OPENBLAS_HAVE_IAMIN ZEND_BEGIN_ARG_INFO_EX(ai_Blas_iamin, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(ai_Blas_copy, 0, 0, 7) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_nrm2, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_rotg, 0, 0, 8) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_ARG_OBJ_INFO(0, c, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetC) ZEND_ARG_OBJ_INFO(0, s, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetS) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_rot, 0, 0, 11) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_ARG_OBJ_INFO(0, c, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetC) ZEND_ARG_OBJ_INFO(0, s, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetS) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_swap, 0, 0, 7) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_gemv, 0, 0, 15) ZEND_ARG_INFO(0, order) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, ldA) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_INFO(0, beta) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_gemm, 0, 0, 17) ZEND_ARG_INFO(0, order) ZEND_ARG_INFO(0, transA) ZEND_ARG_INFO(0, transB) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, k) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, ldA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_ARG_INFO(0, ldB) ZEND_ARG_INFO(0, beta) ZEND_ARG_OBJ_INFO(0, c, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetC) ZEND_ARG_INFO(0, ldC) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_symm, 0, 0, 16) ZEND_ARG_INFO(0, order) ZEND_ARG_INFO(0, side) ZEND_ARG_INFO(0, uplo) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, ldA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_ARG_INFO(0, ldB) ZEND_ARG_INFO(0, beta) ZEND_ARG_OBJ_INFO(0, c, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetC) ZEND_ARG_INFO(0, ldC) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_syrk, 0, 0, 13) ZEND_ARG_INFO(0, order) ZEND_ARG_INFO(0, uplo) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, k) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, ldA) ZEND_ARG_INFO(0, beta) ZEND_ARG_OBJ_INFO(0, c, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetC) ZEND_ARG_INFO(0, ldC) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_syr2k, 0, 0, 16) ZEND_ARG_INFO(0, order) ZEND_ARG_INFO(0, uplo) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, k) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, ldA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_ARG_INFO(0, ldB) ZEND_ARG_INFO(0, beta) ZEND_ARG_OBJ_INFO(0, c, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetC) ZEND_ARG_INFO(0, ldC) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_trmm, 0, 0, 14) ZEND_ARG_INFO(0, order) ZEND_ARG_INFO(0, side) ZEND_ARG_INFO(0, uplo) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, diag) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, ldA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_ARG_INFO(0, ldB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_trsm, 0, 0, 14) ZEND_ARG_INFO(0, order) ZEND_ARG_INFO(0, side) ZEND_ARG_INFO(0, uplo) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, diag) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, ldA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_ARG_INFO(0, ldB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Blas_void, 0, 0, 0) ZEND_END_ARG_INFO() /* {{{ Rindow\OpenBLAS\Blas function entries */ static zend_function_entry php_rindow_openblas_blas_me[] = { /* clang-format off */ PHP_ME(Blas, getNumThreads, ai_Blas_void, ZEND_ACC_PUBLIC) PHP_ME(Blas, getNumProcs, ai_Blas_void, ZEND_ACC_PUBLIC) PHP_ME(Blas, getConfig, ai_Blas_void, ZEND_ACC_PUBLIC) PHP_ME(Blas, getCorename, ai_Blas_void, ZEND_ACC_PUBLIC) PHP_ME(Blas, scal, ai_Blas_scal, ZEND_ACC_PUBLIC) PHP_ME(Blas, axpy, ai_Blas_axpy, ZEND_ACC_PUBLIC) PHP_ME(Blas, dot, ai_Blas_dot, ZEND_ACC_PUBLIC) PHP_ME(Blas, asum, ai_Blas_asum, ZEND_ACC_PUBLIC) PHP_ME(Blas, iamax, ai_Blas_iamax, ZEND_ACC_PUBLIC) #ifdef OPENBLAS_HAVE_IAMIN PHP_ME(Blas, iamin, ai_Blas_iamin, ZEND_ACC_PUBLIC) #endif PHP_ME(Blas, copy, ai_Blas_copy, ZEND_ACC_PUBLIC) PHP_ME(Blas, nrm2, ai_Blas_nrm2, ZEND_ACC_PUBLIC) PHP_ME(Blas, rotg, ai_Blas_rotg, ZEND_ACC_PUBLIC) PHP_ME(Blas, rot, ai_Blas_rot, ZEND_ACC_PUBLIC) PHP_ME(Blas, swap, ai_Blas_swap, ZEND_ACC_PUBLIC) PHP_ME(Blas, gemv, ai_Blas_gemv, ZEND_ACC_PUBLIC) PHP_ME(Blas, gemm, ai_Blas_gemm, ZEND_ACC_PUBLIC) PHP_ME(Blas, symm, ai_Blas_symm, ZEND_ACC_PUBLIC) PHP_ME(Blas, syrk, ai_Blas_syrk, ZEND_ACC_PUBLIC) PHP_ME(Blas, syr2k, ai_Blas_syr2k, ZEND_ACC_PUBLIC) PHP_ME(Blas, trmm, ai_Blas_trmm, ZEND_ACC_PUBLIC) PHP_ME(Blas, trsm, ai_Blas_trsm, ZEND_ACC_PUBLIC) PHP_FE_END /* clang-format on */ }; /* }}} */ /* Class Rindow\OpenBLAS\Blas {{{ */ static zend_class_entry* rindow_openblas_blas_ce; void php_rindow_openblas_blas_init_ce(INIT_FUNC_ARGS) { zend_class_entry ce; INIT_NS_CLASS_ENTRY(ce, "Rindow\\OpenBLAS", "Blas", php_rindow_openblas_blas_me); rindow_openblas_blas_ce = zend_register_internal_class(&ce); rindow_openblas_blas_ce->create_object = php_rindow_openblas_blas_create_object; memcpy(&rindow_openblas_blas_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); rindow_openblas_blas_object_handlers.offset = 0; rindow_openblas_blas_object_handlers.free_obj = php_rindow_openblas_blas_free_object; rindow_openblas_blas_object_handlers.clone_obj = NULL; //zend_class_implements(rindow_openblas_blas_ce, 2, spl_ce_ArrayAccess, spl_ce_Countable); } /* }}} */
{ "alphanum_fraction": 0.6425979733, "avg_line_length": 32.8164136622, "ext": "c", "hexsha": "b29deacae898fcd57f2996bc02863d2c5d0fbed6", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-08-11T19:59:53.000Z", "max_forks_repo_forks_event_min_datetime": "2021-08-11T19:59:53.000Z", "max_forks_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "yuichiis/rindow-openblas", "max_forks_repo_path": "src/Rindow/OpenBLAS/Blas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "yuichiis/rindow-openblas", "max_issues_repo_path": "src/Rindow/OpenBLAS/Blas.c", "max_line_length": 113, "max_stars_count": 9, "max_stars_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "yuichiis/rindow-openblas", "max_stars_repo_path": "src/Rindow/OpenBLAS/Blas.c", "max_stars_repo_stars_event_max_datetime": "2022-02-28T05:59:12.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-15T05:12:39.000Z", "num_tokens": 19051, "size": 69177 }
#ifndef MATHLAB_H #define MATHLAB_H #define USE_MKL 0 #define USE_OPENBLAS 1 #if USE_MKL #include <mkl.h> #elif USE_OPENBLAS #include <cblas.h> #endif #endif
{ "alphanum_fraction": 0.7530864198, "avg_line_length": 10.8, "ext": "h", "hexsha": "82bd28ae1a1a865ce6c691b925d0f195bea00b48", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2018-05-29T23:56:17.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-18T06:09:03.000Z", "max_forks_repo_head_hexsha": "0872ae3ad5398ab1acf1cc53bcf027d65ea04cfb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "TaoHuUMD/Winograd_Convolution", "max_forks_repo_path": "github_winograd/include/mathlib.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0872ae3ad5398ab1acf1cc53bcf027d65ea04cfb", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "TaoHuUMD/Winograd_Convolution", "max_issues_repo_path": "github_winograd/include/mathlib.h", "max_line_length": 22, "max_stars_count": 10, "max_stars_repo_head_hexsha": "0872ae3ad5398ab1acf1cc53bcf027d65ea04cfb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "tsyj0404/winograd_convolution", "max_stars_repo_path": "github_winograd/include/mathlib.h", "max_stars_repo_stars_event_max_datetime": "2019-11-06T10:47:32.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-18T06:08:50.000Z", "num_tokens": 53, "size": 162 }
/** * Finite element method solver. This solver solves laplace(u) = 6 on square * [0, 1]x[0, 1]. Boundary conditions are set to be 1 + x^2 + 2y^2. * * Exact solution of this problem is 1 + x^2 + 2y^2. We will test against this * solution in the end. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include <lapacke.h> #include <triangle.h> #define F -6.0 #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) static void compute_local_a(uint *point_id, REAL *pointlist, REAL *matrix); static void compute_local_f(uint *point_id, REAL *pointlist, REAL *matrix); static void generate_mesh(struct triangulateio *io, struct triangulateio *out); static REAL boundary_condition(uint point_id, struct triangulateio *out); static REAL exact_solution(uint point_id, struct triangulateio *out); int main(int argc, char **argv) { struct triangulateio in, out; uint num_of_points; uint num_of_triangles; REAL *local_A, *local_F, *global_A, *global_F; /* generate geometry */ generate_mesh(&in, &out); num_of_points = out.numberofpoints; num_of_triangles = out.numberoftriangles; /** * Allocate all matrix data structures */ global_A = malloc(num_of_points * num_of_points * sizeof(REAL)); global_F = malloc(num_of_points * sizeof(REAL)); local_A = malloc(3 * 3 * sizeof(REAL)); local_F = malloc(3 * 3 * sizeof(REAL)); assert(global_A != NULL); assert(global_F != NULL); assert(local_A != NULL); assert(local_F != NULL); memset(global_A, 0, num_of_points * num_of_points * sizeof(REAL)); memset(global_F, 0, num_of_points * sizeof(REAL)); /** * Matrix assembly without boundary conditions */ for (size_t n = 0; n < num_of_triangles; n++) { // three points that describe triangle uint point_id[3]; memcpy(point_id, &out.trianglelist[n * 3], 3 * sizeof(int)); compute_local_a(point_id, out.pointlist, local_A); compute_local_f(point_id, out.pointlist, local_F); for (size_t i = 0; i < 3; i++) { int i1 = point_id[i]; for (int j = 0; j < 3; j++) { int j1 = point_id[j]; global_A[i1 * num_of_points + j1] += local_A[i * 3 + j]; global_F[i1] += local_F[i * 3 + j] * F; } } } for (size_t i = 0; i < num_of_points; i++) { if (out.pointmarkerlist[i] == 1) { for (size_t j = 0; j < num_of_points; j++) { global_F[j] -= global_A[j * num_of_points + i] * boundary_condition(i, &out); global_A[i * num_of_points + j] = 0; global_A[j * num_of_points + i] = 0; } global_A[i * num_of_points + i] = 1.0; global_F[i] = boundary_condition(i, &out); } } /************************************************************************* ************************ Solve Ax = b *********************************** *************************************************************************/ int ipiv[num_of_points]; int info = LAPACKE_dgesv(LAPACK_ROW_MAJOR, num_of_points, 1, global_A, num_of_points, ipiv, global_F, 1); if (info > 0) { printf("The factorization has been completed, but the factor U is\n"); printf("exactly singular, so the solution could not be computed."); goto mem_free; } else if (info < 0) { printf("%d-th argument had an illegal value\n", -info); goto mem_free; } //TODO: implement max error printf("\nSolution in point vs exact solution\n"); for (size_t i = 0; i < num_of_points; i++) { double temp = exact_solution(i, &out); printf( "%lf \t %lf \t %lf\n", temp, global_F[i], temp - global_F[i]); } mem_free: /* free all Triangle data structures */ free(out.edgelist); free(out.edgemarkerlist); free(out.neighborlist); free(out.pointlist); free(out.trianglelist); free(out.segmentlist); free(out.segmentmarkerlist); free(out.pointmarkerlist); /* free all input data structures */ free(in.regionlist); free(in.pointlist); /* free all matrix arrays */ free(global_A); free(local_A); free(global_F); free(local_F); return info; } static void generate_mesh(struct triangulateio *in, struct triangulateio *out) { in->numberofpoints = 4; in->numberofpointattributes = 0; in->pointattributelist = (REAL *) NULL; in->pointlist = malloc(in->numberofpoints * 2 * sizeof(REAL)); in->pointlist[0] = 0.0; in->pointlist[1] = 0.0; in->pointlist[2] = 0.0; in->pointlist[3] = 1.0; in->pointlist[4] = 1.0; in->pointlist[5] = 1.0; in->pointlist[6] = 1.0; in->pointlist[7] = 0.0; in->pointmarkerlist = (int *) NULL; in->numberofsegments = 0; in->numberofholes = 0; in->numberofregions = 1; in->regionlist = malloc(in->numberofregions * 4 * sizeof(REAL)); in->regionlist[0] = 0.5; in->regionlist[1] = 0.5; in->regionlist[2] = 7.0; /* Regional attribute (for whole mesh). */ in->regionlist[3] = 0.1; /* Area constraint. */ out->pointlist = (REAL *) NULL; out->pointmarkerlist = (int *) NULL; out->trianglelist = (int *) NULL; out->triangleattributelist = (REAL *) NULL; out->neighborlist = (int *) NULL; out->segmentlist = (int *) NULL; out->segmentmarkerlist = (int *) NULL; out->edgelist = (int *) NULL; out->edgemarkerlist = (int *) NULL; /* Triangulate the points. read and write a PSLG (p), preserve the * convex hull (c), zero index (z), produce edge list (e), produce * neighbor list (n), be quiet (Q), area should be less than 0.1 (a.1) * and generate triangle for FEM (q). */ triangulate("pzceQna.1q", in, out, (struct triangulateio *) NULL); } static void compute_local_a(uint *point_id, REAL *pointlist, REAL *matrix) { REAL dx23 = pointlist[2 * point_id[1]] - pointlist[2 * point_id[2]]; REAL dx31 = pointlist[2 * point_id[2]] - pointlist[2 * point_id[0]]; REAL dx12 = pointlist[2 * point_id[0]] - pointlist[2 * point_id[1]]; REAL dy23 = pointlist[2 * point_id[1] + 1] - pointlist[2 * point_id[2] + 1]; REAL dy31 = pointlist[2 * point_id[2] + 1] - pointlist[2 * point_id[0] + 1]; REAL dy12 = pointlist[2 * point_id[0] + 1] - pointlist[2 * point_id[1] + 1];; REAL area = 0.5 * (dx31 * dy12 - dy31 * dx12); REAL _tmp_mult = 0.25 / area; matrix[0] = _tmp_mult * (dx23 * dx23 + dy23 * dy23); matrix[1] = _tmp_mult * (dx23 * dx31 + dy23 * dy31); matrix[2] = _tmp_mult * (dx23 * dx12 + dy23 * dy12); matrix[3] = _tmp_mult * (dx31 * dx23 + dy31 * dy23); matrix[4] = _tmp_mult * (dx31 * dx31 + dy31 * dy31); matrix[5] = _tmp_mult * (dx31 * dx12 + dy31 * dy12); matrix[6] = _tmp_mult * (dx12 * dx23 + dy12 * dy23); matrix[7] = _tmp_mult * (dx12 * dx31 + dy12 * dy31); matrix[8] = _tmp_mult * (dx12 * dx12 + dy12 * dy12); } static inline void compute_local_f(uint *point_id, REAL *pointlist, REAL *matrix) { REAL dx31 = pointlist[2 * point_id[2]] - pointlist[2 * point_id[0]]; REAL dx12 = pointlist[2 * point_id[0]] - pointlist[2 * point_id[1]]; REAL dy31 = pointlist[2 * point_id[2] + 1] - pointlist[2 * point_id[0] + 1]; REAL dy12 = pointlist[2 * point_id[0] + 1] - pointlist[2 * point_id[1] + 1]; REAL area = 0.5 * (dx31 * dy12 - dy31 * dx12); REAL c_diag = area / 6.0; REAL c_off = area / 12.0; matrix[0] = c_diag; matrix[1] = c_off; matrix[2] = c_off; matrix[3] = c_off; matrix[4] = c_diag; matrix[5] = c_off; matrix[6] = c_off; matrix[7] = c_off; matrix[8] = c_diag; } static inline REAL exact_solution(uint point_id, struct triangulateio *out) { REAL x = out->pointlist[2 * point_id]; REAL y = out->pointlist[2 * point_id + 1]; return (1.0 + x * x + 2.0 * y * y); } static inline REAL boundary_condition(uint point_id, struct triangulateio *out) { REAL x = out->pointlist[2 * point_id]; REAL y = out->pointlist[2 * point_id + 1]; return (1.0 + x * x + 2.0 * y * y); }
{ "alphanum_fraction": 0.5675359607, "avg_line_length": 35.0450819672, "ext": "c", "hexsha": "9961bb725ae4bc29648e9f3e59720b28fb921edc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "59b6f6e79f2852a8041013d029b388d90e555a21", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "djanekovic/fem2d_poisson", "max_forks_repo_path": "src/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "59b6f6e79f2852a8041013d029b388d90e555a21", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "djanekovic/fem2d_poisson", "max_issues_repo_path": "src/main.c", "max_line_length": 85, "max_stars_count": null, "max_stars_repo_head_hexsha": "59b6f6e79f2852a8041013d029b388d90e555a21", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "djanekovic/fem2d_poisson", "max_stars_repo_path": "src/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2536, "size": 8551 }
#include <stdio.h> #include "sweeny_dc.h" #include <gsl/gsl_rng.h> #include <math.h> #include "../src/dyncon.h" #include <ctype.h> #define MIN(a,b) a<=b ? a: b #define MAX(a,b) a>=b? a:b static char verbose = 0; static char equilibration=1; static char setup=0; static __u32 DX; static __u32 seed; static __u32 cutoff; static __u32 steps; static double beta; static double coupling; static double q; static double rnd_num; static double v; static __u32 j=0; static __s8 dB = 0,dN=0; static gsl_rng *r; static Edge *cEdge; static double rcWeights[4]; // array with precalculated mc weights static double p_min_del,p_max_del, p_min_ins,p_max_ins; static __u32 *num_bonds, *num_cluster, *size_giant; static __u64 *sec_cs_moment,*four_cs_moment; /****************************************************************************** *****************************************************************************/ static void extract_observables(__u32 i) { static __u32 clust_cnt=0; static __u64 sum=0,sum_2=0; static __u32 maxc=0; static s_tree *c; num_bonds[i] = nte + te; c = levels[0]->head; while(c) { clust_cnt++; sum += pow(c->root->n,2);//*c->root->n; sum_2 += pow(c->root->n,4); if(c->root->n > maxc) maxc = c->root->n; c = c->next; } num_cluster[i] = clust_cnt; size_giant[i] = maxc; sec_cs_moment[i] = sum; four_cs_moment[i] = sum_2; sum=sum_2=0; maxc = 0; clust_cnt=0; } /****************************************************************************** *****************************************************************************/ static inline void mcStep(void) { // get a randomly selected edge cEdge = &adjMatrix[gsl_rng_uniform_int(r,2*DX*DX)]; rnd_num = gsl_rng_uniform(r); if(ACTIVE_EDGE(cEdge)) { //edge is active hence delete it dB = -1; if(rnd_num < p_min_del) { delete_dc(cEdge); } else { if(rnd_num < p_max_del) { dN = delete_dc(cEdge); if(rnd_num >= rcWeights[dB == -1? dN : 2-dN]) insert_dc(cEdge); } } } else { // Insert cedge. If adjacent vertices are already connected, the new // edge will be a non-tree edge, i.e. dN = 0 dB = 1; if(rnd_num < p_min_ins) { insert_dc(cEdge); } else { if(rnd_num < p_max_ins) { dN = connected_dc_e(cEdge,1) ? 0: -1; dB = 1; if(rnd_num < rcWeights[dB == -1? dN : 2-dN]) insert_dc(cEdge); } } } } /****************************************************************************** *****************************************************************************/ static inline void sweep() { for(j=0;j<2*DX*DX;j++)mcStep(); } /****************************************************************************** *****************************************************************************/ char init_sweeny_dc(double _q,unsigned int _l,double _beta,double _coupl, unsigned int _cutoff,unsigned _tslength,unsigned int rng_seed, void *ts_0,void *ts_1,void * ts_2,void *ts_3, void *ts_4) { q = _q; DX = _l; beta = _beta; coupling = _coupl; cutoff = _cutoff; steps = _tslength; seed = rng_seed; num_bonds = (__u32 *)ts_0; num_cluster = (__u32 *)ts_1; size_giant = (__u32 *)ts_2; sec_cs_moment = (__u64 *)ts_3; four_cs_moment = (__u64 *)ts_4; r = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(r,seed); v = exp(coupling*beta) - 1.; // >0 rcWeights[0] = pow(v,-1); //db==-1,dN==0 rcWeights[1] = rcWeights[0]*q; //db==-1,dN=1 rcWeights[2] = v; //db==1,dN==0 rcWeights[3] = v*pow(q,-1); //db==1,dN==-1 p_min_del = MIN(rcWeights[0],rcWeights[1]); p_max_del = MAX(rcWeights[0],rcWeights[1]); p_min_ins = MIN(rcWeights[2],rcWeights[3]); p_max_ins = MAX(rcWeights[2],rcWeights[3]); return setup=(r && init_dc(DX)); } /****************************************************************************** *****************************************************************************/ void destroy_sweeny_dc(void) { if(setup) { gsl_rng_free(r); destroy_dc(); } setup=0; } /****************************************************************************** *****************************************************************************/ char simulate_sweeny_dc(void) { if(!setup) return 0; __u32 i; for(i=0;i<cutoff;i++)sweep(); if(verbose) printf("Equilibration done!\n"); equilibration=0; for(i=0;i<steps;i++){ sweep(); extract_observables(i); } return 1; } /****************************************************************************** *****************************************************************************/
{ "alphanum_fraction": 0.4621621622, "avg_line_length": 27.8034682081, "ext": "c", "hexsha": "a7b925bdeea833868cda6bb87ecfa72b8e087d8c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2017-04-10T14:18:57.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-10T14:18:57.000Z", "max_forks_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ermeel86/sweeny", "max_forks_repo_path": "src/sweeny_dc.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be", "max_issues_repo_issues_event_max_datetime": "2018-08-20T09:32:03.000Z", "max_issues_repo_issues_event_min_datetime": "2018-08-19T09:29:25.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ernmeel/sweeny", "max_issues_repo_path": "src/sweeny_dc.c", "max_line_length": 79, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ernmeel/sweeny", "max_stars_repo_path": "src/sweeny_dc.c", "max_stars_repo_stars_event_max_datetime": "2017-04-10T14:18:40.000Z", "max_stars_repo_stars_event_min_datetime": "2017-03-03T10:57:43.000Z", "num_tokens": 1269, "size": 4810 }
/** * @file testmatmultc.c * @author Jeff Daily, PNNL jeff.daily@pnl.gov * * This is the C version of testmatmul.F. The port was as direct as possible, * hopefully. */ #if HAVE_CONFIG_H # include "config.h" #endif #include <math.h> #include <stdlib.h> #if defined(USE_ELEMENTAL) #include <cblas.h> #include "El.h" int me, nproc; ElGlobalArrays_d eldga; #else #include "mp3.h" #include "ga.h" #include "macdecls.h" #include "xgemm.h" #endif void load_ga(int handle, double *f, int dim1, int dim2); void verify_ga_dgemm(char xt1, char xt2, int num_m, int num_n, int num_k, double alpha, int g_a, int g_b, double beta, int g_c, double *tmpa, double *tmpb, double *tmpc); #define dgemm_verify 1 #define nummax 1024 #define howmany 2 #define ntrans 4 #if defined(USE_ELEMENTAL) #define MP_TIMER MPI_Wtime void GA_Error (const char *str, int item) { printf ("%s: %d\n", str, item); MPI_Abort(MPI_COMM_WORLD, -101); } #endif /* * test ga_dgemm * Note: - change nummax for large arrays * - turn off "dgemm_verify" for large arrays due to memory * limitations, as dgemm_verify=1 for large arrays produces * segfault, dumps core,or any crap. */ int main(int argc, char **argv) { int num_m; int num_n; int num_k; int i; int ii; double *h0; int g_c; int g_b; int g_a; double a; double t1; double mf; double avg_t[ntrans]; double avg_mf[ntrans]; int itime; int ntimes; int nums_m[/*howmany*/] = {512,1024}; int nums_n[/*howmany*/] = {512,1024}; int nums_k[/*howmany*/] = {512,1024}; char transa[/*ntrans*/] = "ntnt"; char transb[/*ntrans*/] = "nntt"; char ta; char tb; double *tmpa; double *tmpb; double *tmpc; int ndim; int dims[2]; #ifdef BLOCK_CYCLIC int block_size[2]; #endif #if defined(USE_ELEMENTAL) // initialize Elemental (which will initialize MPI) ElInitialize( &argc, &argv ); ElMPICommRank( MPI_COMM_WORLD, &me ); ElMPICommSize( MPI_COMM_WORLD, &nproc ); // instantiate el::global array ElGlobalArraysConstruct_d( &eldga ); // initialize global arrays ElGlobalArraysInitialize_d( eldga ); #else MP_INIT(argc,argv); if (!MA_init(MT_DBL,1,20000000)) { GA_Error("failed: ma_init(MT_DBL,1,20000000)",10); } GA_INIT(argc,argv); me = GA_Nodeid(); #endif h0 = (double*)malloc(sizeof(double) * nummax*nummax); tmpa = (double*)malloc(sizeof(double) * nummax*nummax); tmpb = (double*)malloc(sizeof(double) * nummax*nummax); tmpc = (double*)malloc(sizeof(double) * nummax*nummax); ii = 0; for (i=0; i<nummax*nummax; i++) { ii = ii + 1; if (ii > nummax) { ii = 0; } h0[i] = ii; } /* Compute times assuming 500 mflops and 5 second target time */ /* ntimes = max(3.0d0,5.0d0/(4.0d-9*num**3)); */ ntimes = 5; for (ii=0; ii<howmany; ii++) { num_m = nums_m[ii]; num_n = nums_n[ii]; num_k = nums_k[ii]; a = 0.5/(num_m*num_n); if (num_m > nummax || num_n > nummax || num_k > nummax) { GA_Error("Insufficient memory: check nummax", 1); } #ifndef BLOCK_CYCLIC ndim = 2; /* dims[0] = num_m; dims[1] = num_n; */ dims[1] = num_m; dims[0] = num_n; #if defined(USE_ELEMENTAL) ElGlobalArraysCreate_d( eldga, ndim, dims, "g_c", NULL, &g_c ); #else if (!((g_c = NGA_Create(MT_DBL,ndim,dims,"g_c",NULL)))) { GA_Error("failed: create g_c",20); } #endif /* dims[0] = num_k; dims[1] = num_n; */ dims[1] = num_k; dims[0] = num_n; #if defined(USE_ELEMENTAL) ElGlobalArraysCreate_d( eldga, ndim, dims, "g_b", NULL, &g_b ); #else if (!((g_b = NGA_Create(MT_DBL,ndim,dims,"g_b",NULL)))) { GA_Error("failed: create g_b",30); } #endif /* dims[0] = num_m; dims[1] = num_k; */ dims[1] = num_m; dims[0] = num_k; #if defined(USE_ELEMENTAL) ElGlobalArraysCreate_d( eldga, ndim, dims, "g_a", NULL, &g_a ); #else if (!((g_a = NGA_Create(MT_DBL,ndim,dims,"g_a",NULL)))) { GA_Error("failed: create g_a",40); } #endif #else ndim = 2; block_size[0] = 128; block_size[1] = 128; dims[0] = num_m; dims[1] = num_n; g_c = GA_Create_handle(); GA_Set_data(g_c,ndim,dims,MT_DBL); GA_Set_array_name(g_c,"g_c"); GA_Set_block_cyclic(g_c,block_size); if (!GA_Allocate(g_c)) { GA_Error("failed: create g_c",40); } dims[0] = num_k; dims[1] = num_n; g_b = GA_Create_handle(); GA_Set_data(g_b,ndim,dims,MT_DBL); GA_Set_array_name(g_b,"g_b"); GA_Set_block_cyclic(g_b,block_size); if (!ga_allocate(g_b)) { GA_Error("failed: create g_b",40); } dims[0] = num_m; dims[1] = num_k; g_a = GA_Create_handle(); GA_Set_data(g_a,ndim,dims,MT_DBL); GA_Set_array_name(g_a,"g_a"); GA_Set_block_cyclic(g_a,block_size); if (!ga_allocate(g_a)) { GA_Error('failed: create g_a',40); } #endif /* Initialize matrices A and B */ if (me == 0) { load_ga(g_a, h0, num_m, num_k); load_ga(g_b, h0, num_k, num_n); } #if defined(USE_ELEMENTAL) double zero = 0.0; ElGlobalArraysFill_d( eldga, g_c, &zero ); ElGlobalArraysSync_d( eldga ); #else GA_Zero(g_c); GA_Sync(); #endif #if defined(USE_ELEMENTAL) if (me == 0) { #else if (GA_Nodeid() == 0) { #endif printf("\nMatrix Multiplication on C = A[%ld,%ld]xB[%ld,%ld]\n", (long)num_m, (long)num_k, (long)num_k, (long)num_n); fflush(stdout); } for (i=0; i<ntrans; i++) { avg_t[i] = 0.0; avg_mf[i] = 0.0; } for (itime=0; itime<ntimes; itime++) { for (i=0; i<ntrans; i++) { #if defined(USE_ELEMENTAL) ElGlobalArraysSync_d( eldga ); #else GA_Sync(); #endif ta = transa[i]; tb = transb[i]; t1 = MP_TIMER(); #if defined(USE_ELEMENTAL) ElGlobalArraysDgemm_d( eldga, ta, tb, num_m, num_n, num_k, 1.0, g_a, g_b, 0.0, g_c ); #else GA_Dgemm(ta,tb,num_m,num_n,num_k,1.0, g_a, g_b, 0.0, g_c); #endif t1 = MP_TIMER() - t1; #if defined(USE_ELEMENTAL) if (me == 0) { #else if (GA_Nodeid() == 0) { #endif #if defined(USE_ELEMENTAL) mf = 2e0*num_m*num_n*num_k/t1*1e-6/nproc; #else mf = 2e0*num_m*num_n*num_k/t1*1e-6/GA_Nnodes(); #endif avg_t[i] = avg_t[i]+t1; avg_mf[i] = avg_mf[i] + mf; printf("%15s%2d: %12.4f seconds %12.1f mflops/proc %c %c\n", "Run#", itime, t1, mf, ta, tb); fflush(stdout); if (dgemm_verify && itime == 0) { /* recall the C API swaps the matrix order */ /* we swap it here for the Fortran-based verify */ verify_ga_dgemm(tb, ta, num_n, num_m, num_k, 1.0, g_b, g_a, 0.0, g_c, tmpb, tmpa, tmpc); } } } } #if defined(USE_ELEMENTAL) if (me == 0) { #else if (GA_Nodeid() == 0) { #endif printf("\n"); for (i=0; i<ntrans; i++) { printf("%17s: %12.4f seconds %12.1f mflops/proc %c %c\n", "Average", avg_t[i]/ntimes, avg_mf[i]/ntimes, transa[i], transb[i]); } if(dgemm_verify) { printf("All GA_Dgemms are verified...O.K.\n"); } fflush(stdout); } /* GA_Print(g_a); GA_Print(g_b); GA_Print(g_c); */ #if defined(USE_ELEMENTAL) ElGlobalArraysDestroy_d( eldga, g_a ); ElGlobalArraysDestroy_d( eldga, g_b ); ElGlobalArraysDestroy_d( eldga, g_c ); #else GA_Destroy(g_c); GA_Destroy(g_b); GA_Destroy(g_a); #endif } /* ??? format(a15, i2, ': ', e12.4, ' seconds ',f12.1, . ' mflops/proc ', 3a2) */ #if defined(USE_ELEMENTAL) if (me == 0) { #else if (GA_Nodeid() == 0) { #endif printf("All tests successful\n"); } free(h0); free(tmpa); free(tmpb); free(tmpc); #if defined(USE_ELEMENTAL) // call el::global arrays destructor ElGlobalArraysTerminate_d( eldga ); ElGlobalArraysDestruct_d( eldga ); ElFinalize(); #else GA_Terminate(); MP_FINALIZE(); #endif return 0; } /* * Verify for correctness. Process 0 computes BLAS dgemm * locally. For larger arrays, disbale this test as memory * might not be sufficient */ void verify_ga_dgemm(char xt1, char xt2, int num_m, int num_n, int num_k, double alpha, int g_a, int g_b, double beta, int g_c, double *tmpa, double *tmpb, double *tmpc) { int i,j,type,ndim,dims[2],lo[2],hi[2]; double abs_value; for (i=0; i<num_n; i++) { for (j=0; j<num_m; j++) { tmpc[j+i*num_m] = -1.0; tmpa[j+i*num_m] = -2.0; } } #if defined(USE_ELEMENTAL) ElGlobalArraysInquire_d( eldga, g_a, &ndim, dims ); #else NGA_Inquire(g_a, &type, &ndim, dims); #endif lo[0] = 0; lo[1] = 0; hi[0] = dims[0]-1; hi[1] = dims[1]-1; #if defined(USE_ELEMENTAL) ElGlobalArraysGet_d( eldga, g_a, lo, hi, tmpa, &dims[1] ); #else NGA_Get(g_a, lo, hi, tmpa, &dims[1]); #endif #if defined(USE_ELEMENTAL) ElGlobalArraysInquire_d( eldga, g_a, &ndim, dims ); #else NGA_Inquire(g_a, &type, &ndim, dims); #endif lo[0] = 0; lo[1] = 0; hi[0] = dims[0]-1; hi[1] = dims[1]-1; #if defined(USE_ELEMENTAL) ElGlobalArraysGet_d( eldga, g_b, lo, hi, tmpb, &dims[1] ); #else NGA_Get(g_b, lo, hi, tmpb, &dims[1]); #endif /* compute dgemm sequentially */ #if defined(USE_ELEMENTAL) cblas_dgemm ( CblasRowMajor, ( xt1 == 'n'? CblasNoTrans: CblasTrans ), ( xt2 == 'n'? CblasNoTrans: CblasTrans ), num_m /* M */, num_n /* N */, num_k /* K */, alpha, tmpa, num_m, /* lda */ tmpb, num_k, /* ldb */ beta, tmpc, num_m /* ldc */); #else xb_dgemm(&xt1, &xt2, &num_m, &num_n, &num_k, &alpha, tmpa, &num_m, tmpb, &num_k, &beta, tmpc, &num_m); #endif /* after computing c locally, verify it with the values in g_c */ #if defined(USE_ELEMENTAL) ElGlobalArraysInquire_d( eldga, g_a, &ndim, dims ); #else NGA_Inquire(g_a, &type, &ndim, dims); #endif lo[0] = 0; lo[1] = 0; hi[0] = dims[0]-1; hi[1] = dims[1]-1; #if defined(USE_ELEMENTAL) ElGlobalArraysGet_d( eldga, g_c, lo, hi, tmpa, &dims[1] ); #else NGA_Get(g_c, lo, hi, tmpa, &dims[1]); #endif for (i=0; i<num_n; i++) { for (j=0; j<num_m; j++) { abs_value = fabs(tmpc[j+i*num_m]-tmpa[j+i*num_m]); if(abs_value > 1.0 || abs_value < -1.0) { printf("Values are = %f %f\n", tmpc[j+i*num_m], tmpa[j+i*num_m]); printf("Values are = %f %f\n", fabs(tmpc[j+i*num_m]-tmpa[j*i*num_m]), abs_value); fflush(stdout); GA_Error("verify ga_dgemm failed", 1); } } } } /** * called by process '0' (or your master process ) */ void load_ga(int handle, double *f, int dim1, int dim2) { int lo[2], hi[2]; if (dim1 < 0 || dim2 < 0) { return; } lo[0] = 0; lo[1] = 0; hi[0] = dim1-1; hi[1] = dim2-1; #if defined(USE_ELEMENTAL) ElGlobalArraysPut_d( eldga, handle, lo, hi, f, &dim1 ); #else NGA_Put(handle, lo, hi, f, &dim1); #endif } /* c c----------------------------------------------------------------------- c must be called by all processors, if you need to fillup the c entire array c subroutine load_ga_from_square(handle,num,f,ndim) implicit none integer handle, memhandle integer num,ndim real*8 f(ndim,ndim) integer ilo, ihi, jlo, jhi, nx, ny, ibuff integer ga_nodeid, i1, i2, i, j, ix, jx #include "mafdecls.fh" call ga_distribution(handle, ga_nodeid(), ilo, ihi, jlo, jhi) if(ihi.le.0)return if(jhi.le.0)return c nx = ihi - ilo + 1 c ny = jhi - jlo + 1 do i = ilo,ihi,ndim do j = jlo,jhi,ndim call ga_put(handle,i,min(ihi,i+ndim),j,min(jhi,j+ndim), & f,ndim) enddo enddo return end */ /* c c----------------------------------------------------------------------- c must be called by all processors, if you need to fillup the c entire array c subroutine load_ga_from_triangle(handle,f,ndim) implicit none integer handle, memhandle real*8 f(*) integer ndim integer ilo, ihi, jlo, jhi, nx, ny, ibuff integer ga_nodeid, i1, i2, i, j, ix, jx #include "mafdecls.fh" call ga_distribution(handle, ga_nodeid(), ilo, ihi, jlo, jhi) if(ihi.le.0)return if(jhi.le.0)return nx = ihi - ilo + 1 ny = jhi - jlo + 1 if (.not.ma_alloc_get(MT_DBL,nx*ny,'flap',memhandle,ibuff)) then call ga_error('failed: allocate triangle',100) endif do i = 1,nx do j = 1,ny ix = i + ilo - 1 jx = j + jlo - 1 i1 = min(ix,jx) i2 = max(ix,jx) dbl_mb(ibuff + nx*(j-1) + (i-1) ) = f(i2*(i2-1)/2 + i1) enddo enddo call ga_put(handle,ilo,ihi,jlo,jhi, & dbl_mb(ibuff),nx) if (.not.ma_free_heap(memhandle)) then call ga_error('failed: free triangle',100) endif return end */
{ "alphanum_fraction": 0.5318487098, "avg_line_length": 26.0977859779, "ext": "c", "hexsha": "43eb24569f5d5667f978d22e6a680b8efc173be5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "614f02509690449b553451e36bc78e7e132ea517", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sg0/Elemental", "max_forks_repo_path": "tests/core/GlobalArrays/C/testmatmultc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "614f02509690449b553451e36bc78e7e132ea517", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sg0/Elemental", "max_issues_repo_path": "tests/core/GlobalArrays/C/testmatmultc.c", "max_line_length": 87, "max_stars_count": 1, "max_stars_repo_head_hexsha": "614f02509690449b553451e36bc78e7e132ea517", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sg0/Elemental", "max_stars_repo_path": "tests/core/GlobalArrays/C/testmatmultc.c", "max_stars_repo_stars_event_max_datetime": "2015-12-08T22:54:37.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-08T22:54:37.000Z", "num_tokens": 4537, "size": 14145 }
/** * * @file example_dpotrf.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @brief Example of Cholesky factorization * * @version 2.6.0 * @author Bilel Hadri * @date 2010-11-15 * @generated d Tue Jan 7 11:45:20 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <time.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_dmain.h" static int check_factorization(int, int, double*, double*, int, int*); int testing_dgetrf(int argc, char **argv) { int M = 1000; int N = 500; int LDA = 1000; int info_factorization; double *A1 = (double *)malloc(LDA*N*sizeof(double)); double *A2 = (double *)malloc(LDA*N*sizeof(double)); /* Check if unable to allocate memory */ if ((!A1)||(!A2)){ printf("Out of Memory \n "); return 0; } /* Initialize A1 and A2 */ LAPACKE_dlarnv(3,ISEED, LDA*N, A1); int i; for(i = 0; i < N*LDA; ++i){ A2[i] = A1[i]; } /* Plasma routines */ int *IPIV = calloc(LDA, sizeof(int)); PLASMA_dgetrf(M, N, A2, LDA, IPIV); /* Check the factorization */ info_factorization = check_factorization( M, N, A1, A2, LDA, IPIV); if ( info_factorization != 0 ) printf("-- Error in DGETRF example ! \n"); else printf("-- Run of DGETRF example successful ! \n"); free(A1); free(A2); return 0; } static int check_factorization(int M, int N, double *A1, double *A2, int LDA, int *IPIV) { double Anorm, Rnorm; double Anorm1, Rnorm1; double alpha; int info_factorization; int i,j; double eps; eps = LAPACKE_dlamch_work('e'); // double *Residual = (double *)malloc(M*N*sizeof(double)); // double *L1 = (double *)malloc(M*N*sizeof(double)); // double *L2 = (double *)malloc(M*N*sizeof(double)); double *work = (double *)malloc(N*sizeof(double)); int *ipiv0 = calloc(LDA, sizeof(int)); int dff = 0; LAPACKE_dgetrf(LAPACK_COL_MAJOR, M, N, A1, M, ipiv0); for(j=0; j<N; j++) dff += IPIV[j] - ipiv0[j]; printf("dff: %d\n", dff); Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, A1, M, work); Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, A2, LDA, work); Rnorm1 = PLASMA_dlange(PlasmaInfNorm, M, N, A1, LDA); Anorm1 = PLASMA_dlange(PlasmaInfNorm, M, N, A2, LDA); printf("|Rnorm-Rnorm1|: %e, |Anorm-Anorm1|: %e\n", fabs(Rnorm-Rnorm1), fabs(Anorm-Anorm1)); printf("============\n"); printf("Checking the LU Factorization \n"); printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",fabs(Rnorm-Anorm)/(Anorm)); if ( isnan(fabs(Rnorm-Anorm)/(Anorm)) || (fabs(Rnorm-Anorm)/(Anorm) > 10.0) ){ printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else{ printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } // free(Residual); free(L1); free(L2); free(work); return info_factorization; }
{ "alphanum_fraction": 0.6120906801, "avg_line_length": 26.6890756303, "ext": "c", "hexsha": "f774bc16b235b413ad386abbbe9c969e5576df17", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_dgetrf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_dgetrf.c", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_dgetrf.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1034, "size": 3176 }
#pragma once #include <gsl/gsl_fit.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_movstat.h> #include <gsl/gsl_vector.h> #include <cstdlib> #include "DataFrame.h" #include "Ops.h" namespace adsl { // Evaluate the result of a fit at a given point based on the DataFrame description // double <- DataFrame /* auto evalFit = [](double t) { auto retFunc = [t](DataFrame& df) { if (df.getDesc() == "gsl_fit_linear") { double m = df + select({ "slope" }) + getFirst + single(); double b = df + select({ "intercept" }) + getFirst + single(); return (m * t) + b; } else { return (double)NAN; } }; return retFunc; }; */ // Perform a linear fit using gsl_fit_linear // df must have only 2 columns // DataFrame <- DataFrame auto fitLinear = [](DataFrame& df) { if (df.getCols() == 2) { if (df.getData()[0].type != DBL || df.getData()[1].type != DBL) { std::cout << "[fitLinear] <<ERROR>> At least one of the columns is not of type DBL " << std::endl; exit(1); DataFrame empty_df; return empty_df; } // Setup DataFrame ret; auto xData = df.getData()[0].toVec_dbl(); auto yData = df.getData()[1].toVec_dbl(); size_t length = xData.size(); double* x; double* y; x = (double*)malloc(length * sizeof(double)); y = (double*)malloc(length * sizeof(double)); std::copy(xData.begin(), xData.end(), x); std::copy(yData.begin(), yData.end(), y); // Fitting & r-squared double c0, c1, cov00, cov01, cov11, sumsq; gsl_fit_linear(x, 1, y, 1, length, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); vd tmpSlope = {c1}; DataList slope(&tmpSlope, DataType::DBL, "slope"); vd tmpIntercept = {c0}; DataList intercept(&tmpIntercept, DataType::DBL, "intercept"); vd tmpRsqrd = { gsl_stats_correlation(x, 1, y, 1, length) }; DataList rsqrd(&tmpRsqrd, DataType::DBL, "r-squared"); // Clean up free(x); free(y); // Return ret.addCol(slope); ret.addCol(intercept); ret.addCol(rsqrd); ret.setDesc("gsl_fit_linear"); return ret; } else { std::cout << "[fitLinear] <<ERROR>> DataFrame doesn't have two columns; has " << df.getCols() << std::endl; exit(1); DataFrame empty_df; return empty_df; } }; // TODO: add more fit types // Calculate the moving average of a DataList // DataList <- DataList <- double /* auto SMA = [](double period) { auto retFunc = [period](DataList& dl) { DataFrame ret; double* input; double* output; // TODO }; return retFunc; }; */ }
{ "alphanum_fraction": 0.6141390205, "avg_line_length": 25.5757575758, "ext": "h", "hexsha": "dc869e308039c4a19f10d5ceed6a10b1097eb558", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f1c92598a49dfa03fa7938abbdc990c5f7877579", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ianfr/adsl-cpp", "max_forks_repo_path": "Includes/GSL.h", "max_issues_count": 13, "max_issues_repo_head_hexsha": "f1c92598a49dfa03fa7938abbdc990c5f7877579", "max_issues_repo_issues_event_max_datetime": "2021-12-31T20:11:22.000Z", "max_issues_repo_issues_event_min_datetime": "2021-08-20T20:18:58.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "ianfr/adsl-cpp", "max_issues_repo_path": "Includes/GSL.h", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "f1c92598a49dfa03fa7938abbdc990c5f7877579", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ianfr/adsl-cpp", "max_stars_repo_path": "Includes/GSL.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 806, "size": 2532 }
/** * @file bblas_ztesting.c * * @brief BBLAS testing for double _Complex routines. * * BBLAS is a software package provided by Univ. of Manchester, * Univ. of Tennessee. * * @version 1.0.0 * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-02-20 * */ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Code generation * @precisions normal z -> c d s **/ #endif #include "bblas_common.h" #if defined(BBLAS_WITH_MKL) #include <mkl_lapacke.h> #else #include <lapacke.h> #endif #include <cblas.h> #define COMPLEX /** * Initialize test parameters to their default values. **/ void bblas_zinit_config (bblas_ztest_t *test) { test->gen_uplo =1; test->gen_transA =1; test->gen_transB =1; test->gen_trans =1; test->gen_side =1; test->gen_diag =1; test->minM = 0; test->minN = 0; test->minK = 0; test->maxM = 0; test->maxN = 0; test->maxK = 0; test->minbatch_count = 1; test->maxbatch_count = 1; test->batch_opts = 0; test->routine = 1; test->nb_test = 1; test->set_error = 0; test->global_error = 0; test->faulty_iter = 0; test->mkl_sequential = 0; test->new_accuracy = 1; } /** * Set the values of all the BBLAS parameters inside the test structure. **/ void bblas_zsettest(bblas_ztest_t *test) { enum BBLAS_ROUTINE routine = test->routine; /* * Set the value of batch count */ bblas_zset_batch_count(test); /* * Allocate memory and set values for uplo */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)|| (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { bblas_zsetuplo(test); } /* * Allocate memory and set values for transA */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { bblas_zsettransA(test); } /* * Allocate memory and set values for transB */ if (routine == BBLAS_GEMM) { bblas_zsettransB(test); } /* * Allocate memory and set values for trans */ if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { bblas_zsettrans(test); } /* * Allocate memory and set values for side */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { bblas_zsetside(test); } /* * Allocate memory and set values for diag */ if ((routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { bblas_zsetdiag(test); } /* * Allocate memory and set values for M */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { bblas_zsetM(test); } /* * Allocate memory and set values for N, all routines */ bblas_zsetN(test); /* * Allocate memory and set values for K */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K)) { bblas_zsetK(test); } /* * Allocate memory and set values for lda, all routines */ bblas_zsetlda(test); /* * Allocate memory and set values for ldb, all routines */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { bblas_zsetldb(test); } /* * Allocate memory and set values for ldc, all routines */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { bblas_zsetldc(test); } /* * Allocate memory and set values for alpha, all routines */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)|| (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { bblas_zsetalpha(test); } /* * Allocate memory and set values for alpha */ if (routine == BBLAS_HERK) { bblas_zsetalpha_herk(test); } /* * Allocate memory and set values for beta */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_SYR2K)) { bblas_zsetbeta(test); } /* * Allocate memory and set values for beta_herk */ if ((routine == BBLAS_HERK) || (routine == BBLAS_HER2K)) { bblas_zsetbeta_herk(test); } /* * Allocate memory and set values for arrayA */ bblas_zsetarrayA(test); /* * Allocate memory and set values for arrayB */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { bblas_zsetarrayB(test); } /* * Allocate memory and set values for arrayC */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { bblas_zsetarrayC(test); } /* Memory allocation for result and error variables */ bblas_zmalloc_result_error(test); } /** * Allocate memory and set the values of uplo **/ void bblas_zsetuplo(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "uplo"; int random_number; /*Initialize random number generation */ srand ( time(NULL) ) ; /*Memory allocation */ test->uplo = (enum BBLAS_UPLO*) malloc(nb_data*sizeof(enum BBLAS_UPLO)); /*Malloc checking */ bblas_malloc_check(test->uplo, ptr_name); /*set UPLO values */ switch (test->gen_uplo) { case UPLO_LOWER: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { test->uplo[batch_iter] = BblasLower; } break; case UPLO_UPPER: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { test->uplo[batch_iter] = BblasUpper; } break; default: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { /*Generate a random number */ random_number = rand() % 100; if (random_number < 50 ) { test->uplo[batch_iter] = BblasLower; }else { test->uplo[batch_iter] = BblasUpper; } break; } } } /** * Allocate memory and set the values of transA **/ void bblas_zsettransA(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "transA"; int random_number; /*Initialize random number generation */ srand ( time(NULL) ) ; /*Memory allocation */ test->transA = (enum BBLAS_TRANS*) malloc(nb_data*sizeof(enum BBLAS_TRANS)); /*Malloc checking */ bblas_malloc_check(test->transA, ptr_name); /*set transA */ switch (test->gen_transA) { case NO_TRANS: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->transA[batch_iter] = BblasNoTrans; } break; case TRANS: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->transA[batch_iter] = BblasTrans; } break; case CONJ: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->transA[batch_iter] = BblasConjTrans; } break; default: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { /*Generate a random number */ random_number = rand() % 100; if (random_number < 50) { test->transA[batch_iter] = BblasNoTrans; }else if (random_number < 80) { test->transA[batch_iter] = BblasTrans; }else { test->transA[batch_iter] = BblasConjTrans; } } break; } } /** * Allocate memory and set the values of transB **/ void bblas_zsettransB(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "transB"; int random_number; /*Initialize random number generation */ srand ( time(NULL) ) ; /*Memory allocation for transB */ test->transB = (enum BBLAS_TRANS*) malloc(nb_data*sizeof(enum BBLAS_TRANS)); /*checking memory allocation */ bblas_malloc_check(test->transB, ptr_name); /*set transB */ switch (test->gen_transB) { case NO_TRANS: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->transB[batch_iter] = BblasNoTrans; } break; case TRANS: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->transB[batch_iter] = BblasTrans; } break; case CONJ: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->transB[batch_iter] = BblasConjTrans; } break; default: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { /*Generate a random number */ random_number = rand() % 100; if (random_number < 50) { test->transB[batch_iter] = BblasNoTrans; }else if (random_number < 80) { test->transB[batch_iter] = BblasTrans; }else { test->transB[batch_iter] = BblasConjTrans; } } break; } } /** * Allocate memory and set the values of trans **/ void bblas_zsettrans(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "trans"; int random_number; /*Initialize random number generation */ srand ( time(NULL) ) ; /*Memory allocation for trans */ test->trans = (enum BBLAS_TRANS*) malloc(nb_data*sizeof(enum BBLAS_TRANS)); /*checking memory allocation */ bblas_malloc_check(test->trans, ptr_name); /*Set the values of trans */ switch (test->gen_trans) { case NO_TRANS: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->trans[batch_iter] = BblasNoTrans; } break; case TRANS: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->trans[batch_iter] = BblasTrans; } break; case CONJ: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->trans[batch_iter] = BblasConjTrans; } break; default: for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { /*Generate a random number */ random_number = rand() % 100; if (random_number < 50) { test->trans[batch_iter] = BblasNoTrans; }else if (random_number < 80) { test->trans[batch_iter] = BblasTrans; }else { test->trans[batch_iter] = BblasConjTrans; } } break; } } /** * Allocate memory and set the values of side **/ void bblas_zsetside(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "side"; int random_number; /*Initialize random number generation */ srand ( time(NULL) ) ; /*Memory allocation for side */ test->side = (enum BBLAS_SIDE*) malloc(nb_data*sizeof(enum BBLAS_SIDE)); /*checking memory allocation */ bblas_malloc_check(test->side, ptr_name); /*Set the values of side */ switch (test->gen_side) { case SIDE_LEFT: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { test->side[batch_iter] = BblasLeft; } break; case SIDE_RIGHT: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { test->side[batch_iter] = BblasRight; } break; default: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { /*Generate a random number */ random_number = rand() % 100; if (random_number < 50 ) { test->side[batch_iter] = BblasLeft; }else { test->side[batch_iter] = BblasRight; } break; } } } /** * Allocate memory and set the values of diag **/ void bblas_zsetdiag(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "diag"; int random_number; /*Initialize random number generation */ srand ( time(NULL) ) ; /*Memory allocation for diag */ test->diag = (enum BBLAS_DIAG*) malloc(nb_data*sizeof(enum BBLAS_DIAG)); /*checking memory allocation */ bblas_malloc_check(test->diag, ptr_name); /*Set the values of diag */ switch (test->gen_diag) { case DIAG_NO_U: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { test->diag[batch_iter] = BblasNonUnit; } break; case DIAG_U: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { test->diag[batch_iter] = BblasUnit; } break; default: for( batch_iter =0; batch_iter < nb_data; batch_iter++) { /*Generate a random number */ random_number = rand() % 100; if (random_number < 50 ) { test->diag[batch_iter] = BblasNonUnit; }else { test->diag[batch_iter] = BblasUnit; } break; } } } /** * Allocate memory and set the values of M **/ void bblas_zsetM(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "M"; /*Memory allocation for M */ test->M = (int*) malloc(nb_data*sizeof(int)); /*checking memory allocation */ bblas_malloc_check(test->M, ptr_name); /*Set the values of M */ for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->M[batch_iter] = irandRange(test->minM, test->maxM); } } /** * Allocate memory and set the values of N **/ void bblas_zsetN(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "N"; /*Memory allocation for N */ test->N = (int*) malloc(nb_data*sizeof(int)); /*checking memory allocation */ bblas_malloc_check(test->N, ptr_name); /*Set the values of N */ for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->N[batch_iter] = irandRange(test->minN, test->maxN); } } /** * Allocate memory and set the values of K **/ void bblas_zsetK(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "K"; /*Memory allocation for K */ test->K = (int*) malloc(nb_data*sizeof(int)); /*checking memory allocation */ bblas_malloc_check(test->K, ptr_name); /*Set the values of K */ for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->K[batch_iter] = irandRange(test->minK, test->maxK); } } /** * Allocate memory and set the values of lda **/ void bblas_zsetlda(bblas_ztest_t *test) { int batch_iter; int nb_data = bblas_znbdata(test); int routine = test->routine; char ptr_name[NAME_LENGTH] = "lda"; /*Memory allocation for lda */ test->lda = (int*) malloc(nb_data*sizeof(int)); /*checking memory allocation */ bblas_malloc_check(test->lda, ptr_name); /*LDA for GEMM */ if (routine == BBLAS_GEMM) { for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { if (test->transA[batch_iter] == BblasNoTrans) { test->lda[batch_iter] = test->M[batch_iter]; }else { test->lda[batch_iter] =test->K[batch_iter] ; } } } /*LDA for SYMM, HEMM, TRMM AND TRSM */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { if (test->side[batch_iter] == BblasLeft) { test->lda[batch_iter] = test->M[batch_iter]; }else { test->lda[batch_iter] =test->N[batch_iter] ; } } } /*LDA for SYRK, HERK, SYR2K, HER2K */ if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { if (test->trans[batch_iter] == BblasNoTrans) { test->lda[batch_iter] = test->N[batch_iter]; }else { test->lda[batch_iter] =test->K[batch_iter] ; } } } } /** * Allocate memory and set the values of ldb **/ void bblas_zsetldb(bblas_ztest_t *test) { int batch_iter; int routine = test->routine; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "ldb"; /*Memory allocation for ldb */ test->ldb = (int*) malloc(nb_data*sizeof(int)); /*checking memory allocation */ bblas_malloc_check(test->ldb, ptr_name); /*LDB for GEMM */ if ((routine == BBLAS_GEMM) ) { for( batch_iter =0; batch_iter < nb_data; batch_iter++) { if (test->transB[batch_iter] == BblasNoTrans) { test->ldb[batch_iter] = test->K[batch_iter]; }else { test->ldb[batch_iter] =test->N[batch_iter] ; } } } /*LDB SYMM, HEMM, TRMM AND TRSM */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { for( batch_iter =0; batch_iter < nb_data; batch_iter++) { test->ldb[batch_iter] = test->M[batch_iter]; } } /*LDB for SYR2K, HER2K */ if ((routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { for( batch_iter =0; batch_iter < nb_data; batch_iter++) { if (test->trans[batch_iter] == BblasNoTrans) { test->ldb[batch_iter] = test->N[batch_iter]; }else { test->ldb[batch_iter] =test->K[batch_iter] ; } } } } /** * Allocate memory and set the values of ldc **/ void bblas_zsetldc(bblas_ztest_t *test) { int batch_iter; int routine = test->routine; int nb_data = bblas_znbdata(test); char ptr_name[NAME_LENGTH] = "ldc"; /*Memory allocation for ldc */ test->ldc = (int*) malloc(nb_data*sizeof(int)); /*checking memory allocation */ bblas_malloc_check(test->ldc, ptr_name); /*LDC for GEMM */ if (routine == BBLAS_GEMM) { for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->ldc[batch_iter] = test->M[batch_iter]; } } /*LDC for SYMM, HEMM */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM)) { for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->ldc[batch_iter] = test->M[batch_iter]; } } /*LDC for SYRK, HERK, SYR2K, HER2K */ if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { for( batch_iter =0; batch_iter < nb_data ; batch_iter++) { test->ldc[batch_iter] = test->N[batch_iter]; } } } /** * Allocate memory and set the values of alpha **/ void bblas_zsetalpha(bblas_ztest_t *test) { int batch_iter; int batch_count = test->batch_count; char ptr_name[NAME_LENGTH] = "alpha"; /*Memory allocation for alpha */ test->alpha = (BBLAS_Complex64_t*) malloc(batch_count*sizeof(BBLAS_Complex64_t)); /*checking memory allocation */ bblas_malloc_check(test->alpha, ptr_name); /* Set value of alpha */ for( batch_iter =0; batch_iter < batch_count; batch_iter++) { test->alpha[batch_iter] = ((BBLAS_Complex64_t)rand()/(BBLAS_Complex64_t)RAND_MAX); } } /** * Allocate memory and set the values of alpha specifically for herk. **/ void bblas_zsetalpha_herk(bblas_ztest_t *test) { int batch_iter; int batch_count = test->batch_count; char ptr_name[NAME_LENGTH] = "alpha_herk"; /*Memory allocation for alpha_herk */ test->alpha_herk = (double*) malloc(batch_count*sizeof(double)); /*checking memory allocation */ bblas_malloc_check(test->alpha_herk, ptr_name); /* Set value of alpha_herk */ for( batch_iter =0; batch_iter < batch_count; batch_iter++) { test->alpha_herk[batch_iter] = ((double)rand()/(double)RAND_MAX); } } /** * Allocate memory and set the values of beta. **/ void bblas_zsetbeta(bblas_ztest_t *test) { int batch_iter; int batch_count = test->batch_count; char ptr_name[NAME_LENGTH] = "beta"; /*Memory allocation for beta */ test->beta = (BBLAS_Complex64_t*) malloc(batch_count*sizeof(BBLAS_Complex64_t)); /*checking memory allocation */ bblas_malloc_check(test->beta, ptr_name); /* Set value of beta */ for( batch_iter =0; batch_iter < batch_count; batch_iter++) { test->beta[batch_iter] = ((BBLAS_Complex64_t)rand()/(BBLAS_Complex64_t)RAND_MAX); } } /** * Allocate memory and set the values of beta specifically for herk. **/ void bblas_zsetbeta_herk(bblas_ztest_t *test) { int batch_iter; int batch_count = test->batch_count; char ptr_name[NAME_LENGTH] = "beta_herk"; /*Memory allocation for beta_herk */ test->beta_herk = (double*) malloc(batch_count*sizeof(double)); /*checking memory allocation */ bblas_malloc_check(test->beta_herk, ptr_name); /* Set value of beta_herk */ for( batch_iter =0; batch_iter < batch_count; batch_iter++) { test->beta_herk[batch_iter] = ((double)rand()/(double)RAND_MAX); } } /** * Allocate memory and set the values of arrayA. **/ void bblas_zsetarrayA(bblas_ztest_t *test) { int batch_iter, nb_row, nb_col; int first_index = 0; int routine = test->routine; int batch_count = test->batch_count; char ptr_name[NAME_LENGTH] = "arrayA"; int IONE = 1; int ISEED[4] ={0,0,0,1}; /*Memory allocation for **arrayA */ test->arrayA = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*)); bblas_malloc_check(test->arrayA, ptr_name); if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count; batch_iter++) { nb_row = test->lda[batch_iter]; /* nb_col for GEMM */ if (routine == BBLAS_GEMM) { if (test->transA[batch_iter] == BblasNoTrans) { nb_col =test->K[batch_iter]; }else { nb_col =test->M[batch_iter]; } } /* nb_col SYMM, HEMM, TRMM AND TRSM */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { if(test->side[batch_iter] == BblasLeft ) { nb_col = test->M[batch_iter]; }else { nb_col = test->N[batch_iter]; } } /* nb_col for SYRK, HERK, SYR2K, HER2K */ if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { if (test->trans[batch_iter] == BblasNoTrans) { nb_col = test->K[batch_iter]; }else { nb_col = test->N[batch_iter]; } } /*Matrix filling */ test->arrayA[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t )); bblas_malloc_check(test->arrayA[batch_iter], ptr_name); #if defined(BBLAS_WITH_MKL) LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayA[batch_iter]); #else LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayA[batch_iter]); #endif if( (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { for(int i=0; i<max(nb_row,nb_col); i++) { test->arrayA[batch_iter][nb_col*i+i] = test->arrayA[batch_iter][nb_col*i+i] + 1.0; } } if(routine == BBLAS_HEMM ) { for(int i=0; i< nb_row; i++) { test->arrayA[batch_iter][nb_col*i+i] = creal(test->arrayA[batch_iter][nb_col*i+i]); } } } }else if( test->batch_opts == BBLAS_FIXED ) { nb_row = test->lda[first_index]; /* nb_col for GEMM */ if (routine == BBLAS_GEMM) { if (test->transA[first_index] == BblasNoTrans) { nb_col =test->K[first_index]; }else { nb_col =test->M[first_index]; } } /* nb_col SYMM, HEMM, TRMM AND TRSM */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { if(test->side[first_index] == BblasLeft ) { nb_col = test->M[first_index]; }else { nb_col = test->N[first_index]; } } /* nb_col for SYRK, HERK, SYR2K, HER2K */ if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { if (test->trans[first_index] == BblasNoTrans) { nb_col = test->K[first_index]; }else { nb_col = test->N[first_index]; } } /*Matrix filling */ for( batch_iter =0; batch_iter < batch_count; batch_iter++) { test->arrayA[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t )); bblas_malloc_check(test->arrayA[batch_iter], ptr_name); #if defined(BBLAS_WITH_MKL) LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayA[batch_iter]); #else LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayA[batch_iter]); #endif if( (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { for(int i=0; i<max(nb_row,nb_col); i++) { test->arrayA[batch_iter][nb_col*i+i] = test->arrayA[batch_iter][nb_col*i+i] + 1.0; } } if(routine == BBLAS_HEMM ) { for(int i=0; i<max(nb_row,nb_col); i++) { test->arrayA[batch_iter][nb_col*i+i] = creal(test->arrayA[batch_iter][nb_col*i+i]); } } } }else { bblas_error("bblas_ztesting.c", "wrong batch_opts value"); } } /** * Allocate memory and set the values of arrayB. **/ void bblas_zsetarrayB(bblas_ztest_t *test) { int batch_iter, nb_row, nb_col; int first_index = 0; int routine = test->routine; int batch_count = test->batch_count; char ptr_name[NAME_LENGTH] = "arrayB"; int max_work_size = max(test->maxK, max(test->maxM, test->maxN)); int IONE = 1; int ISEED[4] ={0,0,0,1}; /*Memory allocation for arrayB */ test->arrayB = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*)); bblas_malloc_check(test->arrayB, ptr_name); test->Binitnorm = (double *)malloc(batch_count*sizeof(double)); bblas_malloc_check(test->Binitnorm, "Binitnorm"); double *work = (double *)malloc(max_work_size*sizeof(double)); bblas_malloc_check(work, "work"); if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { nb_row =test->ldb[batch_iter]; /* nb_col for GEMM */ if (routine == BBLAS_GEMM) { if (test->transB[batch_iter] == BblasNoTrans) { nb_col = test->N[batch_iter]; }else { nb_col = test->K[batch_iter]; } } /* nb_col for SYMM, HEMM, TRMM AND TRSM */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { nb_col =test->N[batch_iter]; } /* nb_col for SYR2K, HER2K */ if ((routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { if (test->trans[batch_iter] == BblasNoTrans) { nb_col = test->K[batch_iter]; }else { nb_col = test->N[batch_iter]; } } test->arrayB[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t )); bblas_malloc_check(test->arrayB[batch_iter], ptr_name); #if defined(BBLAS_WITH_MKL) LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayB[batch_iter]); #else LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayB[batch_iter]); #endif /*Compute the infinity norm of B */ if( (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { #if defined(BBLAS_WITH_MKL) test->Binitnorm[batch_iter] = (BBLAS_Complex64_t) LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', nb_row, nb_col, (MKL_Complex16*) test->arrayB[batch_iter], test->ldb[batch_iter], work); #else test->Binitnorm[batch_iter] = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', nb_row, nb_col, test->arrayB[batch_iter], test->ldb[batch_iter], work); #endif } } }else if( test->batch_opts == BBLAS_FIXED ) { nb_row =test->ldb[first_index]; /* nb_col for GEMM */ if (routine == BBLAS_GEMM) { if (test->transB[first_index] == BblasNoTrans) { nb_col = test->N[first_index]; }else { nb_col = test->K[first_index]; } } /* nb_col for SYMM, HEMM, TRMM AND TRSM */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { nb_col =test->N[first_index]; } /* nb_col for SYR2K, HER2K */ if ((routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { if (test->trans[first_index] == BblasNoTrans) { nb_col = test->K[first_index]; }else { nb_col = test->N[first_index]; } } /*Matrix filling */ for( batch_iter =0; batch_iter < batch_count; batch_iter++) { test->arrayB[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t )); #if defined(BBLAS_WITH_MKL) LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayB[batch_iter]); #else LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayB[batch_iter]); #endif /*Compute the infinity norm of B */ if( (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { #if defined(BBLAS_WITH_MKL) test->Binitnorm[batch_iter] = (BBLAS_Complex64_t) LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', nb_row, nb_col, (MKL_Complex16*) test->arrayB[batch_iter], test->ldb[first_index], work); #else test->Binitnorm[batch_iter] = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', nb_row, nb_col, test->arrayB[batch_iter], test->ldb[first_index], work); #endif } } }else { bblas_error("bblas_ztesting.c", "wrong batch_opts value"); } /*Free work */ free(work); } /** * Allocate memory and set the values of arrayC. **/ void bblas_zsetarrayC(bblas_ztest_t *test) { int batch_iter, nb_row, nb_col; int first_index = 0; int batch_count = test->batch_count; int max_work_size = max(test->maxK, max(test->maxM, test->maxN)); char ptr_name[NAME_LENGTH] = "arrayC"; int IONE = 1; int ISEED[4] ={0,0,0,1}; test->arrayC = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*)); bblas_malloc_check(test->arrayC, ptr_name); test->Cinitnorm = (double *)malloc(batch_count*sizeof(double)); bblas_malloc_check(test->Cinitnorm, "Cinitnorm"); double *work = (double *)malloc(max_work_size*sizeof(double)); bblas_malloc_check(work, "work"); if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { nb_row =test->ldc[batch_iter]; nb_col =test->N[batch_iter]; test->arrayC[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t )); bblas_malloc_check(test->arrayC[batch_iter], ptr_name); #if defined(BBLAS_WITH_MKL) LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayC[batch_iter]); #else LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayC[batch_iter]); #endif if( (test->routine == BBLAS_HERK) || (test->routine == BBLAS_HER2K)) { for(int i=0; i<max(nb_row,nb_col); i++) { test->arrayC[batch_iter][nb_col*i+i] = creal(test->arrayC[batch_iter][nb_col*i+i]); } } /*Compuptation of the norm of C */ #if defined(BBLAS_WITH_MKL) test->Cinitnorm[batch_iter] = (BBLAS_Complex64_t) LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', nb_row, nb_col, (MKL_Complex16*) test->arrayC[batch_iter], test->ldc[batch_iter], work); #else test->Cinitnorm[batch_iter] = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', nb_row, nb_col, test->arrayC[batch_iter], test->ldc[batch_iter], work); #endif } }else if( test->batch_opts == BBLAS_FIXED ) { nb_row =test->ldc[first_index]; nb_col =test->N[first_index]; for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { test->arrayC[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t )); bblas_malloc_check(test->arrayC[batch_iter], ptr_name); #if defined(BBLAS_WITH_MKL) LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayC[batch_iter]); #else LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayC[batch_iter]); #endif if( (test->routine == BBLAS_HERK) || (test->routine == BBLAS_HER2K)) { for(int i=0; i<max(nb_row,nb_col); i++) { test->arrayC[batch_iter][nb_col*i+i] = creal(test->arrayC[batch_iter][nb_col*i+i]); } } /*Compuptation of the norm of C */ #if defined(BBLAS_WITH_MKL) test->Cinitnorm[batch_iter] = (BBLAS_Complex64_t) LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', nb_row, nb_col, (MKL_Complex16*) test->arrayC[batch_iter], test->ldc[first_index], work); #else test->Cinitnorm[batch_iter] = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I',nb_row, nb_col, test->arrayC[batch_iter], test->ldc[first_index], work); #endif } } else { bblas_error("bblas_ztesting.c", "wrong batch_opts value"); } /*Free work */ free(work); } /** * Allocate memory for error checking. **/ void bblas_zmalloc_result_error(bblas_ztest_t *test) { int batch_count = test->batch_count; /*Memory for error computation */ switch(test->target) { case BBLAS_MKL: test->mkl_result = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*)); bblas_malloc_check(test->mkl_result, "mkl_result"); test->mkl_error = (double*) malloc(batch_count*sizeof(double)); bblas_malloc_check(test->mkl_error, "mkl_error"); break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_result = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*)); bblas_malloc_check(test->device_result, "device_result"); test->device_error = (double*) malloc(batch_count*sizeof(double)); bblas_malloc_check(test->device_error, "device_error"); break; case BBLAS_OTHER: test->other_result = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*)); bblas_malloc_check(test->other_result, "other_result"); test->other_error = (double*) malloc(batch_count*sizeof(double)); bblas_malloc_check(test->other_error, "other_error"); break; case BBLAS_CUMKL: test->mkl_result = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*)); bblas_malloc_check(test->mkl_result, "mkl_result"); test->device_result = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*)); bblas_malloc_check(test->device_result, "device_result"); test->mkl_error = (double*) malloc(batch_count*sizeof(double)); bblas_malloc_check(test->mkl_error, "mkl_error"); test->device_error = (double*) malloc(batch_count*sizeof(double)); bblas_malloc_check(test->device_error, "device_error"); break; default: printf("Memory alloation for error: Target no defined\n"); exit(EXIT_FAILURE); } /*Memory for info */ test->info = (int*) malloc(batch_count*sizeof(int)); } /** * Allocate memory and copy the initial arrayC values. * This is required to take norms after the computation is complete. **/ void bblas_zcopy_Cinit(bblas_ztest_t *test, BBLAS_Complex64_t **C_copy) { /*Local variables */ enum BBLAS_ROUTINE routine = test->routine; int batch_count = test->batch_count; int batch_iter, first_index = 0; int ldc, N; if (!((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))) { printf("BBLAS FATAL ERROR: bblas_ztesting.c():\n"); printf("\t bblas_zcopy_Cinit not defined for %s \n", bblas_getroutine(test->routine)); exit(EXIT_FAILURE); } if( test->batch_opts == BBLAS_VARIABLE ) // Varible size { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { ldc = test->ldc[batch_iter]; N = test->N[batch_iter]; C_copy[batch_iter] = (BBLAS_Complex64_t *) malloc(ldc*N* sizeof(BBLAS_Complex64_t )); /*Copy the matrix {C}_i */ cblas_zcopy (ldc*N, test->arrayC[batch_iter], 1, C_copy[batch_iter], 1); } }else if( test->batch_opts == BBLAS_FIXED ) //fixed size { ldc = test->ldc[first_index]; N = test->N[first_index]; for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { C_copy[batch_iter] = (BBLAS_Complex64_t *) malloc(ldc*N* sizeof(BBLAS_Complex64_t )); /*Copy the matrix {C}_i */ cblas_zcopy (ldc*N, test->arrayC[batch_iter], 1, C_copy[batch_iter], 1); } }else { bblas_error("bblas_ztesting.c", "wrong batch_opts value\n"); } } /** * Allocate memory and copy the initial arrayB values. * This is required to take norms after the computation is complete. **/ void bblas_zcopy_Binit(bblas_ztest_t *test, BBLAS_Complex64_t **B_copy) { /*Local variables */ enum BBLAS_ROUTINE routine = test->routine; int batch_count = test->batch_count; int batch_iter, first_index = 0; int ldb, N; if (!((routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))) { printf("BBLAS FATAL ERROR: bblas_ztesting.c():\n"); printf("\t bblas_zcopy_Binit not defined for %s \n", bblas_getroutine(test->routine)); exit(EXIT_FAILURE); } if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { ldb = test->ldb[batch_iter]; N = test->N[batch_iter]; B_copy[batch_iter] = (BBLAS_Complex64_t *) malloc(ldb*N* sizeof(BBLAS_Complex64_t )); /*Copy the matrix {B}_i */ cblas_zcopy (ldb*N, test->arrayB[batch_iter], 1, B_copy[batch_iter], 1); } }else if( test->batch_opts == BBLAS_FIXED ) //fixed size { ldb = test->ldb[first_index]; N = test->N[first_index]; for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { B_copy[batch_iter] = (BBLAS_Complex64_t *) malloc(ldb*N* sizeof(BBLAS_Complex64_t )); /*Copy the matrix {B}_i */ cblas_zcopy (ldb*N, test->arrayB[batch_iter], 1, B_copy[batch_iter], 1); } }else { bblas_error("bblas_ztesting.c", "wrong batch_opts value\n"); } } /** * Compute the relative error of each batch operation. **/ void bblas_zcheck_Cfinal(bblas_ztest_t *test, BBLAS_Complex64_t **C_final) { /*Local variables */ enum BBLAS_ROUTINE routine = test->routine; int batch_count = test->batch_count; int batch_iter, first_index = 0; int ldc, N; /* Error calculation variables */ double Cnorm, Error_norm; BBLAS_Complex64_t alpha =-1; /*Check if the call has been made by the correct routine */ if (!((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))) { printf("BBLAS FATAL ERROR: bblas_ztesting.c():\n"); printf("\t bblas_zcheck_Cfinal not defined for %s \n", bblas_getroutine(test->routine)); exit(EXIT_FAILURE); } /*Temporary buffer to save (test-arrayC -C_final) */ BBLAS_Complex64_t **C_diff; C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *)); /*Make a copy of test->arrayC in C_diff */ bblas_zcopy_Cinit(test, C_diff); /*Variable size */ if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { ldc = test->ldc[batch_iter]; N = test->N[batch_iter]; /*Computation of the Frobenus norm of {C}_batch_iter */ Cnorm = cblas_dznrm2(ldc*N, test->arrayC[batch_iter], 1); /*Compute the error */ cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the norm assoicated with the error */ Error_norm = cblas_dznrm2(ldc*N, C_diff[batch_iter], 1); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = Error_norm/Cnorm; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = Error_norm/Cnorm; break; case BBLAS_OTHER: test->other_error[batch_iter] = Error_norm/Cnorm; break; default: printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } }else if( test->batch_opts == BBLAS_FIXED ) //fixed size { ldc = test->ldc[first_index]; N = test->N[first_index]; for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { /*Computation of the Frobenus norm of {C}_batch_iter */ Cnorm = cblas_dznrm2(ldc*N, test->arrayC[batch_iter], 1); /*Compute the error */ cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the norm assoicated with the error */ Error_norm = cblas_dznrm2(ldc*N, C_diff[batch_iter], 1); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = Error_norm/Cnorm; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = Error_norm/Cnorm; break; case BBLAS_OTHER: test->other_error[batch_iter] = Error_norm/Cnorm; break; default: printf("In bblas_zcheck_Cfinal: Fixed, Target no defined\n"); exit(EXIT_FAILURE); } } }else { bblas_error("bblas_ztesting.c", "wrong batch_opts value"); } /*Free C_diff */ for(batch_iter=0; batch_iter < batch_count ; batch_iter++) { free(C_diff[batch_iter]); } free(C_diff); } /** * Compute the relative error of each batch operation. **/ void bblas_zcheck_Bfinal(bblas_ztest_t *test, BBLAS_Complex64_t **B_final) { /*Local variables */ enum BBLAS_ROUTINE routine = test->routine; int batch_count = test->batch_count; int batch_iter, first_index = 0; int ldb, N; /* Error calculation variables */ double Bnorm, Error_norm; BBLAS_Complex64_t alpha =-1; /*Check if the call has been made by the correct routine */ if (!((routine == BBLAS_TRSM) || (routine == BBLAS_TRMM))) { printf("BBLAS FATAL ERROR: bblas_ztesting.c():\n"); printf("\t bblas_zcheck_Bfinal not defined for %s \n", bblas_getroutine(test->routine)); exit(EXIT_FAILURE); } /*Temporary buffer to save (test-arrayB -B_final) */ BBLAS_Complex64_t **B_diff; B_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *)); /*Make a copy of test->arrayB in B_diff */ bblas_zcopy_Binit(test, B_diff); /*Variable size */ if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { ldb = test->ldb[batch_iter]; N = test->N[batch_iter]; /*Computation of the Frobenus norm of {B}_batch_iter */ Bnorm = cblas_dznrm2(ldb*N, test->arrayB[batch_iter], 1); /*Compute the error */ cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1); /*Compute the norm assoicated with the error */ Error_norm = cblas_dznrm2(ldb*N, B_diff[batch_iter], 1); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = Error_norm/Bnorm; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = Error_norm/(Bnorm); break; case BBLAS_OTHER: test->other_error[batch_iter] = Error_norm/(Bnorm); break; default: printf("In bblas_zcheck_Bfinal(): Target no defined\n"); exit(EXIT_FAILURE); } } }else if( test->batch_opts == BBLAS_FIXED ) { ldb = test->ldb[first_index]; N = test->N[first_index]; for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { /*Computation of the Frobenus norm of {B}_batch_iter */ Bnorm = cblas_dznrm2(ldb*N, test->arrayB[batch_iter], 1); /*Compute the error */ cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1); /*Compute the norm assoicated with the error */ Error_norm = cblas_dznrm2(ldb*N, B_diff[batch_iter], 1); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = Error_norm/(Bnorm); break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = Error_norm/(Bnorm); break; case BBLAS_OTHER: test->other_error[batch_iter] = Error_norm/(Bnorm); break; default: printf("In bblas_zcheck_Bfinal(): Target no defined\n"); exit(EXIT_FAILURE); } } }else { bblas_error("bblas_ztesting.c", "wrong batch_opts value"); } /*Free B_diff */ for(batch_iter=0; batch_iter < batch_count ; batch_iter++) { free(B_diff[batch_iter]); } free(B_diff); } /** * Free the memory associated with the test structure. **/ void bblas_zfreetest( bblas_ztest_t *test ) { enum BBLAS_ROUTINE routine = test->routine; /*Free uplo */ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)|| (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { free(test->uplo); } /*Free TRANSA */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { free( test->transA ); } /*Free TRANSB */ if (routine == BBLAS_GEMM) { free( test->transB ); } /*Free TRANS */ if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { free( test->trans ); } /*Free SIDE*/ if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { free( test->side ); } /*Free DIAG*/ if ((routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { free(test->diag); } /* Free M memory*/ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { free( test->M ); } /* Free N memory*/ free( test->N ); /* Free K memory*/ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K)) { free( test->K ); } /*Free LDA memory */ free( test->lda ); /*Free LDB memory */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { free( test->ldb ); } /*Free LDC memory */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { free( test->ldc ); } /*Free ALPHA memory */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||(routine == BBLAS_SYRK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)|| (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { free(test->alpha); }else if (routine == BBLAS_HERK) { free(test->alpha_herk); } /*Free ALPHA BETA memory */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_SYR2K)) { free( test->beta ); }else if ((routine == BBLAS_HERK) || (routine == BBLAS_HER2K)) { free(test->beta_herk); } /*Free matrices {A}_i */ for ( int batch_iter = 0; batch_iter < test->batch_count; batch_iter++ ) { free( test->arrayA[batch_iter] ); } free( test->arrayA ); /*Free matrices {B}_i*/ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { for ( int batch_iter = 0; batch_iter < test->batch_count; batch_iter++ ) { free( test->arrayB[batch_iter] ); } free( test->arrayB ); } /*Free matrices {C}_i*/ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { for ( int batch_iter = 0; batch_iter < test->batch_count; batch_iter++ ) { free( test->arrayC[batch_iter] ); } free( test->arrayC ); } /*Free memory allocated for error computation */ switch(test->target) { case BBLAS_MKL: free(test->mkl_error); //free(test->group_size); for ( int batch_iter = 0; batch_iter < test->batch_count; batch_iter++ ) { free( test->mkl_result[batch_iter] ); } free( test->mkl_result ); break; case BBLAS_CUBLAS: case BBLAS_MAGMA: free(test->device_error); for (int batch_iter =0; batch_iter < test->batch_count; batch_iter++) { free(test->device_result[batch_iter]); } free(test->device_result); break; case BBLAS_OTHER: free(test->other_error); for (int batch_iter =0; batch_iter < test->batch_count; batch_iter++) { free(test->other_result[batch_iter]); } free(test->other_result); break; case BBLAS_CUMKL: free(test->mkl_error); free(test->device_error); free(test->group_size); for (int batch_iter =0; batch_iter < test->batch_count; batch_iter++) { free(test->device_result[batch_iter]); free(test->mkl_result[batch_iter]); } free(test->device_result); free(test->mkl_result); break; default: printf("In bblas_zfreetest(): Target no defined\n"); exit(EXIT_FAILURE); } /*Free INFO */ free( test->info ); /*Free cuda memory */ if( (test->target == BBLAS_CUBLAS) || (test->target == BBLAS_MAGMA)) { bblas_zcudaFree(test); } if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { free(test->Binitnorm); } /*Free memory allocated for norm computing */ if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { free(test->Cinitnorm); } } #undef COMPLEX
{ "alphanum_fraction": 0.6192969189, "avg_line_length": 25.0841439689, "ext": "c", "hexsha": "17e183abdde810a384d7767994f1f20fc2ee3aa6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "NLAFET/BBLAS-ref", "max_forks_repo_path": "testing/bblas_ztesting.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "NLAFET/BBLAS-ref", "max_issues_repo_path": "testing/bblas_ztesting.c", "max_line_length": 105, "max_stars_count": null, "max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "NLAFET/BBLAS-ref", "max_stars_repo_path": "testing/bblas_ztesting.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 15834, "size": 51573 }
//===--- Sudoku/Solver_set_option.h ---===// // // Helper functions //===----------------------------------------------------------------------===// #pragma once #include "Board.h" #include "Location.h" #include "Location_Utilities.h" // is_same_* #include "Options.h" #include "Size.h" #include "Solvers_find.h" #include "Solvers_remove_option.h" #include "Value.h" #include "exceptions.h" #include "traits.h" #include <gsl/gsl> #include <vector> #include <algorithm> // find_if #include <iterator> // next #include <stdexcept> // logic_error #include <type_traits> // is_base_of #include "Solver.fwd.h" // Forward declaration - single_option #include <cassert> namespace Sudoku { //===----------------------------------------------------------------------===// template<int N, typename Options = Options<elem_size<N>>> int set_Value(Board<Options, N>&, Location<N>, Value); template<int N, typename Options = Options<elem_size<N>>, typename ItrT> int set_Value(Board<Options, N>&, ItrT begin, ItrT end); template<int N, typename Options = Options<elem_size<N>>, typename SectionT> int set_unique(Board<Options, N>&, SectionT, Value); template<int N, typename Options = Options<elem_size<N>>, typename SectionT> int set_uniques(Board<Options, N>&, SectionT, Options worker); template<int N, typename Options = Options<elem_size<N>>, typename SectionT> int set_section_locals( Board<Options, N>&, SectionT, int rep_count, Options values); template<int N, typename Options = Options<elem_size<N>>> int set_section_locals( Board<Options, N>&, Board_Section::Block<Options, N>, int rep_count, Options values); //===----------------------------------------------------------------------===// // IF a possible option, Make [value] the answer for [loc] template<int N, typename Options> inline int set_Value( Board<Options, N>& board, // NOLINT(runtime/references) const Location<N> loc, const Value value) { assert(is_valid(loc)); assert(is_valid<N>(value)); int changes{0}; auto& elem = board.at(loc); if (not elem.test(value)) // value is option nor answer throw error::invalid_Board(); if (not is_answer(elem)) { changes = gsl::narrow_cast<int>(elem.count_all()); elem.set_nocheck(value); } return changes; } // set board_ using a transferable container of values template<int N, typename Options, typename ItrT> int set_Value( Board<Options, N>& board, // NOLINT(runtime/references) const ItrT begin, const ItrT end) { { static_assert(traits::is_forward<ItrT>); assert(end - begin == full_size<N>); } int changes{0}; int n{0}; for (auto itr = begin; itr != end; ++itr) { const Location<N> loc(n++); // start at 0! // handle different input types Value value{}; if constexpr (traits::iterator_to<ItrT, Value>) { value = *itr; } else { value = to_Value<N>(*itr); } if (value != Value{0}) { if (not is_valid<N>(value)) { throw std::domain_error{"Invalid Value"}; } if (is_option(board.at(loc), value)) { // update options on board changes += single_option(board, loc, value); } assert(is_answer(board.at(loc), value)); } } assert(n == full_size<N>); return changes; } // Set unique values in section as answer template<int N, typename Options, typename SectionT> inline int set_uniques( Board<Options, N>& board, // NOLINT(runtime/references) const SectionT section, const Options worker) { { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert(std::is_same_v<typename SectionT::value_type, Options>); } int changes{0}; if (worker.count_all() > 0) { for (Value val{1}; val < Value{worker.size()}; ++val) { if (worker[val]) { changes += set_unique(board, section, val); } } } return changes; } // Set unique value in section as answer template<int N, typename Options, typename SectionT> inline int set_unique( Board<Options, N>& board, // NOLINT(runtime/references) const SectionT section, const Value value) { { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert(std::is_same_v<typename SectionT::value_type, Options>); static_assert(traits::is_input<typename SectionT::iterator>); assert(is_valid<N>(value)); } const auto end = section.cend(); const auto condition = [value](const Options& O) { return O.test(value); }; const auto itr = std::find_if(section.cbegin(), end, condition); if (itr == end) { // option not available in section throw error::invalid_Board(); } assert(&(*itr) == &board[itr.location()]); // section must be part of board assert(std::find_if(std::next(itr), end, condition) == end); // unique return single_option(board, itr.location(), value); } // for [row/col] per value: if all in same block, remove from rest block template<int N, typename Options, typename SectionT> inline int set_section_locals( Board<Options, N>& board, // NOLINT(runtime/references) const SectionT section, const int rep_count, const Options values) { { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert(std::is_same_v<typename SectionT::value_type, Options>); assert(rep_count > 1); // should have been caught by caller // use the set_uniques specialization assert(rep_count <= N); // won't fit in single block-row/col assert(values.count_all() > 0); } int changes{0}; std::vector<Location<N>> locations{}; // start at 1, to skip the answer-bit for (Value value{1}; value < Value{values.size()}; ++value) { if (values[value]) { locations = list_where_option<N>(section, value, rep_count); if (locations.size() != gsl::narrow_cast<size_t>(rep_count)) { assert(changes > 0); // changed by earlier value in values } else if (is_same_block<N>(locations.cbegin(), locations.cend())) { // remove from rest of block changes += remove_option_section( board, board.block(locations[0]), locations, value); } } } return changes; } // per value in [block]: if all in same row/col, remove from rest row/col template<int N, typename Options> inline int set_section_locals( Board<Options, N>& board, // NOLINT(runtime/references) const Board_Section::Block<Options, N> block, const int rep_count, const Options values) { { assert(rep_count > 1); // should have been caught by caller // use the set_uniques specialization assert(rep_count <= N); // won't fit in single block-row/col assert(values.count_all() > 0); } int changes{0}; std::vector<Location<N>> locations{}; // start at 1, to skip the answer-bit for (Value value{1}; value < Value{values.size()}; ++value) { if (values[value]) { locations = list_where_option<N>(block, value, rep_count); if (locations.size() != gsl::narrow_cast<size_t>(rep_count)) { assert(changes > 0); // changed by earlier value in values } else if (is_same_row<N>(locations.cbegin(), locations.cend())) { // remove from rest of row changes += remove_option_outside_block( board, board.row(locations[0]), locations[0], value); } else if (is_same_col<N>(locations.cbegin(), locations.cend())) { // remove from rest of col changes += remove_option_outside_block( board, board.col(locations[0]), locations[0], value); } } } return changes; } } // namespace Sudoku
{ "alphanum_fraction": 0.6644897959, "avg_line_length": 27.6315789474, "ext": "h", "hexsha": "ea1e0c04f7e6ad66b45e0634626b5d5bb721dc90", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "FeodorFitsner/fwkSudoku", "max_forks_repo_path": "Sudoku/Sudoku/Solvers_set_option.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "FeodorFitsner/fwkSudoku", "max_issues_repo_path": "Sudoku/Sudoku/Solvers_set_option.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "FeodorFitsner/fwkSudoku", "max_stars_repo_path": "Sudoku/Sudoku/Solvers_set_option.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1903, "size": 7350 }
/* histogram/test2d_resample.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_histogram2d.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include "urand.c" int main (void) { size_t i, j; int status = 0; double total = 0; size_t N = 200000; gsl_histogram2d *h; gsl_ieee_env_setup (); h = gsl_histogram2d_calloc_uniform (10, 10, 0.0, 1.0, 0.0, 1.0); for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { double w = 10.0 * i + j; total += w; gsl_histogram2d_accumulate (h, 0.1 * i, 0.1 * i, w); } } { gsl_histogram2d_pdf *p = gsl_histogram2d_pdf_alloc (10,10); gsl_histogram2d *hh = gsl_histogram2d_calloc_uniform (20, 20, 0.0, 1.0, 0.0, 1.0); gsl_histogram2d_pdf_init (p, h); for (i = 0; i < N; i++) { double u = urand(); double v = urand(); double x, y; status = gsl_histogram2d_pdf_sample (p, u, v, &x, &y); status = gsl_histogram2d_increment (hh, x, y); } status = 0; for (i = 0; i < 20; i++) { for (j = 0; j < 20; j++) { double z = 4 * total * gsl_histogram2d_get (hh, i, j) / (double) N; size_t k1, k2; double ya; double x, xmax, y, ymax; gsl_histogram2d_get_xrange (hh, i, &x, &xmax); gsl_histogram2d_get_yrange (hh, j, &y, &ymax); gsl_histogram2d_find (h, x, y, &k1, &k2); ya = gsl_histogram2d_get (h, k1, k2); if (ya == 0) { if (z != 0) { status = 1; printf ("(%d,%d): %g vs %g\n", (int)i, (int)j, z, ya); } } else { double err = 1 / sqrt (gsl_histogram2d_get (hh, i, j)); double sigma = fabs ((z - ya) / (ya * err)); if (sigma > 3) { status = 1; printf ("%g vs %g err=%g sigma=%g\n", z, ya, err, sigma); } } } } gsl_histogram2d_pdf_free (p) ; gsl_histogram2d_free (hh) ; gsl_test (status, "gsl_histogram2d_pdf_sample within statistical errors"); } gsl_histogram2d_free (h) ; exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.5995732575, "avg_line_length": 23.8305084746, "ext": "c", "hexsha": "480cce96aaa802898e817acd09261d8e57479b2f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/histogram/test2d_resample.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/histogram/test2d_resample.c", "max_line_length": 78, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/test2d_resample.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 943, "size": 2812 }
/* linalg/luc.c * * Copyright (C) 2001, 2007, 2009 Brian Gough * Copyright (C) 2019 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_linalg.h> #include "recurse.h" static int LU_decomp_L2 (gsl_matrix_complex * A, gsl_vector_uint * ipiv); static int LU_decomp_L3 (gsl_matrix_complex * A, gsl_vector_uint * ipiv); static int singular (const gsl_matrix_complex * LU); static int apply_pivots(gsl_matrix_complex * A, const gsl_vector_uint * ipiv); /* Factorise a general N x N complex matrix A into, * * P A = L U * * where P is a permutation matrix, L is unit lower triangular and U * is upper triangular. * * L is stored in the strict lower triangular part of the input * matrix. The diagonal elements of L are unity and are not stored. * * U is stored in the diagonal and upper triangular part of the * input matrix. * * P is stored in the permutation p. Column j of P is column k of the * identity matrix, where k = permutation->data[j] * * signum gives the sign of the permutation, (-1)^n, where n is the * number of interchanges in the permutation. * * See Golub & Van Loan, Matrix Computations, Algorithm 3.4.1 (Gauss * Elimination with Partial Pivoting). */ int gsl_linalg_complex_LU_decomp (gsl_matrix_complex * A, gsl_permutation * p, int *signum) { const size_t M = A->size1; if (p->size != M) { GSL_ERROR ("permutation length must match matrix size1", GSL_EBADLEN); } else { int status; const size_t N = A->size2; const size_t minMN = GSL_MIN(M, N); gsl_vector_uint * ipiv = gsl_vector_uint_alloc(minMN); gsl_matrix_complex_view AL = gsl_matrix_complex_submatrix(A, 0, 0, M, minMN); size_t i; status = LU_decomp_L3 (&AL.matrix, ipiv); /* process remaining right matrix */ if (M < N) { gsl_matrix_complex_view AR = gsl_matrix_complex_submatrix(A, 0, M, M, N - M); /* apply pivots to AR */ apply_pivots(&AR.matrix, ipiv); /* AR = AL^{-1} AR */ gsl_blas_ztrsm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, GSL_COMPLEX_ONE, &AL.matrix, &AR.matrix); } /* convert ipiv array to permutation */ gsl_permutation_init(p); *signum = 1; for (i = 0; i < minMN; ++i) { unsigned int pivi = gsl_vector_uint_get(ipiv, i); if (p->data[pivi] != p->data[i]) { size_t tmp = p->data[pivi]; p->data[pivi] = p->data[i]; p->data[i] = tmp; *signum = -(*signum); } } gsl_vector_uint_free(ipiv); return status; } } /* LU_decomp_L2 LU decomposition with partial pivoting using Level 2 BLAS Inputs: A - on input, matrix to be factored; on output, L and U factors ipiv - (output) array containing row swaps Notes: 1) Based on LAPACK ZGETF2 */ static int LU_decomp_L2 (gsl_matrix_complex * A, gsl_vector_uint * ipiv) { const size_t M = A->size1; const size_t N = A->size2; const size_t minMN = GSL_MIN(M, N); if (ipiv->size != minMN) { GSL_ERROR ("ipiv length must equal MIN(M,N)", GSL_EBADLEN); } else { size_t i, j; for (j = 0; j < minMN; ++j) { /* find maximum in the j-th column */ gsl_vector_complex_view v = gsl_matrix_complex_subcolumn(A, j, j, M - j); size_t j_pivot = j + gsl_blas_izamax(&v.vector); gsl_vector_complex_view v1, v2; gsl_vector_uint_set(ipiv, j, j_pivot); if (j_pivot != j) { /* swap rows j and j_pivot */ v1 = gsl_matrix_complex_row(A, j); v2 = gsl_matrix_complex_row(A, j_pivot); gsl_blas_zswap(&v1.vector, &v2.vector); } if (j < M - 1) { gsl_complex Ajj = gsl_matrix_complex_get(A, j, j); gsl_complex Ajjinv = gsl_complex_inverse(Ajj); if (gsl_complex_abs(Ajj) >= GSL_DBL_MIN) { v1 = gsl_matrix_complex_subcolumn(A, j, j + 1, M - j - 1); gsl_blas_zscal(Ajjinv, &v1.vector); } else { for (i = 1; i < M - j; ++i) { gsl_complex * ptr = gsl_matrix_complex_ptr(A, j + i, j); *ptr = gsl_complex_mul(*ptr, Ajjinv); } } } if (j < minMN - 1) { gsl_matrix_complex_view A22 = gsl_matrix_complex_submatrix(A, j + 1, j + 1, M - j - 1, N - j - 1); v1 = gsl_matrix_complex_subcolumn(A, j, j + 1, M - j - 1); v2 = gsl_matrix_complex_subrow(A, j, j + 1, N - j - 1); gsl_blas_zgeru(GSL_COMPLEX_NEGONE, &v1.vector, &v2.vector, &A22.matrix); } } return GSL_SUCCESS; } } /* LU_decomp_L3 LU decomposition with partial pivoting using Level 3 BLAS Inputs: A - on input, matrix to be factored; on output, L and U factors ipiv - (output) array containing row swaps Notes: 1) Based on ReLAPACK DGETRF */ static int LU_decomp_L3 (gsl_matrix_complex * A, gsl_vector_uint * ipiv) { const size_t M = A->size1; const size_t N = A->size2; if (M < N) { GSL_ERROR ("matrix must have M >= N", GSL_EBADLEN); } else if (ipiv->size != GSL_MIN(M, N)) { GSL_ERROR ("ipiv length must equal MIN(M,N)", GSL_EBADLEN); } else if (N <= CROSSOVER_LU) { /* use Level 2 algorithm */ return LU_decomp_L2(A, ipiv); } else { /* * partition matrix: * * N1 N2 * N1 [ A11 A12 ] * M2 [ A21 A22 ] * * and * N1 N2 * M [ AL AR ] */ int status; const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N); const size_t N2 = N - N1; const size_t M2 = M - N1; gsl_matrix_complex_view A11 = gsl_matrix_complex_submatrix(A, 0, 0, N1, N1); gsl_matrix_complex_view A12 = gsl_matrix_complex_submatrix(A, 0, N1, N1, N2); gsl_matrix_complex_view A21 = gsl_matrix_complex_submatrix(A, N1, 0, M2, N1); gsl_matrix_complex_view A22 = gsl_matrix_complex_submatrix(A, N1, N1, M2, N2); gsl_matrix_complex_view AL = gsl_matrix_complex_submatrix(A, 0, 0, M, N1); gsl_matrix_complex_view AR = gsl_matrix_complex_submatrix(A, 0, N1, M, N2); /* * partition ipiv = [ ipiv1 ] N1 * [ ipiv2 ] N2 */ gsl_vector_uint_view ipiv1 = gsl_vector_uint_subvector(ipiv, 0, N1); gsl_vector_uint_view ipiv2 = gsl_vector_uint_subvector(ipiv, N1, N2); size_t i; /* recursion on (AL, ipiv1) */ status = LU_decomp_L3(&AL.matrix, &ipiv1.vector); if (status) return status; /* apply ipiv1 to AR */ apply_pivots(&AR.matrix, &ipiv1.vector); /* A12 = A11^{-1} A12 */ gsl_blas_ztrsm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, GSL_COMPLEX_ONE, &A11.matrix, &A12.matrix); /* A22 = A22 - A21 * A12 */ gsl_blas_zgemm(CblasNoTrans, CblasNoTrans, GSL_COMPLEX_NEGONE, &A21.matrix, &A12.matrix, GSL_COMPLEX_ONE, &A22.matrix); /* recursion on (A22, ipiv2) */ status = LU_decomp_L3(&A22.matrix, &ipiv2.vector); if (status) return status; /* apply pivots to A21 */ apply_pivots(&A21.matrix, &ipiv2.vector); /* shift pivots */ for (i = 0; i < N2; ++i) { unsigned int * ptr = gsl_vector_uint_ptr(&ipiv2.vector, i); *ptr += N1; } return GSL_SUCCESS; } } int gsl_linalg_complex_LU_solve (const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x) { if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (LU->size2 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else if (singular (LU)) { GSL_ERROR ("matrix is singular", GSL_EDOM); } else { int status; /* copy x <- b */ gsl_vector_complex_memcpy (x, b); /* solve for x */ status = gsl_linalg_complex_LU_svx (LU, p, x); return status; } } int gsl_linalg_complex_LU_svx (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_vector_complex * x) { if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != x->size) { GSL_ERROR ("matrix size must match solution/rhs size", GSL_EBADLEN); } else if (singular (LU)) { GSL_ERROR ("matrix is singular", GSL_EDOM); } else { /* apply permutation to RHS */ gsl_permute_vector_complex (p, x); /* solve for c using forward-substitution, L c = P b */ gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasUnit, LU, x); /* perform back-substitution, U x = c */ gsl_blas_ztrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LU, x); return GSL_SUCCESS; } } int gsl_linalg_complex_LU_refine (const gsl_matrix_complex * A, const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x, gsl_vector_complex * work) { if (A->size1 != A->size2) { GSL_ERROR ("matrix a must be square", GSL_ENOTSQR); } if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (A->size1 != LU->size2) { GSL_ERROR ("LU matrix must be decomposition of a", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (LU->size1 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else if (LU->size1 != work->size) { GSL_ERROR ("matrix size must match workspace size", GSL_EBADLEN); } else if (singular (LU)) { GSL_ERROR ("matrix is singular", GSL_EDOM); } else { int status; /* Compute residual = (A * x - b) */ gsl_vector_complex_memcpy (work, b); { gsl_complex one = GSL_COMPLEX_ONE; gsl_complex negone = GSL_COMPLEX_NEGONE; gsl_blas_zgemv (CblasNoTrans, one, A, x, negone, work); } /* Find correction, delta = - (A^-1) * residual, and apply it */ status = gsl_linalg_complex_LU_svx (LU, p, work); { gsl_complex negone= GSL_COMPLEX_NEGONE; gsl_blas_zaxpy (negone, work, x); } return status; } } int gsl_linalg_complex_LU_invert (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_matrix_complex * inverse) { if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (inverse->size1 != LU->size1 || inverse->size2 != LU->size2) { GSL_ERROR ("inverse matrix must match LU matrix dimensions", GSL_EBADLEN); } else { gsl_matrix_complex_memcpy(inverse, LU); return gsl_linalg_complex_LU_invx(inverse, p); } } int gsl_linalg_complex_LU_invx (gsl_matrix_complex * LU, const gsl_permutation * p) { if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (singular (LU)) { GSL_ERROR ("matrix is singular", GSL_EDOM); } else { int status; const size_t N = LU->size1; size_t i; /* compute U^{-1} */ status = gsl_linalg_complex_tri_invert(CblasUpper, CblasNonUnit, LU); if (status) return status; /* compute L^{-1} */ status = gsl_linalg_complex_tri_invert(CblasLower, CblasUnit, LU); if (status) return status; /* compute U^{-1} L^{-1} */ status = gsl_linalg_complex_tri_UL(LU); if (status) return status; /* apply permutation to columns of A^{-1} */ for (i = 0; i < N; ++i) { gsl_vector_complex_view v = gsl_matrix_complex_row(LU, i); gsl_permute_vector_complex_inverse(p, &v.vector); } return GSL_SUCCESS; } } gsl_complex gsl_linalg_complex_LU_det (gsl_matrix_complex * LU, int signum) { size_t i, n = LU->size1; gsl_complex det = gsl_complex_rect((double) signum, 0.0); for (i = 0; i < n; i++) { gsl_complex zi = gsl_matrix_complex_get (LU, i, i); det = gsl_complex_mul (det, zi); } return det; } double gsl_linalg_complex_LU_lndet (gsl_matrix_complex * LU) { size_t i, n = LU->size1; double lndet = 0.0; for (i = 0; i < n; i++) { gsl_complex z = gsl_matrix_complex_get (LU, i, i); lndet += log (gsl_complex_abs (z)); } return lndet; } gsl_complex gsl_linalg_complex_LU_sgndet (gsl_matrix_complex * LU, int signum) { size_t i, n = LU->size1; gsl_complex phase = gsl_complex_rect((double) signum, 0.0); for (i = 0; i < n; i++) { gsl_complex z = gsl_matrix_complex_get (LU, i, i); double r = gsl_complex_abs(z); if (r == 0) { phase = gsl_complex_rect(0.0, 0.0); break; } else { z = gsl_complex_div_real(z, r); phase = gsl_complex_mul(phase, z); } } return phase; } static int singular (const gsl_matrix_complex * LU) { size_t i, n = LU->size1; for (i = 0; i < n; i++) { gsl_complex u = gsl_matrix_complex_get (LU, i, i); if (GSL_REAL(u) == 0 && GSL_IMAG(u) == 0) return 1; } return 0; } static int apply_pivots(gsl_matrix_complex * A, const gsl_vector_uint * ipiv) { if (0) { } else { size_t i; for (i = 0; i < ipiv->size; ++i) { size_t pi = gsl_vector_uint_get(ipiv, i); if (i != pi) { /* swap rows i and pi */ gsl_vector_complex_view v1 = gsl_matrix_complex_row(A, i); gsl_vector_complex_view v2 = gsl_matrix_complex_row(A, pi); gsl_blas_zswap(&v1.vector, &v2.vector); } } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5952726127, "avg_line_length": 26.4416666667, "ext": "c", "hexsha": "90b74a8c4960b63ab17c911404977736486be68b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/luc.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/linalg/luc.c", "max_line_length": 198, "max_stars_count": null, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/linalg/luc.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4592, "size": 15865 }
/* linalg/test_luc.c * * Copyright (C) 2019 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_test.h> #include <gsl/gsl_math.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_permutation.h> static int test_LUc_decomp_eps(const gsl_matrix_complex * m, const double eps, const char * desc) { int s = 0; const size_t M = m->size1; const size_t N = m->size2; gsl_matrix_complex * A = gsl_matrix_complex_alloc(M, N); gsl_matrix_complex * PLU = gsl_matrix_complex_calloc(M, N); gsl_permutation * p = gsl_permutation_alloc(M); size_t i, j; int signum; gsl_matrix_complex_memcpy(A, m); gsl_linalg_complex_LU_decomp(A, p, &signum); if (M >= N) { gsl_matrix_complex_view U = gsl_matrix_complex_submatrix(A, 0, 0, N, N); /* copy L factor into PLU */ for (j = 0; j < GSL_MIN(M, N); ++j) { gsl_vector_complex_view v1 = gsl_matrix_complex_subcolumn(A, j, j, M - j); gsl_vector_complex_view v2 = gsl_matrix_complex_subcolumn(PLU, j, j, M - j); gsl_vector_complex_memcpy(&v2.vector, &v1.vector); gsl_matrix_complex_set(PLU, j, j, GSL_COMPLEX_ONE); } /* PLU := L * U */ gsl_blas_ztrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, GSL_COMPLEX_ONE, &U.matrix, PLU); } else { gsl_matrix_complex_view L = gsl_matrix_complex_submatrix(A, 0, 0, M, M); /* copy U factor into PLU */ for (i = 0; i < GSL_MIN(M, N); ++i) { gsl_vector_complex_view v1 = gsl_matrix_complex_subrow(A, i, i, N - i); gsl_vector_complex_view v2 = gsl_matrix_complex_subrow(PLU, i, i, N - i); gsl_vector_complex_memcpy(&v2.vector, &v1.vector); } /* PLU := L * U */ gsl_blas_ztrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, GSL_COMPLEX_ONE, &L.matrix, PLU); } /* PLU := P * L * U */ for (j = 0; j < N; ++j) { gsl_vector_complex_view v = gsl_matrix_complex_column(PLU, j); gsl_permute_vector_complex_inverse(p, &v.vector); } /* now test m = PLU */ for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { gsl_complex aij = gsl_matrix_complex_get(PLU, i, j); gsl_complex mij = gsl_matrix_complex_get(m, i, j); gsl_test_rel(GSL_REAL(aij), GSL_REAL(mij), eps, "%s real: (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, i, j, GSL_REAL(aij), GSL_REAL(mij)); gsl_test_rel(GSL_IMAG(aij), GSL_IMAG(mij), eps, "%s imag: (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, i, j, GSL_IMAG(aij), GSL_IMAG(mij)); } } gsl_matrix_complex_free(A); gsl_matrix_complex_free(PLU); gsl_permutation_free(p); return s; } static int test_LUc_decomp(gsl_rng * r) { int s = 0; size_t n; /* test square matrices */ for (n = 1; n <= 50; ++n) { gsl_matrix_complex * m = gsl_matrix_complex_alloc(n, n); create_random_complex_matrix(m, r); test_LUc_decomp_eps(m, 1.0e4 * n * GSL_DBL_EPSILON, "complex_LU_decomp random"); gsl_matrix_complex_free(m); } { gsl_matrix_complex * m = gsl_matrix_complex_alloc(100, 50); create_random_complex_matrix(m, r); test_LUc_decomp_eps(m, 256.0 * n * GSL_DBL_EPSILON, "complex_LU_decomp rect1"); gsl_matrix_complex_free(m); } { gsl_matrix_complex * m = gsl_matrix_complex_alloc(50, 100); create_random_complex_matrix(m, r); test_LUc_decomp_eps(m, 1.0e3 * n * GSL_DBL_EPSILON, "complex_LU_decomp rect2"); gsl_matrix_complex_free(m); } { gsl_matrix_complex * m = gsl_matrix_complex_alloc(80, 100); create_random_complex_matrix(m, r); test_LUc_decomp_eps(m, 1.0e3 * n * GSL_DBL_EPSILON, "complex_LU_decomp rect3"); gsl_matrix_complex_free(m); } return s; } static int test_LUc_solve_eps(const gsl_matrix_complex * m, const gsl_vector_complex * rhs, const gsl_vector_complex * sol, const double eps, const char * desc) { int s = 0; const size_t N = m->size1; int signum; size_t i; gsl_permutation * perm = gsl_permutation_alloc(N); gsl_matrix_complex * lu = gsl_matrix_complex_alloc(N, N); gsl_vector_complex * x = gsl_vector_complex_alloc(N); gsl_vector_complex * residual = gsl_vector_complex_alloc(N); gsl_matrix_complex_memcpy(lu, m); s += gsl_linalg_complex_LU_decomp(lu, perm, &signum); s += gsl_linalg_complex_LU_solve(lu, perm, rhs, x); for (i = 0; i < N; i++) { gsl_complex xi = gsl_vector_complex_get(x, i); gsl_complex yi = gsl_vector_complex_get(sol, i); gsl_test_rel(GSL_REAL(xi), GSL_REAL(yi), eps, "%s: real %3lu[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_REAL(xi), GSL_REAL(yi)); gsl_test_rel(GSL_IMAG(xi), GSL_IMAG(yi), eps, "%s: imag %3lu[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_IMAG(xi), GSL_IMAG(yi)); } s += gsl_linalg_complex_LU_refine(m, lu, perm, rhs, x, residual); for (i = 0; i < N; i++) { gsl_complex xi = gsl_vector_complex_get(x, i); gsl_complex yi = gsl_vector_complex_get(sol, i); gsl_test_rel(GSL_REAL(xi), GSL_REAL(yi), eps, "%s: improved real %3lu[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_REAL(xi), GSL_REAL(yi)); gsl_test_rel(GSL_IMAG(xi), GSL_IMAG(yi), eps, "%s: improved imag %3lu[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_IMAG(xi), GSL_IMAG(yi)); } gsl_vector_complex_free(residual); gsl_vector_complex_free(x); gsl_matrix_complex_free(lu); gsl_permutation_free(perm); return s; } static int test_LUc_solve(gsl_rng * r) { int s = 0; size_t n; for (n = 1; n <= 50; ++n) { gsl_matrix_complex * m = gsl_matrix_complex_alloc(n, n); gsl_vector_complex * rhs = gsl_vector_complex_alloc(n); gsl_vector_complex * sol = gsl_vector_complex_alloc(n); create_random_complex_matrix(m, r); create_random_complex_vector(sol, r); gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_ONE, m, sol, GSL_COMPLEX_ZERO, rhs); test_LUc_solve_eps(m, rhs, sol, 1.0e5 * n * GSL_DBL_EPSILON, "complex_LU_solve random"); gsl_matrix_complex_free(m); gsl_vector_complex_free(rhs); gsl_vector_complex_free(sol); } return s; } int test_LUc_invert_eps(const gsl_matrix_complex * m, const double eps, const char *desc) { int s = 0; size_t i, j, N = m->size1; gsl_matrix_complex * lu = gsl_matrix_complex_alloc(N, N); gsl_matrix_complex * c = gsl_matrix_complex_alloc(N, N); gsl_permutation * perm = gsl_permutation_alloc(N); int signum; gsl_matrix_complex_memcpy(lu, m); s += gsl_linalg_complex_LU_decomp(lu, perm, &signum); s += gsl_linalg_complex_LU_invx(lu, perm); /* c = m m^{-1} */ gsl_blas_zgemm(CblasNoTrans, CblasNoTrans, GSL_COMPLEX_ONE, m, lu, GSL_COMPLEX_ZERO, c); /* c should be the identity matrix */ for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { gsl_complex cij = gsl_matrix_complex_get(c, i, j); double expected = (i == j) ? 1.0 : 0.0; gsl_test_rel(GSL_REAL(cij), expected, eps, "%s real (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, N, N, i, j, GSL_REAL(cij), expected); gsl_test_rel(GSL_IMAG(cij), 0.0, eps, "%s imag (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, N, N, i, j, GSL_IMAG(cij), 0.0); } } gsl_matrix_complex_free(lu); gsl_matrix_complex_free(c); gsl_permutation_free(perm); return s; } static int test_LUc_invert(gsl_rng * r) { int s = 0; size_t n; for (n = 1; n <= 50; ++n) { gsl_matrix_complex * m = gsl_matrix_complex_alloc(n, n); create_random_complex_matrix(m, r); test_LUc_invert_eps(m, 1.0e5 * n * GSL_DBL_EPSILON, "complex_LU_invert random"); gsl_matrix_complex_free(m); } return s; }
{ "alphanum_fraction": 0.6398314735, "avg_line_length": 30.1786941581, "ext": "c", "hexsha": "160e2004f0a1b74bda1521ddbfb24aaa7d29400e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "igormcoelho/optstats", "max_forks_repo_path": "thirdparty/gsl-2.7/linalg/test_luc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "igormcoelho/optstats", "max_issues_repo_path": "thirdparty/gsl-2.7/linalg/test_luc.c", "max_line_length": 149, "max_stars_count": null, "max_stars_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "igormcoelho/optstats", "max_stars_repo_path": "thirdparty/gsl-2.7/linalg/test_luc.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2702, "size": 8782 }
#include <stdio.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_matrix.h> #include <time.h> #define N_OF_RUNS 10 #define RUSAGE_DIFF(r1, r2) \ ((double) ((r1).tv_sec - (r2).tv_sec) + (double) ((r1).tv_nsec - (r2).tv_nsec)/(double)1E9) gsl_vector* random_vector(size_t); gsl_matrix* random_matrix(size_t); double* ddot_test(size_t); double* dgemv_test(size_t); void test_suite(size_t, size_t, size_t, const char*); int main() { srand48((unsigned int)time(NULL)); const char filename[] = "results.csv"; test_suite(1, 15000, 1000, filename); return 0; } void test_suite(const size_t from, const size_t to, const size_t step, const char* filename){ FILE* file = fopen(filename, "w"); if(file == NULL){ printf("Error opening file, exiting \r\n"); exit(EXIT_FAILURE); } fprintf(file, "LEVEL,SIZE,TIME\r\n"); double* ddot_result, * dgemv_result; for(size_t i = from; i < to; i += step){ for(int j = 0; j < N_OF_RUNS; j++) { ddot_result = ddot_test(i); dgemv_result = dgemv_test(i); fprintf(file, "%d,%d,%lf\r\n", 1, (int) i, *ddot_result); fprintf(file, "%d,%d,%lf\r\n", 2, (int) i, *dgemv_result); free(ddot_result); free(dgemv_result); } } fclose(file); } gsl_vector* random_vector(const size_t size) { gsl_vector* a = gsl_vector_calloc(size); for(int i = 0; i < size; i++) gsl_vector_set(a, (size_t)i, drand48()*10); return a; } gsl_matrix* random_matrix(const size_t size) { gsl_matrix* a = gsl_matrix_calloc(size, size); for(int i = 0; i < size; i++) for(int j = 0; j < size; j++) gsl_matrix_set(a, (size_t)i, (size_t)j, drand48()*10); return a; } double* ddot_test(const size_t size) { gsl_vector* v_1 = random_vector(size); gsl_vector* v_2 = random_vector(size); printf("Multiplying 2 vectors of size %d \r\n", (int)size); double * result = calloc(1, sizeof(double)); struct timespec real_start, real_end; clock_gettime(CLOCK_REALTIME, &real_start); for(int i = 0; i < N_OF_RUNS; i++) { gsl_blas_ddot(v_1, v_2, result); } clock_gettime(CLOCK_REALTIME, &real_end); double* time = malloc(sizeof(double)); *time = RUSAGE_DIFF(real_end, real_start)/10; printf("Real time = %lf \r\n", *time); free(result); gsl_vector_free(v_1); gsl_vector_free(v_2); return time; } double* dgemv_test(const size_t size) { gsl_vector* v_1 = random_vector(size); gsl_vector* v_2 = random_vector(size); gsl_matrix* m_1 = random_matrix(size); printf("Multiplying vector times matrix of size %d \r\n", (int)size); struct timespec real_start, real_end; clock_gettime(CLOCK_REALTIME, &real_start); gsl_blas_dgemv(CblasNoTrans, 1, m_1, v_1, 0, v_2); clock_gettime(CLOCK_REALTIME, &real_end); double* time = malloc(sizeof(double)); *time = RUSAGE_DIFF(real_end, real_start); printf("Real time = %lf \r\n", *time); gsl_vector_free(v_1); gsl_matrix_free(m_1); return time; }
{ "alphanum_fraction": 0.6339488176, "avg_line_length": 30.2647058824, "ext": "c", "hexsha": "ff739ad259c792cded94e7cbfb8e881f50297a76", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-12-13T10:05:17.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-13T10:05:17.000Z", "max_forks_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kamilok1965/CMfSaT", "max_forks_repo_path": "lab_2/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kamilok1965/CMfSaT", "max_issues_repo_path": "lab_2/main.c", "max_line_length": 95, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kamilok1965/CMfSaT", "max_stars_repo_path": "lab_2/main.c", "max_stars_repo_stars_event_max_datetime": "2019-01-09T18:59:11.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-09T18:59:11.000Z", "num_tokens": 931, "size": 3087 }
#pragma once #include "Graphics/BufferObject.h" #include "Graphics/GraphicsResource.h" #include "Math/Bounds.h" #include <glad/gl.h> #include <glm/glm.hpp> #include <gsl/span> #include <vector> struct DrawingContext; template<typename T> struct MeshAttributeData { gsl::span<T> values; GLint valueSize = 0; }; struct MeshData { gsl::span<GLuint> indices; MeshAttributeData<GLfloat> positions; MeshAttributeData<GLfloat> normals; MeshAttributeData<GLfloat> texCoords; MeshAttributeData<GLfloat> tangents; MeshAttributeData<GLfloat> bitangents; MeshAttributeData<GLfloat> colors; }; class MeshSection : public GraphicsResource { public: MeshSection(); MeshSection(const MeshSection& other) = delete; MeshSection(MeshSection&& other); ~MeshSection(); MeshSection& operator=(const MeshSection& other) = delete; MeshSection& operator=(MeshSection&& other); private: void move(MeshSection&& other); void release(); public: void setData(const MeshData& data); void draw(const DrawingContext& context) const; const Bounds& getBounds() const { return bounds; } void setLabel(std::string newLabel); private: void bind() const; BufferObject elementBufferObject; VertexBufferObject positionBufferObject; VertexBufferObject normalBufferObject; VertexBufferObject texCoordBufferObject; VertexBufferObject tangentBufferObject; VertexBufferObject bitangentBufferObject; VertexBufferObject colorBufferObject; GLsizei numIndices; Bounds bounds; }; class Mesh { public: Mesh(std::vector<MeshSection>&& meshSections); void draw(const DrawingContext& context) const; std::vector<MeshSection>& getSections() { return sections; } const std::vector<MeshSection>& getSections() const { return sections; } private: std::vector<MeshSection> sections; };
{ "alphanum_fraction": 0.7308302485, "avg_line_length": 20.1170212766, "ext": "h", "hexsha": "d7e40e06d651105ad21b4c2b63dc9df628cc8250", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "aaronmjacobs/Swap", "max_forks_repo_path": "Source/Graphics/Mesh.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "aaronmjacobs/Swap", "max_issues_repo_path": "Source/Graphics/Mesh.h", "max_line_length": 61, "max_stars_count": null, "max_stars_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "aaronmjacobs/Swap", "max_stars_repo_path": "Source/Graphics/Mesh.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 439, "size": 1891 }
/** */ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "aXe_grism.h" #include <math.h> #include <string.h> #include <ctype.h> #include "drz2pet_utils.h" /** * Function: make_spc_drztable * The function generates and fills an ap_pixel vector for one * drizzled 2D grism image. * * Parameters: * @param obs - pointer to observation structure with image values * @param obs - pointer to observation structure with image values * @param ob - pointer to the description of the current beam * @param lambda0 - the starting wavelength in this drizzled image * @param dlambda - the dispersion in this drizzled image * * Returns: * @return table - pointer to an ap_pixel vector */ ap_pixel * make_spc_drztable(observation * const obs, observation * const wobs, const object *ob, const double lambda0, const double dlambda){ ap_pixel *table, *cur_ap; int npix1, npix2; int nsub1=1, nsub2=1; int i, j; int beamInt = 0; npix1 = obs->grism->size1; npix2 = obs->grism->size2; if (!(table = malloc ((npix1 * npix2 + 1) * sizeof (ap_pixel) * nsub1 * nsub2))) return NULL; cur_ap = table; for (i = 0; i < npix1; i++){ for (j = 0; j < npix2; j++){ //* check whether the pixel is within the extraction box if (fabs((double)j - ob->beams[beamInt].refpoint.y) > ob->beams[beamInt].width + .5) continue; //* fill the ap_pixel cur_ap->p_x = i; cur_ap->p_y = j; cur_ap->x = (double)i - ob->beams[beamInt].refpoint.x; cur_ap->y = (double)j - ob->beams[beamInt].refpoint.y; cur_ap->dist = (double)j - ob->beams[beamInt].refpoint.y; cur_ap->xs = (double)i - ob->beams[beamInt].refpoint.x; cur_ap->ys = 0.0; cur_ap->dxs = 0.0; // be reminded: dxs is the LOCAL TRACEANGLE, not the pixels size.. cur_ap->xi = (double)i - ob->beams[beamInt].refpoint.x; cur_ap->lambda = lambda0 + dlambda * ((double)i - ob->beams[beamInt].refpoint.x); cur_ap->dlambda = dlambda; // transfer the cps values and the weight values cur_ap->count = gsl_matrix_get(obs->grism, i, j); cur_ap->weight = gsl_matrix_get(wobs->grism, i, j); cur_ap->error = gsl_matrix_get(obs->pixerrs, i, j); cur_ap->contam = gsl_matrix_get(obs->dq, i, j); // dq is always set to zero, bad (=unexposed) pixels // have exptime=weight=0.0 cur_ap->dq = 0; // go to the next // PET pixel cur_ap++; } } cur_ap->p_x = -1; cur_ap->p_y = -1; cur_ap->count = -1; return table; } /** * Function: get_ID_num * The function generates the extension name used in the PET * for a 2D drizzled grism image * * Parameters: * @param grism_image - the name of the 2D drizzled grism image * @param extname - The ID number of the image * * Returns: * @return WorkPtr - Pointer to the ID-string */ char *get_ID_num (char *grism_image, char *extname){ char *WorkPtr; char *WorkPtr2; char **t_err=NULL; char tmp[MAXCHAR]; char ID[4]; int len; int i=0; strcpy(ID,"_ID"); strcpy(tmp, grism_image); t_err = (char **) malloc(sizeof(char *)*1); WorkPtr = strstr(tmp, ID)+3; WorkPtr2 = WorkPtr + strlen (WorkPtr); while (isspace ((int) *WorkPtr2)) *WorkPtr2-- = '\0'; WorkPtr2 = WorkPtr2 - 1; len = strlen(WorkPtr); while (i++ < len){ strtol(WorkPtr,t_err,10); if (strlen(t_err[0])==0) break; *WorkPtr2-- = '\0'; } strcpy(extname,WorkPtr); free(t_err); return WorkPtr; } /** * Function: normalize_weight * The function computes the weights used in the extraction * from the exposure times given for each pixel in a column. * * Parameters: * @param wobs - pointer to the structure which carries the pixel data * @param ob - pointer to the beam description */ void normalize_weight(observation *wobs, object *ob, const int opt_extr) { gsl_matrix *weight; //int i, j; // // check for optimal extraction if (opt_extr) { // let the optimal weights compute fprintf(stdout, "aXe_DRZ2PET: Use otpimal weighting.\n"); weight = comp_opt_weight(wobs->pixerrs, wobs->dq, ob); } else { // let the exposure time weights compute fprintf(stdout, "aXe_DRZ2PET: Use normal, flat weighting.\n"); weight = comp_equ_weight(wobs->grism, ob); // code lines for exposure time weighting //fprintf(stdout, "use exposure time weighting\n"); //weight = comp_exp_weight(wobs->grism, ob); } // replace the weight extension with the new weights gsl_matrix_free(wobs->grism); wobs->grism = weight; } /* * Function: comp_equ_weight * The function creates and fills a weight map with flat entries. * Pixels with non-zero exposure time which which contribute to the * extracted spectrum all receive the weight 1.0, all other * get the weight 0.0. * * Parameters: * @param exp_map - the matrix with the exposure times * @param ob - the object structure * * Returns: * @return weight - the matrix with the exposure time weights */ gsl_matrix * comp_equ_weight(gsl_matrix *exp_map, const object *ob) { gsl_matrix *weight; int i, j; int beamInt = 0; // allocate the matrix and set it to the default weight = gsl_matrix_alloc(exp_map->size1, exp_map->size2); gsl_matrix_set_all(weight, 0.0); // go over all columns for (i=0; i < (int)exp_map->size1; i++) // go over all rows for (j=0; j < (int)exp_map->size2; j++) // check whether the pixel is inside the extraction // area and has a positive exposure time if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5 && gsl_matrix_get(exp_map, i, j) > 0.0 ) // set the weight to one gsl_matrix_set(weight, i,j,1.0); // return the resulting weight map return weight; } /* * Function: comp_exp_weight * The function uses the exposure time map and computes * the weights which are proportional to the relative * exposure time of the pixel. Pixels outside of the extraction * area are set to 1000.0 Inside the default is 1.0 in unexposed * columns and 0.0 within exposed columns. * * Parameters: * @param exp_map - the matrix with the exposure times * @param ob - the object structure * * Returns: * @return weight - the matrix with the exposure time weights */ gsl_matrix * comp_exp_weight(gsl_matrix *exp_map, const object *ob) { gsl_matrix *weight; int i, j; double sum, contr, norm, allweight; int beamInt = 0; // allocate the matrix and set it to the default weight = gsl_matrix_alloc(exp_map->size1, exp_map->size2); gsl_matrix_set_all(weight, 1000.0); //* go over all columns for (i=0; i < (int)exp_map->size1; i++) { sum = 0.0; contr = 0.0; allweight = 0.0; // determine for each column the total exposure time // and the number of pixels with non-zero exposure time for (j=0; j < (int)exp_map->size2; j++) { // check whether the pixel is inside the extraction // area and has a positive weight if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5 && gsl_matrix_get(exp_map, i, j) > 0.0 ) { // sum up the weigth and the number of pixels sum = sum + gsl_matrix_get(exp_map, i, j); contr = contr + 1.0; } } // check whether the row has exposure time at all if (sum > 0.0) { // if the row is exposed: // determine the mean exposure time norm = sum / contr; // go over each pixel for (j=0; j < (int)exp_map->size2; j++) { // check whether the pixel is inside the extraction are if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5) { // compute and store the relative exposure time (==weight) // for positive exposure time if (gsl_matrix_get(exp_map, i, j) > 0.0) { gsl_matrix_set(weight, i,j,gsl_matrix_get(exp_map, i, j)/norm); allweight = allweight + gsl_matrix_get(weight, i, j); } // make a default to avoid values <0.0 else { gsl_matrix_set(weight, i,j,0.0); } } } } // treat unexposed columns differently: else { // go over each row for (j=0; j < (int)exp_map->size2; j++) { // check whether the pixel is inside the extraction are if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5) { // set inside pixels to the defaulkt 1.0 gsl_matrix_set(weight, i,j,1.0); allweight = allweight + gsl_matrix_get(weight, i, j); } } } } // return the resulting weight map return weight; } /* * Function: comp_opt_weight * The function uses the model map and and the variance * map and computes optimale weigths according to the * Hoorne method. * Pixels outside of the extraction * area are set to 1000.0 * * Parameters: * @param mod_map - the matrix with the model values * @param var_map - the matrix with the variance values * @param ob - the object structure * * Returns: * @return weight - the matrix with the exposure time weights */ gsl_matrix * comp_opt_weight(gsl_matrix *mod_map, gsl_matrix *var_map, const object *ob) { gsl_matrix *weight; int i, j; double mod_sum, weight_sum, contr, norm, allweight; int beamInt = 0; double mod_val; //double var_val; // allocate the weight matrix and set the default weight = gsl_matrix_alloc(mod_map->size1, mod_map->size2); gsl_matrix_set_all(weight, 0.0); //* go over all columns for (i=0; i < (int)mod_map->size1; i++) { mod_sum = 0.0; contr = 0.0; allweight = 0.0; weight_sum=0.0; // determine for each column the total model counts // and the number of pixels with non-zero model_counts for (j=0; j < (int)mod_map->size2; j++) { if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5 && gsl_matrix_get(mod_map, i, j) > 0.0 ) { mod_sum = mod_sum + gsl_matrix_get(mod_map, i, j); contr = contr + 1.0; } } // check whether the column has model values. // normalize the model values and compute // optimal weights if yes. if (mod_sum > 0.0) { //* determine the mean model value // norm = mod_sum / contr; norm = mod_sum; // go over each row for (j=0; j < (int)mod_map->size2; j++) { // check whether the pixel is inside the extraction area if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5 && gsl_matrix_get(mod_map, i, j) > 0.0 ) { // normalize the model counts mod_val = gsl_matrix_get(mod_map, i, j)/norm; // store the normalized model counts gsl_matrix_set(mod_map, i, j, mod_val); // add up the normalization value for the optimal weights weight_sum = weight_sum + mod_val*mod_val/gsl_matrix_get(var_map, i, j); } } // finally compute and write the weights: // go over each pixel for (j=0; j < (int)mod_map->size2; j++) { // check whether the pixel is inside the extraction area if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5) { if (gsl_matrix_get(mod_map, i, j) > 0.0 ) { // compute and set the individual pixel weight gsl_matrix_set(weight, i, j, gsl_matrix_get(mod_map, i, j)/gsl_matrix_get(var_map, i, j)/weight_sum); allweight = allweight + gsl_matrix_get(weight, i, j); } else { // set the default value if no model value is zero gsl_matrix_set(weight, i, j,0.0); } } } } // if the column does not have model values at all: else { // go over each row for (j=0; j < (int)mod_map->size2; j++) { // check whether the pixel is within the extraction area if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5) { // set the inside default value gsl_matrix_set(weight, i,j,1.0); allweight = allweight + gsl_matrix_get(mod_map, i, j); } } } } // return the weight matrix return weight; }
{ "alphanum_fraction": 0.5775385076, "avg_line_length": 30.6743119266, "ext": "c", "hexsha": "63ee97c3d846a2ade893e749c03b008950b32e35", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/drz2pet_utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/drz2pet_utils.c", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/drz2pet_utils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3637, "size": 13374 }
/// based on https://mklimenko.github.io/english/2018/06/04/constexpr-random/ #pragma once #include <atomic> #include <cstdint> #include <gsl/gsl> #include <limits> #include <random> #include "HyperionUtils/Concepts.h" namespace hyperion::math { using gsl::narrow_cast; #ifndef _MSC_VER using std::size_t; #endif //_MSC_VER // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_DATETIME_START \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wdate-time\"") #else // NOLINTNEXTLINE #define IGNORE_DATETIME_START #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_DATETIME_STOP \ _Pragma("GCC diagnostic pop") #else // NOLINTNEXTLINE #define IGNORE_DATETIME_STOP #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_WEAK_VTABLES_START \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wweak-vtables\"") #else // NOLINTNEXTLINE #define IGNORE_WEAK_VTABLES_START #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_WEAK_VTABLES_STOP \ _Pragma("GCC diagnostic pop") #else // NOLINTNEXTLINE #define IGNORE_WEAK_VTABLES_STOP #endif // clang-format on IGNORE_WEAK_VTABLES_START class Engine { public: constexpr Engine() noexcept = default; constexpr Engine(const Engine& engine) noexcept = default; constexpr Engine(Engine&& engine) noexcept = default; virtual constexpr ~Engine() noexcept = default; [[nodiscard]] virtual constexpr auto get_seed() const noexcept -> size_t = 0; virtual constexpr auto seed(size_t seed) noexcept -> void = 0; virtual constexpr auto generate() noexcept -> size_t = 0; template<size_t size> inline constexpr auto generate_array() noexcept -> std::array<size_t, size> { auto array = std::array<size_t, size>(); for(auto& element : array) { element = generate(); } } [[nodiscard]] virtual constexpr auto max_value() const noexcept -> size_t = 0; constexpr auto operator=(const Engine& engine) noexcept -> Engine& = default; constexpr auto operator=(Engine&& engine) noexcept -> Engine& = default; virtual constexpr auto operator()() noexcept -> size_t = 0; }; IGNORE_WEAK_VTABLES_STOP template<size_t max = 714025> class LinearCongruentialEngine final : public Engine { public: constexpr LinearCongruentialEngine() noexcept = default; constexpr LinearCongruentialEngine( const LinearCongruentialEngine& engine) noexcept = default; constexpr LinearCongruentialEngine(LinearCongruentialEngine&& engine) noexcept = default; constexpr ~LinearCongruentialEngine() noexcept final = default; IGNORE_DATETIME_START [[nodiscard]] inline constexpr auto get_seed() const noexcept -> size_t final { const auto* t = __TIME__; return time_from_string(t, 0) * 60 * 60 + time_from_string(t, 3) * 60 + time_from_string(t, 6); } IGNORE_DATETIME_STOP inline constexpr auto seed(size_t seed) noexcept -> void final { m_previous = seed; } [[nodiscard]] inline constexpr auto generate() noexcept -> size_t final { m_previous = (m_a * m_previous + m_c) % max; return m_previous; } [[nodiscard]] inline constexpr auto max_value() const noexcept -> size_t final { return max; } constexpr auto operator=(const LinearCongruentialEngine& engine) noexcept -> LinearCongruentialEngine& = default; constexpr auto operator=(LinearCongruentialEngine&& engine) noexcept -> LinearCongruentialEngine& = default; inline constexpr auto operator()() noexcept -> size_t final { return generate(); } private: size_t m_a = 4096; size_t m_c = 150889; size_t m_previous = get_seed(); [[nodiscard]] static inline constexpr auto time_from_string(const char* string, int offset) noexcept -> size_t { return narrow_cast<size_t>(string[offset] - '0') * 10 // NOLINT + narrow_cast<size_t>(string[offset + 1] - '0'); // NOLINT } }; IGNORE_WEAK_VTABLES_START template<typename EngineType, utils::concepts::Numeric T = int> requires utils::concepts::Derived<EngineType, Engine> class Distribution { public: constexpr Distribution() noexcept = default; constexpr Distribution(const Distribution& distribution) noexcept = default; constexpr Distribution(Distribution&& distribution) noexcept = default; virtual constexpr ~Distribution() noexcept = default; virtual constexpr auto normalized_random_value() noexcept -> double = 0; virtual constexpr auto random_value() noexcept -> T = 0; template<size_t size> inline constexpr auto normalized_random_values() noexcept -> std::array<double, size> { auto array = std::array<double, size>(); for(auto& element : array) { element = normalized_random_value(); } return array; } template<size_t size> inline constexpr auto random_values() noexcept -> std::array<T, size> { auto array = std::array<T, size>(); for(auto& element : array) { element = random_value(); } return array; } virtual constexpr auto seed(size_t seed) noexcept -> void = 0; [[nodiscard]] virtual constexpr auto get_seed() noexcept -> size_t = 0; [[nodiscard]] virtual constexpr auto get_min() const noexcept -> T = 0; virtual constexpr auto set_min(T min) noexcept -> void = 0; [[nodiscard]] virtual constexpr auto get_max() const noexcept -> T = 0; virtual constexpr auto set_max(T max) noexcept -> void = 0; constexpr auto operator=(const Distribution& distribution) noexcept -> Distribution& = default; constexpr auto operator=(Distribution&& distribution) noexcept -> Distribution& = default; virtual constexpr auto operator()() noexcept -> T = 0; }; IGNORE_WEAK_VTABLES_STOP template<typename EngineType, utils::concepts::Numeric T = int> requires utils::concepts::Derived<EngineType, Engine> class UniformDistribution final : public Distribution<EngineType, T> { public: constexpr UniformDistribution() noexcept requires utils::concepts::DefaultConstructible<EngineType> : m_engine(std::make_unique<EngineType>()) { m_engine->seed(m_engine->get_seed()); } constexpr UniformDistribution(T min, T max) noexcept requires utils::concepts::DefaultConstructible<EngineType> : m_min(min), m_max(max), m_engine(std::make_unique<EngineType>()) { m_engine->seed(m_engine->get_seed()); } constexpr UniformDistribution(T min, T max, std::unique_ptr<EngineType>&& engine) noexcept : m_min(min), m_max(max), m_engine(engine) { m_engine->seed(m_engine->get_seed()); } explicit constexpr UniformDistribution(std::unique_ptr<EngineType>&& engine) noexcept : m_engine(std::move(engine)) { m_engine->seed(m_engine->get_seed()); } template<typename... Args> requires utils::concepts::Derived<EngineType, Engine> && utils::concepts:: ConstructibleFrom<EngineType, Args...> explicit constexpr UniformDistribution(Args&&... args) noexcept : m_engine(std::make_unique<EngineType>(args...)) { m_engine->seed(m_engine->get_seed()); } template<typename... Args> requires utils::concepts::Derived<EngineType, Engine> && utils::concepts:: ConstructibleFrom<EngineType, Args...> explicit constexpr UniformDistribution(T min, T max, Args&&... args) noexcept : m_min(min), m_max(max), m_engine(std::make_unique<EngineType>(args...)) { m_engine->seed(m_engine->get_seed()); } constexpr UniformDistribution(const UniformDistribution& distribution) noexcept = default; constexpr UniformDistribution(UniformDistribution&& distribution) noexcept = default; constexpr ~UniformDistribution() noexcept final = default; inline constexpr auto normalized_random_value() noexcept -> double final { return narrow_cast<double>(m_engine->generate()) / narrow_cast<double>(m_engine->max_value()); } inline constexpr auto random_value() noexcept -> T final { return narrow_cast<T>(this->normalized_random_value()) * (m_max - m_min) + m_min; } inline constexpr auto seed(size_t seed) noexcept -> void final { m_engine->seed(seed); } [[nodiscard]] inline constexpr auto get_seed() noexcept -> size_t final { return m_engine->get_seed(); } inline constexpr auto set_min(T min) noexcept -> void final { m_min = min; } [[nodiscard]] inline constexpr auto get_min() const noexcept -> T final { return m_min; } inline constexpr auto set_max(T max) noexcept -> void final { m_max = max; } [[nodiscard]] inline constexpr auto get_max() const noexcept -> T final { return m_max; } constexpr auto operator=(const UniformDistribution& distribution) noexcept -> UniformDistribution& = default; constexpr auto operator=(UniformDistribution&& distribution) noexcept -> UniformDistribution& = default; inline constexpr auto operator()() noexcept -> T final { return random_value(); } private: T m_min = narrow_cast<T>(0); T m_max = narrow_cast<T>(1); std::unique_ptr<EngineType> m_engine; }; template<utils::concepts::Numeric T = float> [[clang::no_destroy]] static math::UniformDistribution<math::LinearCongruentialEngine<>, T> GLOBAL_UNIFORM_DISTRIBUTION; template<utils::concepts::Numeric T = float> static std::atomic_bool GLOBAL_UNIFORM_DISTRIBUTION_INITIALIZED; template<utils::concepts::Numeric T = float> inline static constexpr auto initialize_global_uniform_distribution() noexcept -> void { bool initialized = false; if(GLOBAL_UNIFORM_DISTRIBUTION_INITIALIZED<T>.compare_exchange_strong( initialized, true, std::memory_order_seq_cst)) { GLOBAL_UNIFORM_DISTRIBUTION< T> = math::UniformDistribution<math::LinearCongruentialEngine<>, T>(); } } template<utils::concepts::FloatingPoint T = float> inline auto random_value() noexcept -> T { initialize_global_uniform_distribution<T>(); GLOBAL_UNIFORM_DISTRIBUTION<T>.set_min(narrow_cast<T>(0)); GLOBAL_UNIFORM_DISTRIBUTION<T>.set_max(narrow_cast<T>(1)); return GLOBAL_UNIFORM_DISTRIBUTION<T>(); } template<utils::concepts::Numeric T = float> inline auto random_value(T min, T max) noexcept -> T { initialize_global_uniform_distribution<T>(); GLOBAL_UNIFORM_DISTRIBUTION<T>.set_min(min); GLOBAL_UNIFORM_DISTRIBUTION<T>.set_max(max); return GLOBAL_UNIFORM_DISTRIBUTION<T>(); } } // namespace hyperion::math
{ "alphanum_fraction": 0.7282229965, "avg_line_length": 32.6962025316, "ext": "h", "hexsha": "840d8e553fe4f6c20abd26a21a7b3122276ba3f3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "braxtons12/Hyperion-Math", "max_forks_repo_path": "include/HyperionMath/Random.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "braxtons12/Hyperion-Math", "max_issues_repo_path": "include/HyperionMath/Random.h", "max_line_length": 92, "max_stars_count": null, "max_stars_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "braxtons12/Hyperion-Math", "max_stars_repo_path": "include/HyperionMath/Random.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2581, "size": 10332 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * 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. * * 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. * */ /* funcs.h */ #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv2.h> #define WS_SZ 1000 /* size of the integration workspace */ #define POW_2 gsl_pow_2 /* square */ #define VECTOR gsl_vector_get /* vector_get */ struct f_params { double omega_c ; double beta ; double Omega ; double omega_1; double alpha; } ; int assign_p ( void*, double*, double*, double*, double* ) ; struct ent_pars { const gsl_vector* rhoeq ; gsl_matrix* red_m ; } ; /* Re_gsc functions */ double k_func ( double, void* ) ; double k_func_1 ( double , void* ) ; double k_func_2 ( double , void* ) ; double k_func_3 ( double , void* ) ; double k_func_4 ( double , void* ) ; int first_int ( double*, double*, void* ) ; int second_int ( double* , double* , void* ) ; int third_int ( double* , double* , void* ) ; int fourth_int ( double* , double* , void* ) ; int re_gsc ( double* result, double* error, void* params ) ; int re_gcs ( double* result, double* error, void* params ) ; int re_gcc ( void* params, double* val ) ; int im_gcc ( void* params, double* val, double* error ) ; int re_gss ( void* params, double* val ) ; int im_gss ( void* params, double* val, double* error ) ; int im_gcs ( void* params, double* val ) ; int im_gsc ( void* params, double* val ) ; int re_gc0 ( void* params, double* val ) ; int im_gc0 ( void* params, double* val, double* error ) ; int re_gs0 ( void* params, double* val, double* error ) ; int im_gs0 ( void* params, double* val ) ; /* Img_c0, Img_cc, Img_ss, Img_cs functions */ int expi ( double , double*, double* ) ; int expi_plus ( double, double*, double* ) ; double fu ( double, void* ) ; double ex ( double, void* ) ; /* Reg_s0 functions */ double fu_inv ( double, void* ) ; double fu_cau ( double, void* ) ; double fu_coth ( double, void* ) ; /* Functions to create matrices */ int red_mat ( gsl_matrix* , void* ) ; int cp_mat ( gsl_matrix*, void* ) ; int ham_gen ( gsl_matrix*, const double* ) ; int mat_write ( gsl_matrix*, char* ) ; int mat_read ( gsl_matrix*, char* ) ; int integration ( void*, double* ) ; /* Functions for evolution */ int generator ( double, const double*, double*, void* ) ; int jac ( double, const double*, double*, double*, void* ) ; int evol ( double, gsl_vector*, double, gsl_odeiv2_evolve*, gsl_odeiv2_control*, gsl_odeiv2_step*, gsl_odeiv2_system* ) ; int red_evol ( void*, const double*, double, double, const gsl_vector*, gsl_matrix* ) ; int cp_evol ( void*, const double*, double, double, const gsl_vector*, gsl_matrix* ) ; /* Stationarity */ int stationary ( const gsl_matrix* , gsl_vector* ) ; double J ( double, double ) ; double polarization ( void*, double ) ; /* Entropy */ double entropy_of_state ( const gsl_vector* ) ; double entropy_production ( const gsl_vector*, const gsl_vector*, const gsl_matrix* ) ; double entropy_prod_time ( double, void* ) ; double entropy_integ ( double, const gsl_vector*, gsl_matrix* ) ; /* DC current */ double current ( const gsl_vector* ) ; double current_temp ( double ) ; /* total current */ double tot_current ( const gsl_vector*, void* ) ; /* writing operations */ int save_integrals ( void* ) ; int save_matrices ( void* ) ; int write_red_curr_T ( void* ) ; int write_cp_curr_T ( void* ) ; int write_red_curr_O ( void* ) ; int write_cp_curr_O ( void* ) ; /* currents */ double current_red_om ( double, void* ) ; double current_red_T ( double, void* ) ; double current_cp_om ( double, void* ) ; double current_cp_T ( double, void* ) ; /* positivity */ double r0_dot ( const gsl_matrix* , const gsl_vector* ) ; int bloch_vector ( gsl_vector* , double , double , double ) ; int polars ( double* , double* , double* , const gsl_vector* ) ; int sample ( const gsl_matrix* , unsigned int ) ; /* posit */ gsl_matrix_complex* state_matrix ( double, double ) ; gsl_matrix_complex* rotate ( gsl_matrix_complex*, double ) ; gsl_matrix_complex* D_psi ( gsl_matrix_complex* ) ; /* pos_study */ double delta ( double, double*, double, double, double ) ; int read_integs ( double* ) ; /* entropy production with different parameters */ int ent_prod_fixed_t ( double, double ) ; int ent_prod_red_evol ( void* , const double* , double , double , const gsl_vector* , gsl_matrix* , double ) ; char* dtoascii ( double, int ) ;
{ "alphanum_fraction": 0.7042774159, "avg_line_length": 37.8733333333, "ext": "h", "hexsha": "784f8a4a698939d7eed6df1ba29896ca34cb4c36", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "funcs.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_path": "funcs.h", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "funcs.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1475, "size": 5681 }
#ifndef TOPO_SL_H #define TOPO_SL_H #include <assert.h> #include <vector> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_splinalg.h> #include <apf.h> #include <apfMDS.h> #include <apfMesh.h> #include <apfMesh2.h> #include <apfNumbering.h> #include <apfShape.h> #include "topo_disp.h" // Container for the gsl based linear solver: class solv_kuprat { private: solv_kuprat(const solv_kuprat &obj); solv_kuprat& operator=( const solv_kuprat& obj ); public: apf::Mesh2* m; field_calc* f_calc; int n; std::map<apf::MeshEntity*, int> v2id; std::map<apf::MeshEntity*, bool> v_map; std::map<int, apf::MeshEntity*> id2v; std::vector<apf::MeshEntity*>* verts; gsl_spmatrix* A; gsl_spmatrix* C; gsl_vector *f; gsl_vector *u; apf::GlobalNumbering* gn; // Functions: void numb_vert(); void numb_verts_in(); void dest_numb(); void add_forces(apf::MeshEntity* tri); void collect_matrix_verts(); void collect_matrix(); void init(apf::Mesh2* m_in); void init_verts(apf::Mesh2* m_in); void clear(); double solve(const double tol); solv_kuprat(apf::Mesh2* m, field_calc* f_calc_in); solv_kuprat(apf::Mesh2* m, field_calc* f_calc_in, std::vector<apf::MeshEntity*>* verts); ~solv_kuprat(); friend std::ostream& operator<<(std::ostream& s, const solv_kuprat& sl); }; // Container for the gsl based linear solver: class solv_kuprat_NBC { private: solv_kuprat_NBC(const solv_kuprat_NBC &obj); solv_kuprat_NBC& operator=( const solv_kuprat_NBC& obj ); public: apf::Mesh2* m; field_calc* f_calc; int n; std::map<apf::MeshEntity*, int> v2id; std::map<apf::MeshEntity*, bool> v_map; std::map<int, apf::MeshEntity*> id2v; std::map<apf::MeshEntity*, bool> v_sp; std::vector<apf::MeshEntity*>* verts; gsl_spmatrix* A; gsl_spmatrix* C; gsl_vector *f; gsl_vector *u; apf::GlobalNumbering* gn; // Functions: void numb_vert(); void numb_verts_in(); void dest_numb(); void add_forces(apf::MeshEntity* tri); void collect_matrix_verts(); void collect_matrix(); void process_ext_shell(); void process_ext_shell_verts(); void init(apf::Mesh2* m_in); void init_verts(apf::Mesh2* m_in); void clear(); double solve(const double tol); solv_kuprat_NBC(apf::Mesh2* m, field_calc* f_calc_in); solv_kuprat_NBC(apf::Mesh2* m, field_calc* f_calc_in, std::vector<apf::MeshEntity*>* verts); ~solv_kuprat_NBC(); friend std::ostream& operator<<(std::ostream& s, const solv_kuprat_NBC& sl); }; #endif
{ "alphanum_fraction": 0.6670321637, "avg_line_length": 22.6115702479, "ext": "h", "hexsha": "1e3de8db16e1477610415da8c74352da799979dd", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "23091adbea4ba26379eaf941be53d925304a0560", "max_forks_repo_licenses": [ "Apache-2.0", "MIT" ], "max_forks_repo_name": "erdemeren/VDlib", "max_forks_repo_path": "src/topo_solvlin.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "23091adbea4ba26379eaf941be53d925304a0560", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0", "MIT" ], "max_issues_repo_name": "erdemeren/VDlib", "max_issues_repo_path": "src/topo_solvlin.h", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "23091adbea4ba26379eaf941be53d925304a0560", "max_stars_repo_licenses": [ "Apache-2.0", "MIT" ], "max_stars_repo_name": "erdemeren/VDlib", "max_stars_repo_path": "src/topo_solvlin.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 860, "size": 2736 }
/* ---------------------------------------------------------------------------- JAM_AXI_RMS_WMMT Calculates weighted second moment. INPUTS xp : projected x' [pc] yp : projected y' [pc] nxy : number of x' and y' values given incl : inclination [radians] lum : projected luminous MGE pot : projected potential MGE beta : velocity anisotropy (1 - vz^2 / vr^2) vv : velocity integral selector (1=xx, 2=yy, 3=zz, 4=xy, 5=xz, 6=yz) NOTES * Based on janis2_weighted_second_moment_squared IDL code by Michele Cappellari. Mark den Brok Laura L Watkins [lauralwatkins@gmail.com] This code is released under a BSD 2-clause license. If you use this code for your research, please cite: Watkins et al. 2013, MNRAS, 436, 2598 "Discrete dynamical models of omega Centauri" http://adsabs.harvard.edu/abs/2013MNRAS.436.2598W ---------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include "jam.h" #include "../mge/mge.h" #include "../tools/tools.h" double *jam_axi_rms_wmmt( double *xp, double *yp, int nxy, double incl, \ struct multigaussexp *lum, struct multigaussexp *pot, \ double *beta, int vv , int *gslFlag_rms) { struct params_rmsint p; struct multigaussexp ilum, ipot; double ci, si, *kani, *s2l, *q2l, *s2q2l, *s2p, *e2p; double result, error, *sb_mu2; int i; int status = 0; // convert from projected MGEs to intrinsic MGEs ilum = mge_deproject( lum, incl ); ipot = mge_deproject( pot, incl ); // angles ci = cos( incl ); si = sin( incl ); // mge component combinations kani = (double *) malloc ( lum->ntotal * sizeof( double ) ); s2l = (double *) malloc( lum->ntotal * sizeof( double ) ); q2l = (double *) malloc( lum->ntotal * sizeof( double ) ); s2q2l = (double *) malloc( lum->ntotal * sizeof( double ) ); s2p = (double *) malloc( pot->ntotal * sizeof( double ) ); e2p = (double *) malloc( pot->ntotal * sizeof( double ) ); for ( i = 0; i < ilum.ntotal; i++ ) { kani[i] = 1. / ( 1. - beta[i] ); s2l[i] = pow( ilum.sigma[i], 2. ); q2l[i] = pow( ilum.q[i], 2. ); s2q2l[i] = s2l[i] * q2l[i]; } for ( i = 0; i < ipot.ntotal; i++ ) { s2p[i] = pow( ipot.sigma[i], 2. ); e2p[i] = 1. - pow( ipot.q[i], 2. ); } // parameters for the integrand function p.ci2 = ci * ci; p.si2 = si * si; p.cisi = ci * si; p.lum = &ilum; p.pot = &ipot; p.kani = kani; p.s2l = s2l; p.q2l = q2l; p.s2q2l = s2q2l; p.s2p = s2p; p.e2p = e2p; p.vv = vv; // perform integration gsl_integration_workspace *w = gsl_integration_workspace_alloc( 1000 ); gsl_function F; gsl_set_error_handler_off(); F.function = &jam_axi_rms_mgeint; sb_mu2 = (double *) malloc( nxy * sizeof( double ) ); for ( i = 0; i < nxy; i++ ) { p.x2 = xp[i] * xp[i]; p.y2 = yp[i] * yp[i]; p.xy = xp[i] * yp[i]; F.params = &p; status += gsl_integration_qag( &F, 0., 1., 0., 1e-5, 1000, 6, w, \ &result, &error ); sb_mu2[i] = result; } /*// if you want to test the gsl flagging thing uncomment these two lines int test = 1; status += test; */ if (status > 0) { *gslFlag_rms += 1; } gsl_integration_workspace_free( w ); free( kani ); free( s2l ); free( q2l ); free( s2q2l ); free( s2p ); free( e2p ); return sb_mu2; }
{ "alphanum_fraction": 0.5322151225, "avg_line_length": 28.2406015038, "ext": "c", "hexsha": "8fea4889c156aec82be9ecde0ffa2167a211c8b1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "tadejaversic/cjam", "max_forks_repo_path": "src/jam/jam_axi_rms_wmmt.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "tadejaversic/cjam", "max_issues_repo_path": "src/jam/jam_axi_rms_wmmt.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "tadejaversic/cjam", "max_stars_repo_path": "src/jam/jam_axi_rms_wmmt.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1244, "size": 3756 }
#ifndef MODULE_WASM_TABLE_H #define MODULE_WASM_TABLE_H #include "function/TableFunction.h" #include <gsl/span> namespace wasm { struct WasmTable { using wasm_external_kind_type = parse::Table; using any_function_type = std::optional< gsl::span<any_function_type> get_segment(std::size_t offset, std::size_t length) { assert(offset <= table_.size()); assert((table_.size() - offset) >= lenfth); return gsl::span<TableFunction>(table_.data() + offset, length); } friend bool matches(const WasmTable& self, const parse::Table& tp) { return self.table_.size() >= tp.size() and ( self.maximum_ == tp.maximum.value_or(std::numeric_limits<std::size_t>::max()) ); } const any_function_type& at(wasm_uint32_t idx) const { return table_.at(idx); } any_function_type& at(wasm_uint32_t idx) { return table_.at(idx); } private: std::vector<table_function_type> table_; const std::size_t maximum_ = std::numeric_limits<std::size_t>::max(); }; } /* namespace wasm */ #endif /* MODULE_WASM_TABLE_H */
{ "alphanum_fraction": 0.71692607, "avg_line_length": 24.4761904762, "ext": "h", "hexsha": "76a30b50566578c0361d7ee21d9ed1edb9810bfc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_path": "include/module/WasmTable.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tvanslyke/wasm-cpp", "max_issues_repo_path": "include/module/WasmTable.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_path": "include/module/WasmTable.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 272, "size": 1028 }
/** * @file objective_measure.h * @brief objective measure for speech quality or distance * @author Kenichi Kumatani */ #ifndef OBJECTIVE_MEASURE_H #define OBJECTIVE_MEASURE_H #include <stdio.h> #include <assert.h> #include <float.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_complex.h> #include <common/refcount.h> #include "common/jexception.h" #include "stream/stream.h" #include "feature/feature.h" #include "modulated/modulated.h" // ----- definition for class `SNR' ----- // /** @class calculate the signal-to-ratio (SNR) of two speech data @usage */ class SNR{ public: //SNR(); //SNR( const String& nm = "SNR" ); float getSNR( const String& fn1, const String& fn2, int normalizationOption, int chX=1, int samplerate=16000, int cfrom=-1, int to=-1 ); float getSNR2( gsl_vector_float *original, gsl_vector_float *enhanced, int normalizationOption); }; typedef refcount_ptr<SNR> SNRPtr; class segmentalSNR{ public: }; class ItakuraSaitoMeasurePS { public: ItakuraSaitoMeasurePS( unsigned fftLen, unsigned r = 1, unsigned windowType = 1, const String& nm = "ItakuraSaitoMeasurePS" ):_fftLen(fftLen),_r(r),_windowType(windowType) { _D = _fftLen / (int)pow( (float)2, (int)_r ); } float getDistance( const String& fn1, const String& fn2, int chX=1, int samplerate=16000, int bframe = 0, int eframe = -1 ); //float getDistance( VectorFloatFeatureStreamPtr& original, //VectorFloatFeatureStreamPtr& enhanced ); int frameShiftLength(){ return _D; } private: unsigned _fftLen; unsigned _r; unsigned _windowType; unsigned _D; }; typedef refcount_ptr<ItakuraSaitoMeasurePS> ItakuraSaitoMeasurePSPtr; #endif
{ "alphanum_fraction": 0.7194127243, "avg_line_length": 24.1973684211, "ext": "h", "hexsha": "5521f7b5f463af998411b75cba4c20470b66f417", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/objective_measure/objective_measure.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/objective_measure/objective_measure.h", "max_line_length": 173, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/objective_measure/objective_measure.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 546, "size": 1839 }
#include <pygsl/error_helpers.h> #include <pygsl/utils.h> #include <gsl/gsl_errno.h> #include <compile.h> #include <frameobject.h> enum handleflag { HANDLE_ERROR = 0, HANDLE_WARNING }; static int PyGSL_internal_error_handler(const char *reason, /* name of function*/ const char *file, /*from CPP*/ int line, /*from CPP*/ int gsl_error, enum handleflag flag); static int PyGSL_error_flag(long flag) { FUNC_MESS_BEGIN(); if(PyGSL_DEBUG_LEVEL() > 2){ fprintf(stderr,"I got an Error %ld\n", flag); } if(PyErr_Occurred()){ DEBUG_MESS(3, "Already a python error registered for flag %ld", flag); return GSL_FAILURE; } if(flag>0){ /* * How can I end here without an Python error? * * 25. October 2008 * Well, very simply when the GSL_ERROR_HANDLER is set to off. * * All GSL modules are * supposed to call GSL_ERROR which should call the default error * handler. * * 25. October 2008 * No not when the handler is set to off, which is necessary in * a threaded python. That's why it was a bad idea to call the * gsl_error_handler here! */ /* * gsl_error("Unknown Reason. It was not set by GSL.", __FILE__, * __LINE__, flag); */ PyGSL_internal_error_handler("Unknown Reason. It was not set by GSL", __FILE__, __LINE__, flag, HANDLE_ERROR); /* * So lets keep the flag to return ... who knows what it will be used for... * return GSL_FAILURE; */ return flag; } FUNC_MESS_END(); return GSL_SUCCESS; } static PyObject * PyGSL_error_flag_to_pyint(long flag) { PyObject * result = NULL; FUNC_MESS_BEGIN(); if(GSL_FAILURE == PyGSL_error_flag(flag)){ return NULL; } result = PyInt_FromLong((long) flag); FUNC_MESS_END(); return result; } static void PyGSL_add_traceback(PyObject *module, const char *filename, const char *funcname, int lineno) { PyObject *py_srcfile = NULL, *py_funcname = NULL, *py_globals = NULL, *empty_tuple = NULL, *empty_string = NULL; PyCodeObject *py_code = NULL; PyFrameObject *py_frame = NULL; FUNC_MESS_BEGIN(); if(filename == NULL) filename = "file ???"; py_srcfile = PyString_FromString(filename); if (py_srcfile == NULL) goto fail; if(funcname == NULL) funcname = "function ???"; py_funcname = PyString_FromString(funcname); if (py_funcname == NULL) goto fail; /* Use the module if provided */ if(module == NULL){ py_globals = PyDict_New(); } else { py_globals = PyModule_GetDict(module); } if (py_globals == NULL) goto fail; empty_tuple = PyTuple_New(0); if (empty_tuple == NULL) goto fail; empty_string = PyString_FromString(""); if (empty_string == NULL) goto fail; py_code = PyCode_New( 0, /*int argcount,*/ 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ empty_string, /*PyObject *code,*/ empty_tuple, /*PyObject *consts,*/ empty_tuple, /*PyObject *names,*/ empty_tuple, /*PyObject *varnames,*/ empty_tuple, /*PyObject *freevars,*/ empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ lineno, /*int firstlineno,*/ empty_string /*PyObject *lnotab*/ ); if (py_code == NULL) goto fail; py_frame = PyFrame_New( PyThreadState_Get(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (py_frame == NULL) goto fail; py_frame->f_lineno = lineno; PyTraceBack_Here(py_frame); FUNC_MESS_END(); return; fail: FUNC_MESS("Handling failure"); Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(empty_tuple); Py_XDECREF(empty_string); Py_XDECREF(py_code); Py_XDECREF(py_frame); } #define PyGSL_ERRNO_MAX 32 static PyObject * errno_accel[PyGSL_ERRNO_MAX]; static PyObject * error_dict = NULL; static PyObject * warning_dict = NULL; static PyObject * unknown_error = NULL; static void PyGSL_print_accel_object(void) { int i; FUNC_MESS_BEGIN(); for(i = 0; i<PyGSL_ERRNO_MAX; ++i){ DEBUG_MESS(4, "errno_accel[%d] = %p", i, (void*)(errno_accel[i])); } FUNC_MESS_END(); } static int PyGSL_register_accel_err_object(PyObject * err_ob, long test_errno) { PyObject *tmp; FUNC_MESS_BEGIN(); assert(err_ob); tmp = errno_accel[test_errno]; if(tmp != NULL){ PyErr_Format(PyExc_ValueError, "In errno_accel: errno %ld already occupied with object %p!\n", test_errno, (void *) tmp); return -2; } Py_INCREF(err_ob); errno_accel[test_errno] = err_ob; FUNC_MESS_END(); return 0; } /* register an error object to the Python dictionary */ static int _PyGSL_register_err_object(PyObject *dict, PyObject * err_ob, PyObject *the_errno) { PyObject *test; FUNC_MESS_BEGIN(); assert(error_dict); test = PyDict_GetItem(dict, the_errno); if(test != NULL){ PyErr_Format(PyExc_ValueError, "In dict %p: key %p already occupied with object %p!\n", dict, the_errno, (void *) test); return -2; } Py_INCREF(err_ob); PyDict_SetItem(dict, the_errno, err_ob); FUNC_MESS_END(); return 0; } /* register an error object */ static int _PyGSL_register_error(PyObject *dict, int errno_max, PyObject * err_ob) { PyObject *tmp, *name; long test_errno; int flag; char * c_name; FUNC_MESS_BEGIN(); assert(err_ob); tmp = PyObject_GetAttrString(err_ob, "errno"); if(tmp == NULL){ name = PyObject_GetAttrString(err_ob, "__name__"); if(name == NULL) c_name = "unknown name"; else if (!PyString_Check(name)) c_name = "name not str object!"; else c_name = PyString_AsString (name); fprintf(stderr, "failed to get errno from err_ob '%s' @ %p\n", c_name, (void *) err_ob); PyErr_Format(PyExc_AttributeError, "err_ob '%s' @ %p missed attribue 'errno!'\n", c_name, err_ob); return -1; } if(!PyInt_CheckExact(tmp)){ fprintf(stderr, "errno %p from err_ob %p was not an exact int!\n", (void *) tmp, (void *) err_ob); PyErr_Format(PyExc_TypeError, "errno %p from err_ob %p was not an exact int!\n", (void *) tmp, (void *) err_ob); return -1; } test_errno = PyInt_AsLong(tmp); if((dict == error_dict) && (test_errno < PyGSL_ERRNO_MAX)){ flag = PyGSL_register_accel_err_object(err_ob, test_errno); }else{ flag = _PyGSL_register_err_object(dict, err_ob, tmp); } if(flag != 0) fprintf(stderr, "Failed to register err_ob %p with errno %ld.\n" "\tAlready registered?\n", err_ob, test_errno); FUNC_MESS_END(); return flag; } static PyObject* PyGSL_register_error_objs(PyObject *self, PyObject *args, PyObject *dict, int errno_max) { int flag, i, len; PyObject *tmp; FUNC_MESS_BEGIN(); if(!PySequence_Check(args)) return NULL; len = PySequence_Size(args); DEBUG_MESS(5, "Recieved %d error objects", len); for(i = 0; i < len; ++i){ tmp = PySequence_GetItem(args, i); flag = _PyGSL_register_error(dict, errno_max, tmp); if(flag != 0){ fprintf(stderr, "Failed to register error object %d\n", i); return NULL; } } PyGSL_print_accel_object(); Py_INCREF(Py_None); FUNC_MESS_END(); return Py_None; } static PyObject* PyGSL_register_warnings(PyObject *self, PyObject *args) { PyObject *tmp; FUNC_MESS_BEGIN(); tmp = PyGSL_register_error_objs(self, args, warning_dict, 0); FUNC_MESS_END(); return tmp; } static PyObject* PyGSL_register_exceptions(PyObject *self, PyObject *args) { PyObject *tmp; FUNC_MESS_BEGIN(); tmp = PyGSL_register_error_objs(self, args, error_dict, PyGSL_ERRNO_MAX); FUNC_MESS_END(); return tmp; } static PyObject * PyGSL_get_error_object(int the_errno, PyObject ** accel, int accel_max, PyObject *dict) { PyObject *tmp; FUNC_MESS_BEGIN(); assert(the_errno >= 0); if (the_errno < accel_max){ DEBUG_MESS(4, "Trying to get an error object from accel array at %p", (void*) accel); tmp = accel[the_errno]; }else{ DEBUG_MESS(4, "Trying to get an error object from dictonary at %p", (void*) dict); tmp = PyDict_GetItem(dict, PyInt_FromLong(the_errno)); } if(tmp == NULL){ DEBUG_MESS(3, "Could not find an error object for errno %d", the_errno); PyGSL_print_accel_object(); return unknown_error; } FUNC_MESS_END(); return tmp; } static int PyGSL_init_errno(void) { int i; FUNC_MESS_BEGIN(); for(i = 0; i< PyGSL_ERRNO_MAX; ++i){ DEBUG_MESS(3, "setting errno_accel[%d] to NULL; was %p", i, (void*) (errno_accel[i])); errno_accel[i] = NULL; } error_dict = PyDict_New(); if (error_dict == NULL) return -1; warning_dict = PyDict_New(); if (warning_dict == NULL) return -1; unknown_error = PyExc_ValueError; FUNC_MESS_END(); return 0; } /* * Warnings return a flag, so one can see if the warning raises an exception * or not. */ static int PyGSL_internal_error_handler(const char *reason, /* name of function*/ const char *file, /*from CPP*/ int line, /*from CPP*/ int gsl_error, enum handleflag flag) { const char* error_explanation; char error_text[255]; PyObject* gsl_error_object; FUNC_MESS_BEGIN(); /* * GSL_ENOMEM is special. I am out of memory. No fancy tricks here. */ if (GSL_ENOMEM == gsl_error){ PyErr_NoMemory(); return -1; } /* * some functions call error handler more than once before returning * report only the first (most specific) error */ if (line < 0) line = 0; /* test, if exception is already set */ DEBUG_MESS(5, "Checking if python error occured, gsl error %d, line %d", gsl_error, line); if (PyErr_Occurred()) { if(PyGSL_DEBUG_LEVEL() > 0) fprintf(stderr, "Another error occured: %s\n",error_text); FUNC_MESS("Already set python error found"); return -1; } /* * Find the approbriate error */ error_explanation = gsl_strerror(gsl_error); if (reason==NULL){ reason = "no reason given!"; } if (error_explanation==NULL){ snprintf(error_text,sizeof(error_text), "unknown error %d: %s", gsl_error, reason); }else{ snprintf(error_text,sizeof(error_text), "%s: %s", error_explanation,reason); } switch(flag){ case HANDLE_ERROR: assert(gsl_error > 0); gsl_error_object = PyGSL_get_error_object(gsl_error, errno_accel, PyGSL_ERRNO_MAX, error_dict); Py_INCREF(gsl_error_object); PyErr_SetObject(gsl_error_object, PyString_FromString(error_text)); FUNC_MESS("Set Python error object"); return -1; break; case HANDLE_WARNING: assert(gsl_error > 0); gsl_error_object = PyGSL_get_error_object(gsl_error, NULL, 0, warning_dict); Py_INCREF(gsl_error_object); FUNC_MESS("Returning python warning"); return PyErr_Warn(gsl_error_object, error_text); break; default: fprintf(stderr, "Unknown handle %d\n", flag); } FUNC_MESS("Should not end here!"); return -1; } /* * sets the right exception, but does not return to python! */ static void PyGSL_module_error_handler(const char *reason, /* name of function*/ const char *file, /*from CPP*/ int line, /*from CPP*/ int gsl_error) /* real "reason" */ { FUNC_MESS_BEGIN(); PyGSL_internal_error_handler(reason, file, line, gsl_error, HANDLE_ERROR); FUNC_MESS_END(); } static int PyGSL_warning(const char *reason, /* name of function*/ const char *file, /*from CPP*/ int line, /*from CPP*/ int gsl_error) /* real "reason" */ { int tmp; FUNC_MESS_BEGIN(); tmp = PyGSL_internal_error_handler(reason, file, line, gsl_error, HANDLE_WARNING); FUNC_MESS_END(); return tmp; }
{ "alphanum_fraction": 0.6277049312, "avg_line_length": 26.1705263158, "ext": "c", "hexsha": "973f3902bf6318b86e3ee4e05382314c188fc8b0", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/src/init/error_helpers.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/src/init/error_helpers.c", "max_line_length": 102, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/src/init/error_helpers.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3337, "size": 12431 }