repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
socaljoker/SITableViewForm
SITableViewForm/TextFieldFormFieldCell.h
// // TextFieldFormFieldCell.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "FormFieldTableViewCell.h" #define TextFieldFormFieldIdentifier @"TEXTFIELDFORMFIELD" @interface TextFieldFormFieldCell : FormFieldTableViewCell @property (strong, nonatomic) IBOutlet UILabel *titleLabel; @property (strong, nonatomic) IBOutlet UILabel *subtitleLabel; @property (strong, nonatomic) IBOutlet UITextField *textField; @end
socaljoker/SITableViewForm
SITableViewForm/FormBuilder.h
<reponame>socaljoker/SITableViewForm // // FormBuilder.h // SITableViewForm // // Created by <NAME> on 9/15/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "FormFieldSection.h" #import "FormBuilderElement.h" @interface FormBuilder : NSObject @property (strong, nonatomic, nonnull) NSDictionary<FormFieldSection *, FormBuilderElement *> *formInfo; +(instancetype _Nullable)buildFormWithSectionsAndElements:(NSDictionary<FormFieldSection *, FormBuilderElement *> * _Nonnull)formInfo; @end
socaljoker/SITableViewForm
SITableViewForm/StringValidator.h
// // StringValidator.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Validator.h" @interface StringValidator : Validator @property (nonatomic) int minLength; @property (nonatomic) int maxLength; @property (nonatomic) NSMutableArray<NSString *> *restrictedChars; @end
socaljoker/SITableViewForm
SITableViewForm/Validator.h
<gh_stars>0 // // Validator.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #define NSValidatorErrorDomain @"NSValidatorErrorDomain" typedef enum : NSUInteger { NSValidationErrorBeyondMaxValue, NSValidationErrorBeyondMinValue, NSValidationErrorValueNotEqual, NSValidationErrorContainsRestrictedCharacters, NSValidationErrorInvalidFormat, NSValidationErrorEmptyValue } NSValidationError; @interface Validator : NSObject -(NSError * _Nullable)validate:(id _Nonnull)value; @end
socaljoker/SITableViewForm
SITableViewForm/ArrayValidator.h
// // ArrayValidator.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "Validator.h" @interface ArrayValidator : Validator @property (nonatomic) int minCount; @property (nonatomic) int maxCount; @end
socaljoker/SITableViewForm
SITableViewForm/BooleanFormField.h
<reponame>socaljoker/SITableViewForm // // BooleanFormField.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "FormField.h" @interface BooleanFormField : FormField @property (nonatomic) BOOL currentValue; @property (nonatomic, copy, nullable) void (^updateBlock)(BOOL value); @end
socaljoker/SITableViewForm
SITableViewForm/RegexValidator.h
<filename>SITableViewForm/RegexValidator.h // // RegexValidator.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "Validator.h" typedef enum : NSUInteger { RegexMatchCountTypeEquals, RegexMatchCountTypeLessThan, RegexMatchCountTypeGreaterThan, } RegexMatchCountType; @interface RegexValidator : Validator @property (strong, nonatomic, nonnull) NSRegularExpression *regex; @property (nonatomic) int requiredMatchCount; @property (nonatomic) RegexMatchCountType matchCountType; @end
socaljoker/SITableViewForm
SITableViewForm/NumberFormField.h
<gh_stars>0 // // NumberFormField.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "FormField.h" @interface NumberFormField : FormField @property (strong, nonatomic, nullable) NSNumber *currentValue; @property (strong, nonatomic, nonnull) NSNumberFormatter *formatter; @property (nonatomic, copy, nullable) void (^updateBlock)(NSNumber * _Nullable value); @end
socaljoker/SITableViewForm
SITableViewForm/FormTableViewController.h
<reponame>socaljoker/SITableViewForm // // FormTableViewController.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Form.h" #import "FormField.h" #import "FormFieldTableViewCell.h" #import "StringFormField.h" #import "NumberFormField.h" #import "DateFormField.h" #import "AttributedStringFormField.h" #import "BooleanFormField.h" #import "ObjectSelectionFormField.h" #import "MultipleObjectSelectionFormField.h" @interface FormTableViewController : UITableViewController @property (strong, nonatomic, nonnull) Form *form; @property (nonatomic, copy, nullable) FormFieldTableViewCell *_Nullable (^customCellBlock)(UITableView * _Nonnull tableView, FormField * _Nonnull field, NSIndexPath * _Nonnull indexPath); @property (nonatomic, copy, nullable) void (^customizeCellBlock)(UITableView * _Nonnull tableView, FormFieldTableViewCell * _Nonnull cell, NSIndexPath * _Nonnull indexPath); @end
socaljoker/SITableViewForm
SITableViewForm/DateFormField.h
// // DateFormField.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "FormField.h" @interface DateFormField : FormField @property (strong, nonatomic, nullable) NSDate *currentValue; @property (strong, nonatomic, nonnull) NSDateFormatter *formatter; @property (nonatomic, copy, nullable) void (^updateBlock)(NSDate * _Nullable value); @end
socaljoker/SITableViewForm
SITableViewForm/StringFormField.h
<gh_stars>0 // // StringFormField.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "FormField.h" @interface StringFormField : FormField @property (strong, nonatomic, nullable) NSString *currentValue; @property (nonatomic, copy, nullable) void (^updateBlock)(NSString * _Nullable value); @end
socaljoker/SITableViewForm
SITableViewForm/FormFieldTableViewCell.h
<reponame>socaljoker/SITableViewForm // // FormFieldTableViewCell.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "FormField.h" @interface FormFieldTableViewCell : UITableViewCell @property (strong, nonatomic, nonnull) FormField *field; @end
socaljoker/SITableViewForm
SITableViewForm/ObjectSelectionFormField.h
<reponame>socaljoker/SITableViewForm // // ObjectSelectionFormField.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "FormField.h" @interface ObjectSelectionFormField : FormField @property (strong, nonatomic, nullable) NSObject *currentValue; @property (nonatomic, copy, nullable) void (^updateBlock)(NSObject * _Nullable value); @end
socaljoker/SITableViewForm
SITableViewForm/IntegerValidator.h
<filename>SITableViewForm/IntegerValidator.h // // IntegerValidator.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "Validator.h" @interface IntegerValidator : Validator @property (nonatomic) int maxValue; @property (nonatomic) int minValue; @end
socaljoker/SITableViewForm
SITableViewForm/BlockValidator.h
<filename>SITableViewForm/BlockValidator.h<gh_stars>0 // // BlockValidator.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "Validator.h" #import "FormField.h" @interface BlockValidator : Validator @property (nonatomic, copy, nonnull) NSError* _Nullable (^validationBlock)(id _Nonnull value); @end
socaljoker/SITableViewForm
SITableViewForm/AttributedStringFormField.h
// // AttributedStringFormField.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "FormField.h" @interface AttributedStringFormField : FormField @property (strong, nonatomic, nullable) NSAttributedString *currentValue; @property (nonatomic, copy, nullable) void (^updateBlock)(NSAttributedString * _Nullable value); @end
socaljoker/SITableViewForm
SITableViewForm/FormBuilderElement.h
// // FormBuilderElement.h // SITableViewForm // // Created by <NAME> on 9/15/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "FormField.h" #import "FormFieldTableViewCell.h" typedef void (^CellInfoBlock)(FormFieldTableViewCell * _Nonnull cell); @interface FormBuilderElement : NSObject @property (strong, nonatomic, nonnull) FormFieldTableViewCell *cell; @property (strong, nonatomic, nullable) CellInfoBlock customizationBlock; @property (strong, nonatomic, nullable) CellInfoBlock updateBlock; @property (strong, nonatomic, nullable) CellInfoBlock cellSelectionAction; @property (strong, nonatomic, nullable) CellInfoBlock accessorySelectionAction; +(instancetype _Nonnull)newElementWithFormField:(FormField * _Nonnull)field customizationBlock:(CellInfoBlock _Nullable)customizationBlock updateBlock:(CellInfoBlock _Nullable)updateBlock; +(instancetype _Nonnull)newElementWithFormField:(FormField * _Nonnull)field customCellUI:(FormFieldTableViewCell * _Nonnull)cell customizationBlock:(CellInfoBlock _Nullable)customizationBlock updateBlock:(CellInfoBlock _Nullable)updateBlock; @end
socaljoker/SITableViewForm
SITableViewForm/DecimalValidator.h
<reponame>socaljoker/SITableViewForm // // DecimalValidator.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "Validator.h" @interface DecimalValidator : Validator @property (nonatomic) float minValue; @property (nonatomic) float maxValue; @end
socaljoker/SITableViewForm
SITableViewForm/FormField.h
<filename>SITableViewForm/FormField.h // // FormField.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "Validator.h" @interface FormField : NSObject @property (strong, nonatomic, nullable) NSString *identifier; @property (strong, nonatomic, nullable) NSString *title; @property (strong, nonatomic, nullable) NSString *subtitle; @property (strong, nonatomic, nullable) Validator *validator; -(instancetype _Nonnull)initWithIdentifier:(NSString * _Nullable)identifier title:(NSString * _Nullable)title subtitle:(NSString * _Nullable)subtitle validator:(Validator * _Nullable)validator; @end
socaljoker/SITableViewForm
SITableViewForm/NilValueValidator.h
<reponame>socaljoker/SITableViewForm // // NilValueValidator.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "Validator.h" @interface NilValueValidator : Validator @end
socaljoker/SITableViewForm
SITableViewForm/FormFieldSection.h
// // FormFieldSection.h // SITableViewForm // // Created by <NAME> on 9/14/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface FormFieldSection : NSObject @property (strong, nonatomic, nullable) NSString *headerText; @property (strong, nonatomic, nullable) NSString *footerText; @end
supercj92/tomcat6
native/connector/src/jnilib.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * * @author <NAME> * @version $Revision: 466609 $, $Date: 2006-10-22 01:30:39 +0200 (dim., 22 oct. 2006) $ */ #include "tcn.h" #include "apr_version.h" #include "apr_file_io.h" #include "apr_mmap.h" #include "apr_atomic.h" #include "tcn_version.h" #ifdef TCN_DO_STATISTICS extern void sp_poll_dump_statistics(); extern void sp_network_dump_statistics(); extern void ssl_network_dump_statistics(); #endif apr_pool_t *tcn_global_pool = NULL; static JavaVM *tcn_global_vm = NULL; static jclass jString_class; static jclass jFinfo_class; static jclass jAinfo_class; static jmethodID jString_init; static jmethodID jString_getBytes; int tcn_parent_pid = 0; /* Called by the JVM when APR_JAVA is loaded */ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env; UNREFERENCED(reserved); if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_4)) { return JNI_ERR; } tcn_global_vm = vm; /* Initialize global java.lang.String class */ TCN_LOAD_CLASS(env, jString_class, "java/lang/String", JNI_ERR); TCN_LOAD_CLASS(env, jFinfo_class, TCN_FINFO_CLASS, JNI_ERR); TCN_LOAD_CLASS(env, jAinfo_class, TCN_AINFO_CLASS, JNI_ERR); TCN_GET_METHOD(env, jString_class, jString_init, "<init>", "([B)V", JNI_ERR); TCN_GET_METHOD(env, jString_class, jString_getBytes, "getBytes", "()[B", JNI_ERR); if(tcn_load_finfo_class(env, jFinfo_class) != APR_SUCCESS) return JNI_ERR; if(tcn_load_ainfo_class(env, jAinfo_class) != APR_SUCCESS) return JNI_ERR; #ifdef WIN32 { char *ppid = getenv(TCN_PARENT_IDE); if (ppid) tcn_parent_pid = atoi(ppid); } #else tcn_parent_pid = getppid(); #endif apr_initialize(); return JNI_VERSION_1_4; } /* Called by the JVM before the APR_JAVA is unloaded */ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) { JNIEnv *env; UNREFERENCED(reserved); if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_2)) { return; } TCN_UNLOAD_CLASS(env, jString_class); TCN_UNLOAD_CLASS(env, jFinfo_class); TCN_UNLOAD_CLASS(env, jAinfo_class); apr_terminate(); } jstring tcn_new_stringn(JNIEnv *env, const char *str, size_t l) { jstring result; jbyteArray bytes = 0; size_t len = l; if (!str) return NULL; if ((*env)->EnsureLocalCapacity(env, 2) < 0) { return NULL; /* out of memory error */ } if (l < 0) len = strlen(str); bytes = (*env)->NewByteArray(env, (jsize)len); if (bytes != NULL) { (*env)->SetByteArrayRegion(env, bytes, 0, (jint)len, (jbyte *)str); result = (*env)->NewObject(env, jString_class, jString_init, bytes); (*env)->DeleteLocalRef(env, bytes); return result; } /* else fall through */ return NULL; } jbyteArray tcn_new_arrayb(JNIEnv *env, const unsigned char *data, size_t len) { jbyteArray bytes = (*env)->NewByteArray(env, (jsize)len); if (bytes != NULL) { (*env)->SetByteArrayRegion(env, bytes, 0, (jint)len, (jbyte *)data); } return bytes; } jobjectArray tcn_new_arrays(JNIEnv *env, size_t len) { return (*env)->NewObjectArray(env, (jsize)len, jString_class, NULL); } jstring tcn_new_string(JNIEnv *env, const char *str) { if (!str) return NULL; else return (*env)->NewStringUTF(env, str); } char *tcn_get_string(JNIEnv *env, jstring jstr) { jbyteArray bytes = NULL; jthrowable exc; char *result = NULL; if ((*env)->EnsureLocalCapacity(env, 2) < 0) { return NULL; /* out of memory error */ } bytes = (*env)->CallObjectMethod(env, jstr, jString_getBytes); exc = (*env)->ExceptionOccurred(env); if (!exc) { jint len = (*env)->GetArrayLength(env, bytes); result = (char *)malloc(len + 1); if (result == NULL) { TCN_THROW_OS_ERROR(env); (*env)->DeleteLocalRef(env, bytes); return 0; } (*env)->GetByteArrayRegion(env, bytes, 0, len, (jbyte *)result); result[len] = '\0'; /* NULL-terminate */ } else { (*env)->DeleteLocalRef(env, exc); } (*env)->DeleteLocalRef(env, bytes); return result; } char *tcn_strdup(JNIEnv *env, jstring jstr) { char *result = NULL; const char *cjstr; cjstr = (const char *)((*env)->GetStringUTFChars(env, jstr, 0)); if (cjstr) { result = strdup(cjstr); (*env)->ReleaseStringUTFChars(env, jstr, cjstr); } return result; } char *tcn_pstrdup(JNIEnv *env, jstring jstr, apr_pool_t *pool) { char *result = NULL; const char *cjstr; cjstr = (const char *)((*env)->GetStringUTFChars(env, jstr, 0)); if (cjstr) { result = apr_pstrdup(pool, cjstr); (*env)->ReleaseStringUTFChars(env, jstr, cjstr); } return result; } TCN_IMPLEMENT_CALL(jboolean, Library, initialize)(TCN_STDARGS) { UNREFERENCED_STDARGS; if (!tcn_global_pool) { if (apr_pool_create(&tcn_global_pool, NULL) != APR_SUCCESS) { return JNI_FALSE; } apr_atomic_init(tcn_global_pool); } return JNI_TRUE; } TCN_IMPLEMENT_CALL(void, Library, terminate)(TCN_STDARGS) { UNREFERENCED_STDARGS; if (tcn_global_pool) { #ifdef TCN_DO_STATISTICS fprintf(stderr, "APR Statistical data ....\n"); #endif apr_pool_destroy(tcn_global_pool); tcn_global_pool = NULL; #ifdef TCN_DO_STATISTICS sp_poll_dump_statistics(); sp_network_dump_statistics(); ssl_network_dump_statistics(); fprintf(stderr, "APR Terminated\n"); #endif } } TCN_IMPLEMENT_CALL(jlong, Library, globalPool)(TCN_STDARGS) { UNREFERENCED_STDARGS; return P2J(tcn_global_pool); } TCN_IMPLEMENT_CALL(jint, Library, version)(TCN_STDARGS, jint what) { apr_version_t apv; UNREFERENCED_STDARGS; apr_version(&apv); switch (what) { case 0x01: return TCN_MAJOR_VERSION; break; case 0x02: return TCN_MINOR_VERSION; break; case 0x03: return TCN_PATCH_VERSION; break; case 0x04: #ifdef TCN_IS_DEV_VERSION return 1; #else return 0; #endif break; case 0x11: return apv.major; break; case 0x12: return apv.minor; break; case 0x13: return apv.patch; break; case 0x14: return apv.is_dev; break; } return 0; } TCN_IMPLEMENT_CALL(jstring, Library, versionString)(TCN_STDARGS) { UNREFERENCED(o); return AJP_TO_JSTRING(TCN_VERSION_STRING); } TCN_IMPLEMENT_CALL(jstring, Library, aprVersionString)(TCN_STDARGS) { UNREFERENCED(o); return AJP_TO_JSTRING(apr_version_string()); } TCN_IMPLEMENT_CALL(jboolean, Library, has)(TCN_STDARGS, jint what) { jboolean rv = JNI_FALSE; UNREFERENCED_STDARGS; switch (what) { case 0: #if APR_HAVE_IPV6 rv = JNI_TRUE; #endif break; case 1: #if APR_HAS_SHARED_MEMORY rv = JNI_TRUE; #endif break; case 2: #if APR_HAS_THREADS rv = JNI_TRUE; #endif break; case 3: #if APR_HAS_SENDFILE rv = JNI_TRUE; #endif break; case 4: #if APR_HAS_MMAP rv = JNI_TRUE; #endif break; case 5: #if APR_HAS_FORK rv = JNI_TRUE; #endif break; case 6: #if APR_HAS_RANDOM rv = JNI_TRUE; #endif break; case 7: #if APR_HAS_OTHER_CHILD rv = JNI_TRUE; #endif break; case 8: #if APR_HAS_DSO rv = JNI_TRUE; #endif break; case 9: #if APR_HAS_SO_ACCEPTFILTER rv = JNI_TRUE; #endif break; case 10: #if APR_HAS_UNICODE_FS rv = JNI_TRUE; #endif break; case 11: #if APR_HAS_PROC_INVOKED rv = JNI_TRUE; #endif break; case 12: #if APR_HAS_USER rv = JNI_TRUE; #endif break; case 13: #if APR_HAS_LARGE_FILES rv = JNI_TRUE; #endif break; case 14: #if APR_HAS_XTHREAD_FILES rv = JNI_TRUE; #endif break; case 15: #if APR_HAS_OS_UUID rv = JNI_TRUE; #endif break; case 16: #if APR_IS_BIGENDIAN rv = JNI_TRUE; #endif break; case 17: #if APR_FILES_AS_SOCKETS rv = JNI_TRUE; #endif break; case 18: #if APR_CHARSET_EBCDIC rv = JNI_TRUE; #endif break; case 19: #if APR_TCP_NODELAY_INHERITED rv = JNI_TRUE; #endif break; case 20: #if APR_O_NONBLOCK_INHERITED rv = JNI_TRUE; #endif break; } return rv; } TCN_IMPLEMENT_CALL(jint, Library, size)(TCN_STDARGS, jint what) { UNREFERENCED_STDARGS; switch (what) { case 1: return APR_SIZEOF_VOIDP; break; case 2: return APR_PATH_MAX; break; case 3: return APRMAXHOSTLEN; break; case 4: return APR_MAX_IOVEC_SIZE; break; case 5: return APR_MAX_SECS_TO_LINGER; break; case 6: return APR_MMAP_THRESHOLD; break; case 7: return APR_MMAP_LIMIT; break; } return 0; } TCN_DECLARE(apr_pool_t *) tcn_get_global_pool() { if (!tcn_global_pool) { if (apr_pool_create(&tcn_global_pool, NULL) != APR_SUCCESS) { return NULL; } apr_atomic_init(tcn_global_pool); } return tcn_global_pool; } TCN_DECLARE(jclass) tcn_get_string_class() { return jString_class; } TCN_DECLARE(JavaVM *) tcn_get_java_vm() { return tcn_global_vm; } TCN_DECLARE(jint) tcn_get_java_env(JNIEnv **env) { if ((*tcn_global_vm)->GetEnv(tcn_global_vm, (void **)env, JNI_VERSION_1_4)) { return JNI_ERR; } return JNI_OK; }
supercj92/tomcat6
native/connector/src/ssl.c
<reponame>supercj92/tomcat6 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * * @author <NAME> * @version $Revision: 481766 $, $Date: 2006-12-03 13:40:18 +0100 (dim., 03 déc. 2006) $ */ #include "tcn.h" #include "apr_file_io.h" #include "apr_thread_mutex.h" #include "apr_atomic.h" #include "apr_poll.h" #ifdef HAVE_OPENSSL #include "ssl_private.h" static int ssl_initialized = 0; static char *ssl_global_rand_file = NULL; extern apr_pool_t *tcn_global_pool; ENGINE *tcn_ssl_engine = NULL; void *SSL_temp_keys[SSL_TMP_KEY_MAX]; tcn_pass_cb_t tcn_password_callback; /* * Handle the Temporary RSA Keys and DH Params */ #define SSL_TMP_KEY_FREE(type, idx) \ if (SSL_temp_keys[idx]) { \ type##_free((type *)SSL_temp_keys[idx]); \ SSL_temp_keys[idx] = NULL; \ } else (void)(0) #define SSL_TMP_KEYS_FREE(type) \ SSL_TMP_KEY_FREE(type, SSL_TMP_KEY_##type##_512); \ SSL_TMP_KEY_FREE(type, SSL_TMP_KEY_##type##_1024); \ SSL_TMP_KEY_FREE(type, SSL_TMP_KEY_##type##_2048); \ SSL_TMP_KEY_FREE(type, SSL_TMP_KEY_##type##_4096) #define SSL_TMP_KEY_INIT_RSA(bits) \ ssl_tmp_key_init_rsa(bits, SSL_TMP_KEY_RSA_##bits) #define SSL_TMP_KEY_INIT_DH(bits) \ ssl_tmp_key_init_dh(bits, SSL_TMP_KEY_DH_##bits) #define SSL_TMP_KEYS_INIT(R) \ SSL_temp_keys[SSL_TMP_KEY_RSA_2048] = NULL; \ SSL_temp_keys[SSL_TMP_KEY_RSA_4096] = NULL; \ R |= SSL_TMP_KEY_INIT_RSA(512); \ R |= SSL_TMP_KEY_INIT_RSA(1024); \ R |= SSL_TMP_KEY_INIT_DH(512); \ R |= SSL_TMP_KEY_INIT_DH(1024); \ R |= SSL_TMP_KEY_INIT_DH(2048); \ R |= SSL_TMP_KEY_INIT_DH(4096) static int ssl_tmp_key_init_rsa(int bits, int idx) { if (!(SSL_temp_keys[idx] = RSA_generate_key(bits, RSA_F4, NULL, NULL))) return 1; else return 0; } static int ssl_tmp_key_init_dh(int bits, int idx) { if (!(SSL_temp_keys[idx] = SSL_dh_get_tmp_param(bits))) return 1; else return 0; } TCN_IMPLEMENT_CALL(jint, SSL, version)(TCN_STDARGS) { UNREFERENCED_STDARGS; return OPENSSL_VERSION_NUMBER; } TCN_IMPLEMENT_CALL(jstring, SSL, versionString)(TCN_STDARGS) { UNREFERENCED(o); return AJP_TO_JSTRING(OPENSSL_VERSION_TEXT); } /* * the various processing hooks */ static apr_status_t ssl_init_cleanup(void *data) { UNREFERENCED(data); if (!ssl_initialized) return APR_SUCCESS; ssl_initialized = 0; if (tcn_password_callback.cb.obj) { JNIEnv *env; tcn_get_java_env(&env); TCN_UNLOAD_CLASS(env, tcn_password_callback.cb.obj); } SSL_TMP_KEYS_FREE(RSA); SSL_TMP_KEYS_FREE(DH); /* * Try to kill the internals of the SSL library. */ #if OPENSSL_VERSION_NUMBER >= 0x00907001 /* Corresponds to OPENSSL_load_builtin_modules(): * XXX: borrowed from apps.h, but why not CONF_modules_free() * which also invokes CONF_modules_finish()? */ CONF_modules_unload(1); #endif /* Corresponds to SSL_library_init: */ EVP_cleanup(); #if HAVE_ENGINE_LOAD_BUILTIN_ENGINES ENGINE_cleanup(); #endif #if OPENSSL_VERSION_NUMBER >= 0x00907001 CRYPTO_cleanup_all_ex_data(); #endif ERR_remove_state(0); /* Don't call ERR_free_strings here; ERR_load_*_strings only * actually load the error strings once per process due to static * variable abuse in OpenSSL. */ /* * TODO: determine somewhere we can safely shove out diagnostics * (when enabled) at this late stage in the game: * CRYPTO_mem_leaks_fp(stderr); */ return APR_SUCCESS; } #ifndef OPENSSL_NO_ENGINE /* Try to load an engine in a shareable library */ static ENGINE *ssl_try_load_engine(const char *engine) { ENGINE *e = ENGINE_by_id("dynamic"); if (e) { if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0) || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) { ENGINE_free(e); e = NULL; } } return e; } #endif /* * To ensure thread-safetyness in OpenSSL */ static apr_thread_mutex_t **ssl_lock_cs; static int ssl_lock_num_locks; static void ssl_thread_lock(int mode, int type, const char *file, int line) { UNREFERENCED(file); UNREFERENCED(line); if (type < ssl_lock_num_locks) { if (mode & CRYPTO_LOCK) { apr_thread_mutex_lock(ssl_lock_cs[type]); } else { apr_thread_mutex_unlock(ssl_lock_cs[type]); } } } static unsigned long ssl_thread_id(void) { /* OpenSSL needs this to return an unsigned long. On OS/390, the pthread * id is a structure twice that big. Use the TCB pointer instead as a * unique unsigned long. */ #ifdef __MVS__ struct PSA { char unmapped[540]; unsigned long PSATOLD; } *psaptr = 0; return psaptr->PSATOLD; #else return (unsigned long)(apr_os_thread_current()); #endif } static apr_status_t ssl_thread_cleanup(void *data) { UNREFERENCED(data); CRYPTO_set_locking_callback(NULL); CRYPTO_set_id_callback(NULL); /* Let the registered mutex cleanups do their own thing */ return APR_SUCCESS; } static void ssl_thread_setup(apr_pool_t *p) { int i; ssl_lock_num_locks = CRYPTO_num_locks(); ssl_lock_cs = apr_palloc(p, ssl_lock_num_locks * sizeof(*ssl_lock_cs)); for (i = 0; i < ssl_lock_num_locks; i++) { apr_thread_mutex_create(&(ssl_lock_cs[i]), APR_THREAD_MUTEX_DEFAULT, p); } CRYPTO_set_id_callback(ssl_thread_id); CRYPTO_set_locking_callback(ssl_thread_lock); apr_pool_cleanup_register(p, NULL, ssl_thread_cleanup, apr_pool_cleanup_null); } static int ssl_rand_choosenum(int l, int h) { int i; char buf[50]; apr_snprintf(buf, sizeof(buf), "%.0f", (((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l))); i = atoi(buf)+1; if (i < l) i = l; if (i > h) i = h; return i; } static int ssl_rand_load_file(const char *file) { char buffer[APR_PATH_MAX]; int n; if (file == NULL) file = ssl_global_rand_file; if (file == NULL) file = RAND_file_name(buffer, sizeof(buffer)); else if ((n = RAND_egd(file)) > 0) { return n; } if (file && (n = RAND_load_file(file, -1)) > 0) return n; else return -1; } /* * writes a number of random bytes (currently 1024) to * file which can be used to initialize the PRNG by calling * RAND_load_file() in a later session */ static int ssl_rand_save_file(const char *file) { char buffer[APR_PATH_MAX]; int n; if (file == NULL) file = RAND_file_name(buffer, sizeof(buffer)); else if ((n = RAND_egd(file)) > 0) { return 0; } if (file == NULL || !RAND_write_file(file)) return 0; else return 1; } int SSL_rand_seed(const char *file) { unsigned char stackdata[256]; static volatile apr_uint32_t counter = 0; if (ssl_rand_load_file(file) < 0) { int n; struct { apr_time_t t; pid_t p; unsigned long i; apr_uint32_t u; } _ssl_seed; if (counter == 0) { apr_generate_random_bytes(stackdata, 256); RAND_seed(stackdata, 128); } _ssl_seed.t = apr_time_now(); _ssl_seed.p = getpid(); _ssl_seed.i = ssl_thread_id(); apr_atomic_inc32(&counter); _ssl_seed.u = counter; RAND_seed((unsigned char *)&_ssl_seed, sizeof(_ssl_seed)); /* * seed in some current state of the run-time stack (128 bytes) */ n = ssl_rand_choosenum(0, sizeof(stackdata)-128-1); RAND_seed(stackdata + n, 128); } return RAND_status(); } static int ssl_rand_make(const char *file, int len, int base64) { int r; int num = len; BIO *out = NULL; out = BIO_new(BIO_s_file()); if (out == NULL) return 0; if ((r = BIO_write_filename(out, (char *)file)) < 0) { BIO_free_all(out); return 0; } if (base64) { BIO *b64 = BIO_new(BIO_f_base64()); if (b64 == NULL) { BIO_free_all(out); return 0; } out = BIO_push(b64, out); } while (num > 0) { unsigned char buf[4096]; int len = num; if (len > sizeof(buf)) len = sizeof(buf); r = RAND_bytes(buf, len); if (r <= 0) { BIO_free_all(out); return 0; } BIO_write(out, buf, len); num -= len; } BIO_flush(out); BIO_free_all(out); return 1; } TCN_IMPLEMENT_CALL(jint, SSL, initialize)(TCN_STDARGS, jstring engine) { int r = 0; TCN_ALLOC_CSTRING(engine); UNREFERENCED(o); if (!tcn_global_pool) { TCN_FREE_CSTRING(engine); tcn_ThrowAPRException(e, APR_EINVAL); return (jint)APR_EINVAL; } /* Check if already initialized */ if (ssl_initialized++) { TCN_FREE_CSTRING(engine); return (jint)APR_SUCCESS; } if (SSLeay() < 0x0090700L) { TCN_FREE_CSTRING(engine); tcn_ThrowAPRException(e, APR_EINVAL); ssl_initialized = 0; return (jint)APR_EINVAL; } /* We must register the library in full, to ensure our configuration * code can successfully test the SSL environment. */ CRYPTO_malloc_init(); ERR_load_crypto_strings(); SSL_load_error_strings(); SSL_library_init(); #if HAVE_ENGINE_LOAD_BUILTIN_ENGINES ENGINE_load_builtin_engines(); #endif #if OPENSSL_VERSION_NUMBER >= 0x00907001 OPENSSL_load_builtin_modules(); #endif #ifndef OPENSSL_NO_ENGINE if (J2S(engine)) { ENGINE *ee = NULL; apr_status_t err = APR_SUCCESS; if(strcmp(J2S(engine), "auto") == 0) { ENGINE_register_all_complete(); } else { if ((ee = ENGINE_by_id(J2S(engine))) == NULL && (ee = ssl_try_load_engine(J2S(engine))) == NULL) err = APR_ENOTIMPL; else { if (strcmp(J2S(engine), "chil") == 0) ENGINE_ctrl(ee, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0); if (!ENGINE_set_default(ee, ENGINE_METHOD_ALL)) err = APR_ENOTIMPL; } /* Free our "structural" reference. */ if (ee) ENGINE_free(ee); } if (err != APR_SUCCESS) { TCN_FREE_CSTRING(engine); ssl_init_cleanup(NULL); tcn_ThrowAPRException(e, err); return (jint)err; } tcn_ssl_engine = ee; } #endif memset(&tcn_password_callback, 0, sizeof(tcn_pass_cb_t)); /* Initialize PRNG * This will in most cases call the builtin * low entropy seed. */ SSL_rand_seed(NULL); /* For SSL_get_app_data2() at request time */ SSL_init_app_data2_idx(); SSL_TMP_KEYS_INIT(r); if (r) { TCN_FREE_CSTRING(engine); ssl_init_cleanup(NULL); tcn_ThrowAPRException(e, APR_ENOTIMPL); return APR_ENOTIMPL; } /* * Let us cleanup the ssl library when the library is unloaded */ apr_pool_cleanup_register(tcn_global_pool, NULL, ssl_init_cleanup, apr_pool_cleanup_null); /* Initialize thread support */ ssl_thread_setup(tcn_global_pool); TCN_FREE_CSTRING(engine); return (jint)APR_SUCCESS; } TCN_IMPLEMENT_CALL(jboolean, SSL, randLoad)(TCN_STDARGS, jstring file) { TCN_ALLOC_CSTRING(file); int r; UNREFERENCED(o); r = SSL_rand_seed(J2S(file)); TCN_FREE_CSTRING(file); return r ? JNI_TRUE : JNI_FALSE; } TCN_IMPLEMENT_CALL(jboolean, SSL, randSave)(TCN_STDARGS, jstring file) { TCN_ALLOC_CSTRING(file); int r; UNREFERENCED(o); r = ssl_rand_save_file(J2S(file)); TCN_FREE_CSTRING(file); return r ? JNI_TRUE : JNI_FALSE; } TCN_IMPLEMENT_CALL(jboolean, SSL, randMake)(TCN_STDARGS, jstring file, jint length, jboolean base64) { TCN_ALLOC_CSTRING(file); int r; UNREFERENCED(o); r = ssl_rand_make(J2S(file), length, base64); TCN_FREE_CSTRING(file); return r ? JNI_TRUE : JNI_FALSE; } TCN_IMPLEMENT_CALL(void, SSL, randSet)(TCN_STDARGS, jstring file) { TCN_ALLOC_CSTRING(file); UNREFERENCED(o); if (J2S(file)) { ssl_global_rand_file = apr_pstrdup(tcn_global_pool, J2S(file)); } TCN_FREE_CSTRING(file); } /* OpenSSL Java Stream BIO */ typedef struct { int refcount; apr_pool_t *pool; tcn_callback_t cb; } BIO_JAVA; static apr_status_t generic_bio_cleanup(void *data) { BIO *b = (BIO *)data; if (b) { BIO_free(b); } return APR_SUCCESS; } void SSL_BIO_close(BIO *bi) { if (bi == NULL) return; if (bi->ptr != NULL && (bi->flags & SSL_BIO_FLAG_CALLBACK)) { BIO_JAVA *j = (BIO_JAVA *)bi->ptr; j->refcount--; if (j->refcount == 0) { if (j->pool) apr_pool_cleanup_run(j->pool, bi, generic_bio_cleanup); else BIO_free(bi); } } else BIO_free(bi); } void SSL_BIO_doref(BIO *bi) { if (bi == NULL) return; if (bi->ptr != NULL && (bi->flags & SSL_BIO_FLAG_CALLBACK)) { BIO_JAVA *j = (BIO_JAVA *)bi->ptr; j->refcount++; } } static int jbs_new(BIO *bi) { BIO_JAVA *j; if ((j = OPENSSL_malloc(sizeof(BIO_JAVA))) == NULL) return 0; j->pool = NULL; j->refcount = 1; bi->shutdown = 1; bi->init = 0; bi->num = -1; bi->ptr = (char *)j; return 1; } static int jbs_free(BIO *bi) { if (bi == NULL) return 0; if (bi->ptr != NULL) { BIO_JAVA *j = (BIO_JAVA *)bi->ptr; if (bi->init) { JNIEnv *e = NULL; bi->init = 0; tcn_get_java_env(&e); TCN_UNLOAD_CLASS(e, j->cb.obj); } OPENSSL_free(bi->ptr); } bi->ptr = NULL; return 1; } static int jbs_write(BIO *b, const char *in, int inl) { jint ret = 0; if (b->init && in != NULL) { BIO_JAVA *j = (BIO_JAVA *)b->ptr; JNIEnv *e = NULL; jbyteArray jb = (*e)->NewByteArray(e, inl); tcn_get_java_env(&e); if (!(*e)->ExceptionOccurred(e)) { (*e)->SetByteArrayRegion(e, jb, 0, inl, (jbyte *)in); ret = (*e)->CallIntMethod(e, j->cb.obj, j->cb.mid[0], jb); (*e)->ReleaseByteArrayElements(e, jb, (jbyte *)in, JNI_ABORT); (*e)->DeleteLocalRef(e, jb); } } return ret; } static int jbs_read(BIO *b, char *out, int outl) { jint ret = 0; if (b->init && out != NULL) { BIO_JAVA *j = (BIO_JAVA *)b->ptr; JNIEnv *e = NULL; jbyteArray jb = (*e)->NewByteArray(e, outl); tcn_get_java_env(&e); if (!(*e)->ExceptionOccurred(e)) { ret = (*e)->CallIntMethod(e, j->cb.obj, j->cb.mid[1], jb); if (ret > 0) { jbyte *jout = (*e)->GetPrimitiveArrayCritical(e, jb, NULL); memcpy(out, jout, ret); (*e)->ReleasePrimitiveArrayCritical(e, jb, jout, 0); } (*e)->DeleteLocalRef(e, jb); } } return ret; } static int jbs_puts(BIO *b, const char *in) { int ret = 0; if (b->init && in != NULL) { BIO_JAVA *j = (BIO_JAVA *)b->ptr; JNIEnv *e = NULL; tcn_get_java_env(&e); ret = (*e)->CallIntMethod(e, j->cb.obj, j->cb.mid[2], tcn_new_string(e, in)); } return ret; } static int jbs_gets(BIO *b, char *out, int outl) { int ret = 0; if (b->init && out != NULL) { BIO_JAVA *j = (BIO_JAVA *)b->ptr; JNIEnv *e = NULL; jobject o; tcn_get_java_env(&e); if ((o = (*e)->CallObjectMethod(e, j->cb.obj, j->cb.mid[3], (jint)(outl - 1)))) { TCN_ALLOC_CSTRING(o); if (J2S(o)) { int l = (int)strlen(J2S(o)); if (l < outl) { strcpy(out, J2S(o)); ret = outl; } } TCN_FREE_CSTRING(o); } } return ret; } static long jbs_ctrl(BIO *b, int cmd, long num, void *ptr) { return 0; } static BIO_METHOD jbs_methods = { BIO_TYPE_FILE, "Java Callback", jbs_write, jbs_read, jbs_puts, jbs_gets, jbs_ctrl, jbs_new, jbs_free, NULL }; static BIO_METHOD *BIO_jbs() { return(&jbs_methods); } TCN_IMPLEMENT_CALL(jlong, SSL, newBIO)(TCN_STDARGS, jlong pool, jobject callback) { BIO *bio = NULL; BIO_JAVA *j; jclass cls; UNREFERENCED(o); if ((bio = BIO_new(BIO_jbs())) == NULL) { tcn_ThrowException(e, "Create BIO failed"); goto init_failed; } j = (BIO_JAVA *)bio->ptr; if ((j = (BIO_JAVA *)bio->ptr) == NULL) { tcn_ThrowException(e, "Create BIO failed"); goto init_failed; } j->pool = J2P(pool, apr_pool_t *); if (j->pool) { apr_pool_cleanup_register(j->pool, (const void *)bio, generic_bio_cleanup, apr_pool_cleanup_null); } cls = (*e)->GetObjectClass(e, callback); j->cb.mid[0] = (*e)->GetMethodID(e, cls, "write", "([B)I"); j->cb.mid[1] = (*e)->GetMethodID(e, cls, "read", "([B)I"); j->cb.mid[2] = (*e)->GetMethodID(e, cls, "puts", "(Ljava/lang/String;)I"); j->cb.mid[3] = (*e)->GetMethodID(e, cls, "gets", "(I)Ljava/lang/String;"); /* TODO: Check if method id's are valid */ j->cb.obj = (*e)->NewGlobalRef(e, callback); bio->init = 1; bio->flags = SSL_BIO_FLAG_CALLBACK; return P2J(bio); init_failed: return 0; } TCN_IMPLEMENT_CALL(jint, SSL, closeBIO)(TCN_STDARGS, jlong bio) { BIO *b = J2P(bio, BIO *); UNREFERENCED_STDARGS; SSL_BIO_close(b); return APR_SUCCESS; } TCN_IMPLEMENT_CALL(void, SSL, setPasswordCallback)(TCN_STDARGS, jobject callback) { jclass cls; UNREFERENCED(o); if (tcn_password_callback.cb.obj) { TCN_UNLOAD_CLASS(e, tcn_password_callback.cb.obj); } cls = (*e)->GetObjectClass(e, callback); tcn_password_callback.cb.mid[0] = (*e)->GetMethodID(e, cls, "callback", "(Ljava/lang/String;)Ljava/lang/String;"); /* TODO: Check if method id is valid */ tcn_password_callback.cb.obj = (*e)->NewGlobalRef(e, callback); } TCN_IMPLEMENT_CALL(void, SSL, setPassword)(TCN_STDARGS, jstring password) { TCN_ALLOC_CSTRING(password); UNREFERENCED(o); if (J2S(password)) { strncpy(tcn_password_callback.password, J2S(password), SSL_MAX_PASSWORD_LEN); tcn_password_callback.password[SSL_MAX_PASSWORD_LEN-1] = '\0'; } TCN_FREE_CSTRING(password); } TCN_IMPLEMENT_CALL(jboolean, SSL, generateRSATempKey)(TCN_STDARGS, jint idx) { int r = 1; UNREFERENCED_STDARGS; SSL_TMP_KEY_FREE(RSA, idx); switch (idx) { case SSL_TMP_KEY_RSA_512: r = SSL_TMP_KEY_INIT_RSA(512); break; case SSL_TMP_KEY_RSA_1024: r = SSL_TMP_KEY_INIT_RSA(1024); break; case SSL_TMP_KEY_RSA_2048: r = SSL_TMP_KEY_INIT_RSA(2048); break; case SSL_TMP_KEY_RSA_4096: r = SSL_TMP_KEY_INIT_RSA(4096); break; } return r ? JNI_FALSE : JNI_TRUE; } TCN_IMPLEMENT_CALL(jboolean, SSL, loadDSATempKey)(TCN_STDARGS, jint idx, jstring file) { jboolean r = JNI_FALSE; TCN_ALLOC_CSTRING(file); DH *dh; UNREFERENCED(o); if (!J2S(file)) return JNI_FALSE; SSL_TMP_KEY_FREE(DSA, idx); if ((dh = SSL_dh_get_param_from_file(J2S(file)))) { SSL_temp_keys[idx] = dh; r = JNI_TRUE; } TCN_FREE_CSTRING(file); return r; } TCN_IMPLEMENT_CALL(jstring, SSL, getLastError)(TCN_STDARGS) { char buf[256]; UNREFERENCED(o); ERR_error_string(ERR_get_error(), buf); return tcn_new_string(e, buf); } #else /* OpenSSL is not supported. * Create empty stubs. */ TCN_IMPLEMENT_CALL(jint, SSL, version)(TCN_STDARGS) { UNREFERENCED_STDARGS; return 0; } TCN_IMPLEMENT_CALL(jstring, SSL, versionString)(TCN_STDARGS) { UNREFERENCED_STDARGS; return NULL; } TCN_IMPLEMENT_CALL(jint, SSL, initialize)(TCN_STDARGS, jstring engine) { UNREFERENCED(o); UNREFERENCED(engine); tcn_ThrowAPRException(e, APR_ENOTIMPL); return (jint)APR_ENOTIMPL; } TCN_IMPLEMENT_CALL(jboolean, SSL, randLoad)(TCN_STDARGS, jstring file) { UNREFERENCED_STDARGS; UNREFERENCED(file); return JNI_FALSE; } TCN_IMPLEMENT_CALL(jboolean, SSL, randSave)(TCN_STDARGS, jstring file) { UNREFERENCED_STDARGS; return JNI_FALSE; } TCN_IMPLEMENT_CALL(jboolean, SSL, randMake)(TCN_STDARGS, jstring file, jint length, jboolean base64) { UNREFERENCED_STDARGS; UNREFERENCED(file); UNREFERENCED(length); UNREFERENCED(base64); return JNI_FALSE; } TCN_IMPLEMENT_CALL(jlong, SSL, newBIO)(TCN_STDARGS, jlong pool, jobject callback) { UNREFERENCED_STDARGS; UNREFERENCED(pool); UNREFERENCED(callback); return 0; } TCN_IMPLEMENT_CALL(jint, SSL, closeBIO)(TCN_STDARGS, jlong bio) { UNREFERENCED_STDARGS; UNREFERENCED(bio); return (jint)APR_ENOTIMPL; } TCN_IMPLEMENT_CALL(void, SSL, setPasswordCallback)(TCN_STDARGS, jobject callback) { UNREFERENCED_STDARGS; UNREFERENCED(callback); } TCN_IMPLEMENT_CALL(void, SSL, setPassword)(TCN_STDARGS, jstring password) { UNREFERENCED_STDARGS; UNREFERENCED(password); } TCN_IMPLEMENT_CALL(jboolean, SSL, generateRSATempKey)(TCN_STDARGS, jint idx) { UNREFERENCED_STDARGS; UNREFERENCED(idx); return JNI_FALSE; } TCN_IMPLEMENT_CALL(jboolean, SSL, loadDSATempKey)(TCN_STDARGS, jint idx, jstring file) { UNREFERENCED_STDARGS; UNREFERENCED(idx); UNREFERENCED(file); return JNI_FALSE; } TCN_IMPLEMENT_CALL(jstring, SSL, getLastError)(TCN_STDARGS) { UNREFERENCED_STDARGS; return NULL; } #endif
supercj92/tomcat6
native/connector/src/poll.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * * @author <NAME> * @version $Revision: 466609 $, $Date: 2006-10-22 01:30:39 +0200 (dim., 22 oct. 2006) $ */ #include "tcn.h" #include "apr_poll.h" #ifdef TCN_DO_STATISTICS static int sp_created = 0; static int sp_destroyed = 0; static int sp_cleared = 0; #endif /* Internal poll structure for queryset */ typedef struct tcn_pollset { apr_pool_t *pool; apr_int32_t nelts; apr_int32_t nalloc; apr_pollset_t *pollset; jlong *set; apr_pollfd_t *socket_set; apr_interval_time_t *socket_ttl; apr_interval_time_t max_ttl; #ifdef TCN_DO_STATISTICS int sp_added; int sp_max_count; int sp_poll; int sp_polled; int sp_max_polled; int sp_remove; int sp_removed; int sp_maintained; int sp_max_maintained; int sp_err_poll; int sp_poll_timeout; int sp_overflow; int sp_equals; int sp_eintr; #endif } tcn_pollset_t; #ifdef TCN_DO_STATISTICS static void sp_poll_statistics(tcn_pollset_t *p) { fprintf(stderr, "Pollset Statistics ......\n"); fprintf(stderr, "Number of added sockets : %d\n", p->sp_added); fprintf(stderr, "Max. number of sockets : %d\n", p->sp_max_count); fprintf(stderr, "Poll calls : %d\n", p->sp_poll); fprintf(stderr, "Poll timeouts : %d\n", p->sp_poll_timeout); fprintf(stderr, "Poll errors : %d\n", p->sp_err_poll); fprintf(stderr, "Poll overflows : %d\n", p->sp_overflow); fprintf(stderr, "Polled sockets : %d\n", p->sp_polled); fprintf(stderr, "Max. Polled sockets : %d\n", p->sp_max_polled); fprintf(stderr, "Poll remove : %d\n", p->sp_remove); fprintf(stderr, "Total removed : %d\n", p->sp_removed); fprintf(stderr, "Maintained : %d\n", p->sp_maintained); fprintf(stderr, "Max. maintained : %d\n", p->sp_max_maintained); fprintf(stderr, "Number of duplicates : %d\n", p->sp_equals); fprintf(stderr, "Number of interrupts : %d\n", p->sp_eintr); } static apr_status_t sp_poll_cleanup(void *data) { sp_cleared++; sp_poll_statistics(data); return APR_SUCCESS; } void sp_poll_dump_statistics() { fprintf(stderr, "Poll Statistics .........\n"); fprintf(stderr, "Polls created : %d\n", sp_created); fprintf(stderr, "Polls destroyed : %d\n", sp_destroyed); fprintf(stderr, "Polls cleared : %d\n", sp_cleared); } #endif TCN_IMPLEMENT_CALL(jlong, Poll, create)(TCN_STDARGS, jint size, jlong pool, jint flags, jlong ttl) { apr_pool_t *p = J2P(pool, apr_pool_t *); apr_pollset_t *pollset = NULL; tcn_pollset_t *tps = NULL; apr_uint32_t f = (apr_uint32_t)flags; UNREFERENCED(o); TCN_ASSERT(pool != 0); if (f & APR_POLLSET_THREADSAFE) { apr_status_t rv = apr_pollset_create(&pollset, (apr_uint32_t)size, p, f); if (rv == APR_ENOTIMPL) f &= ~APR_POLLSET_THREADSAFE; else if (rv != APR_SUCCESS) { tcn_ThrowAPRException(e, rv); goto cleanup; } } if (pollset == NULL) { TCN_THROW_IF_ERR(apr_pollset_create(&pollset, (apr_uint32_t)size, p, f), pollset); } tps = apr_pcalloc(p, sizeof(tcn_pollset_t)); TCN_CHECK_ALLOCATED(tps); tps->pollset = pollset; tps->set = apr_palloc(p, size * sizeof(jlong) * 2); TCN_CHECK_ALLOCATED(tps->set); tps->socket_set = apr_palloc(p, size * sizeof(apr_pollfd_t)); TCN_CHECK_ALLOCATED(tps->socket_set); tps->socket_ttl = apr_palloc(p, size * sizeof(apr_interval_time_t)); TCN_CHECK_ALLOCATED(tps->socket_ttl); tps->nelts = 0; tps->nalloc = size; tps->pool = p; tps->max_ttl = J2T(ttl); #ifdef TCN_DO_STATISTICS sp_created++; apr_pool_cleanup_register(p, (const void *)tps, sp_poll_cleanup, apr_pool_cleanup_null); #endif cleanup: return P2J(tps); } TCN_IMPLEMENT_CALL(jint, Poll, destroy)(TCN_STDARGS, jlong pollset) { tcn_pollset_t *p = J2P(pollset, tcn_pollset_t *); UNREFERENCED_STDARGS; TCN_ASSERT(pollset != 0); #ifdef TCN_DO_STATISTICS sp_destroyed++; apr_pool_cleanup_kill(p->pool, p, sp_poll_cleanup); sp_poll_statistics(p); #endif return (jint)apr_pollset_destroy(p->pollset); } TCN_IMPLEMENT_CALL(jint, Poll, add)(TCN_STDARGS, jlong pollset, jlong socket, jint reqevents) { tcn_pollset_t *p = J2P(pollset, tcn_pollset_t *); tcn_socket_t *s = J2P(socket, tcn_socket_t *); apr_pollfd_t fd; UNREFERENCED_STDARGS; TCN_ASSERT(socket != 0); if (p->nelts == p->nalloc) { #ifdef TCN_DO_STATISTICS p->sp_overflow++; #endif return APR_ENOMEM; } memset(&fd, 0, sizeof(apr_pollfd_t)); fd.desc_type = APR_POLL_SOCKET; fd.reqevents = (apr_int16_t)reqevents; fd.desc.s = s->sock; fd.client_data = s; if (p->max_ttl > 0) p->socket_ttl[p->nelts] = apr_time_now(); else p->socket_ttl[p->nelts] = 0; p->socket_set[p->nelts] = fd; p->nelts++; #ifdef TCN_DO_STATISTICS p->sp_added++; p->sp_max_count = TCN_MAX(p->sp_max_count, p->sp_added); #endif return (jint)apr_pollset_add(p->pollset, &fd); } static apr_status_t do_remove(tcn_pollset_t *p, const apr_pollfd_t *fd) { apr_int32_t i; for (i = 0; i < p->nelts; i++) { if (fd->desc.s == p->socket_set[i].desc.s) { /* Found an instance of the fd: remove this and any other copies */ apr_int32_t dst = i; apr_int32_t old_nelts = p->nelts; p->nelts--; #ifdef TCN_DO_STATISTICS p->sp_removed++; #endif for (i++; i < old_nelts; i++) { if (fd->desc.s == p->socket_set[i].desc.s) { #ifdef TCN_DO_STATISTICS p->sp_equals++; #endif p->nelts--; } else { p->socket_set[dst] = p->socket_set[i]; dst++; } } break; } } return apr_pollset_remove(p->pollset, fd); } static void remove_all(tcn_pollset_t *p) { apr_int32_t i; for (i = 0; i < p->nelts; i++) { apr_pollset_remove(p->pollset, &(p->socket_set[i])); #ifdef TCN_DO_STATISTICS p->sp_removed++; #endif } p->nelts = 0; } TCN_IMPLEMENT_CALL(jint, Poll, remove)(TCN_STDARGS, jlong pollset, jlong socket) { tcn_pollset_t *p = J2P(pollset, tcn_pollset_t *); tcn_socket_t *s = J2P(socket, tcn_socket_t *); apr_pollfd_t fd; UNREFERENCED_STDARGS; TCN_ASSERT(socket != 0); memset(&fd, 0, sizeof(apr_pollfd_t)); fd.desc_type = APR_POLL_SOCKET; fd.desc.s = s->sock; fd.reqevents = APR_POLLIN | APR_POLLOUT; #ifdef TCN_DO_STATISTICS p->sp_remove++; #endif return (jint)do_remove(p, &fd); } TCN_IMPLEMENT_CALL(jint, Poll, poll)(TCN_STDARGS, jlong pollset, jlong timeout, jlongArray set, jboolean remove) { const apr_pollfd_t *fd = NULL; tcn_pollset_t *p = J2P(pollset, tcn_pollset_t *); apr_int32_t i, num = 0; apr_status_t rv = APR_SUCCESS; apr_interval_time_t ptime = J2T(timeout); UNREFERENCED(o); TCN_ASSERT(pollset != 0); #ifdef TCN_DO_STATISTICS p->sp_poll++; #endif if (ptime > 0 && p->max_ttl >= 0) { apr_time_t now = apr_time_now(); /* Find the minimum timeout */ for (i = 0; i < p->nelts; i++) { apr_interval_time_t t = now - p->socket_ttl[i]; if (t >= p->max_ttl) { ptime = 0; break; } else { ptime = TCN_MIN(p->max_ttl - t, ptime); } } } else if (ptime < 0) ptime = 0; for (;;) { rv = apr_pollset_poll(p->pollset, ptime, &num, &fd); if (rv != APR_SUCCESS) { if (APR_STATUS_IS_EINTR(rv)) { #ifdef TCN_DO_STATISTICS p->sp_eintr++; #endif continue; } TCN_ERROR_WRAP(rv); #ifdef TCN_DO_STATISTICS if (rv == TCN_TIMEUP) p->sp_poll_timeout++; else p->sp_err_poll++; #endif num = (apr_int32_t)(-rv); } break; } if (num > 0) { #ifdef TCN_DO_STATISTICS p->sp_polled += num; p->sp_max_polled = TCN_MAX(p->sp_max_polled, num); #endif for (i = 0; i < num; i++) { p->set[i*2+0] = (jlong)(fd->rtnevents); p->set[i*2+1] = P2J(fd->client_data); if (remove) do_remove(p, fd); fd ++; } (*e)->SetLongArrayRegion(e, set, 0, num * 2, p->set); } return (jint)num; } TCN_IMPLEMENT_CALL(jint, Poll, maintain)(TCN_STDARGS, jlong pollset, jlongArray set, jboolean remove) { tcn_pollset_t *p = J2P(pollset, tcn_pollset_t *); apr_int32_t i = 0, num = 0; apr_time_t now = apr_time_now(); apr_pollfd_t fd; UNREFERENCED(o); TCN_ASSERT(pollset != 0); /* Check for timeout sockets */ if (p->max_ttl > 0) { for (i = 0; i < p->nelts; i++) { if ((now - p->socket_ttl[i]) >= p->max_ttl) { fd = p->socket_set[i]; p->set[num++] = P2J(fd.client_data); } } if (remove && num) { memset(&fd, 0, sizeof(apr_pollfd_t)); #ifdef TCN_DO_STATISTICS p->sp_maintained += num; p->sp_max_maintained = TCN_MAX(p->sp_max_maintained, num); #endif for (i = 0; i < num; i++) { fd.desc_type = APR_POLL_SOCKET; fd.reqevents = APR_POLLIN | APR_POLLOUT; fd.desc.s = (J2P(p->set[i], tcn_socket_t *))->sock; do_remove(p, &fd); } } } else if (p->max_ttl == 0) { for (i = 0; i < p->nelts; i++) { fd = p->socket_set[i]; p->set[num++] = P2J(fd.client_data); } if (remove) { remove_all(p); #ifdef TCN_DO_STATISTICS p->sp_maintained += num; p->sp_max_maintained = TCN_MAX(p->sp_max_maintained, num); #endif } } if (num) (*e)->SetLongArrayRegion(e, set, 0, num, p->set); return (jint)num; } TCN_IMPLEMENT_CALL(void, Poll, setTtl)(TCN_STDARGS, jlong pollset, jlong ttl) { tcn_pollset_t *p = J2P(pollset, tcn_pollset_t *); UNREFERENCED_STDARGS; p->max_ttl = J2T(ttl); } TCN_IMPLEMENT_CALL(jlong, Poll, getTtl)(TCN_STDARGS, jlong pollset) { tcn_pollset_t *p = J2P(pollset, tcn_pollset_t *); UNREFERENCED_STDARGS; return (jlong)p->max_ttl; } TCN_IMPLEMENT_CALL(jint, Poll, pollset)(TCN_STDARGS, jlong pollset, jlongArray set) { tcn_pollset_t *p = J2P(pollset, tcn_pollset_t *); apr_int32_t i = 0; apr_pollfd_t fd; UNREFERENCED(o); TCN_ASSERT(pollset != 0); for (i = 0; i < p->nelts; i++) { p->socket_set[i].rtnevents = APR_POLLHUP | APR_POLLIN; fd = p->socket_set[i]; p->set[i*2+0] = (jlong)(fd.rtnevents); p->set[i*2+1] = P2J(fd.client_data); } if (p->nelts) (*e)->SetLongArrayRegion(e, set, 0, p->nelts * 2, p->set); return (jint)p->nelts; }
supercj92/tomcat6
native/connector/src/sslcontext.c
<filename>native/connector/src/sslcontext.c<gh_stars>0 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /** SSL Context wrapper * * @author <NAME> * @version $Revision: 481766 $, $Date: 2006-12-03 13:40:18 +0100 (dim., 03 déc. 2006) $ */ #include "tcn.h" #include "apr_file_io.h" #include "apr_thread_mutex.h" #include "apr_poll.h" #ifdef HAVE_OPENSSL #include "ssl_private.h" static apr_status_t ssl_context_cleanup(void *data) { tcn_ssl_ctxt_t *c = (tcn_ssl_ctxt_t *)data; if (c) { int i; if (c->crl) X509_STORE_free(c->crl); c->crl = NULL; if (c->ctx) SSL_CTX_free(c->ctx); c->ctx = NULL; for (i = 0; i < SSL_AIDX_MAX; i++) { if (c->certs[i]) { X509_free(c->certs[i]); c->certs[i] = NULL; } if (c->keys[i]) { EVP_PKEY_free(c->keys[i]); c->keys[i] = NULL; } } if (c->bio_is) { SSL_BIO_close(c->bio_is); c->bio_is = NULL; } if (c->bio_os) { SSL_BIO_close(c->bio_os); c->bio_os = NULL; } } return APR_SUCCESS; } /* Initialize server context */ TCN_IMPLEMENT_CALL(jlong, SSLContext, make)(TCN_STDARGS, jlong pool, jint protocol, jint mode) { apr_pool_t *p = J2P(pool, apr_pool_t *); tcn_ssl_ctxt_t *c = NULL; SSL_CTX *ctx = NULL; UNREFERENCED(o); switch (protocol) { case SSL_PROTOCOL_SSLV2: case SSL_PROTOCOL_SSLV2 | SSL_PROTOCOL_TLSV1: if (mode == SSL_MODE_CLIENT) ctx = SSL_CTX_new(SSLv2_client_method()); else if (mode == SSL_MODE_SERVER) ctx = SSL_CTX_new(SSLv2_server_method()); else ctx = SSL_CTX_new(SSLv2_method()); break; case SSL_PROTOCOL_SSLV3: case SSL_PROTOCOL_SSLV3 | SSL_PROTOCOL_TLSV1: if (mode == SSL_MODE_CLIENT) ctx = SSL_CTX_new(SSLv3_client_method()); else if (mode == SSL_MODE_SERVER) ctx = SSL_CTX_new(SSLv3_server_method()); else ctx = SSL_CTX_new(SSLv3_method()); break; case SSL_PROTOCOL_SSLV2 | SSL_PROTOCOL_SSLV3: case SSL_PROTOCOL_ALL: if (mode == SSL_MODE_CLIENT) ctx = SSL_CTX_new(SSLv23_client_method()); else if (mode == SSL_MODE_SERVER) ctx = SSL_CTX_new(SSLv23_server_method()); else ctx = SSL_CTX_new(SSLv23_method()); break; case SSL_PROTOCOL_TLSV1: if (mode == SSL_MODE_CLIENT) ctx = SSL_CTX_new(TLSv1_client_method()); else if (mode == SSL_MODE_SERVER) ctx = SSL_CTX_new(TLSv1_server_method()); else ctx = SSL_CTX_new(TLSv1_method()); break; } if (!ctx) { tcn_ThrowException(e, "Invalid Server SSL Protocol"); goto init_failed; } if ((c = apr_pcalloc(p, sizeof(tcn_ssl_ctxt_t))) == NULL) { tcn_ThrowAPRException(e, apr_get_os_error()); goto init_failed; } c->protocol = protocol; c->mode = mode; c->ctx = ctx; c->pool = p; c->bio_os = BIO_new(BIO_s_file()); if (c->bio_os != NULL) BIO_set_fp(c->bio_os, stderr, BIO_NOCLOSE | BIO_FP_TEXT); SSL_CTX_set_options(c->ctx, SSL_OP_ALL); if (!(protocol & SSL_PROTOCOL_SSLV2)) SSL_CTX_set_options(c->ctx, SSL_OP_NO_SSLv2); if (!(protocol & SSL_PROTOCOL_SSLV3)) SSL_CTX_set_options(c->ctx, SSL_OP_NO_SSLv3); if (!(protocol & SSL_PROTOCOL_TLSV1)) SSL_CTX_set_options(c->ctx, SSL_OP_NO_TLSv1); /* * Configure additional context ingredients */ SSL_CTX_set_options(c->ctx, SSL_OP_SINGLE_DH_USE); #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION /* * Disallow a session from being resumed during a renegotiation, * so that an acceptable cipher suite can be negotiated. */ SSL_CTX_set_options(c->ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); #endif /* Default session context id and cache size */ SSL_CTX_sess_set_cache_size(c->ctx, SSL_DEFAULT_CACHE_SIZE); MD5((const unsigned char *)SSL_DEFAULT_VHOST_NAME, (unsigned long)(sizeof(SSL_DEFAULT_VHOST_NAME) - 1), &(c->context_id[0])); if (mode) { SSL_CTX_set_tmp_rsa_callback(c->ctx, SSL_callback_tmp_RSA); SSL_CTX_set_tmp_dh_callback(c->ctx, SSL_callback_tmp_DH); } /* Set default Certificate verification level * and depth for the Client Authentication */ c->verify_depth = 1; c->verify_mode = SSL_CVERIFY_UNSET; c->shutdown_type = SSL_SHUTDOWN_TYPE_UNSET; /* Set default password callback */ SSL_CTX_set_default_passwd_cb(c->ctx, (pem_password_cb *)SSL_password_callback); SSL_CTX_set_default_passwd_cb_userdata(c->ctx, (void *)(&tcn_password_callback)); /* * Let us cleanup the ssl context when the pool is destroyed */ apr_pool_cleanup_register(p, (const void *)c, ssl_context_cleanup, apr_pool_cleanup_null); return P2J(c); init_failed: return 0; } TCN_IMPLEMENT_CALL(jint, SSLContext, free)(TCN_STDARGS, jlong ctx) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); UNREFERENCED_STDARGS; TCN_ASSERT(ctx != 0); /* Run and destroy the cleanup callback */ return apr_pool_cleanup_run(c->pool, c, ssl_context_cleanup); } TCN_IMPLEMENT_CALL(void, SSLContext, setContextId)(TCN_STDARGS, jlong ctx, jstring id) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); TCN_ALLOC_CSTRING(id); TCN_ASSERT(ctx != 0); UNREFERENCED(o); if (J2S(id)) { MD5((const unsigned char *)J2S(id), (unsigned long)strlen(J2S(id)), &(c->context_id[0])); } TCN_FREE_CSTRING(id); } TCN_IMPLEMENT_CALL(void, SSLContext, setBIO)(TCN_STDARGS, jlong ctx, jlong bio, jint dir) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); BIO *bio_handle = J2P(bio, BIO *); UNREFERENCED_STDARGS; TCN_ASSERT(ctx != 0); if (dir == 0) { if (c->bio_os && c->bio_os != bio_handle) SSL_BIO_close(c->bio_os); c->bio_os = bio_handle; } else if (dir == 1) { if (c->bio_is && c->bio_is != bio_handle) SSL_BIO_close(c->bio_is); c->bio_is = bio_handle; } else return; SSL_BIO_doref(bio_handle); } TCN_IMPLEMENT_CALL(void, SSLContext, setOptions)(TCN_STDARGS, jlong ctx, jint opt) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); UNREFERENCED_STDARGS; TCN_ASSERT(ctx != 0); SSL_CTX_set_options(c->ctx, opt); } TCN_IMPLEMENT_CALL(void, SSLContext, setQuietShutdown)(TCN_STDARGS, jlong ctx, jboolean mode) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); UNREFERENCED_STDARGS; TCN_ASSERT(ctx != 0); SSL_CTX_set_quiet_shutdown(c->ctx, mode ? 1 : 0); } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCipherSuite)(TCN_STDARGS, jlong ctx, jstring ciphers) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); TCN_ALLOC_CSTRING(ciphers); jboolean rv = JNI_TRUE; UNREFERENCED(o); TCN_ASSERT(ctx != 0); if (!J2S(ciphers)) return JNI_FALSE; if (!SSL_CTX_set_cipher_list(c->ctx, J2S(ciphers))) { char err[256]; ERR_error_string(ERR_get_error(), err); tcn_Throw(e, "Unable to configure permitted SSL ciphers (%s)", err); rv = JNI_FALSE; } TCN_FREE_CSTRING(ciphers); return rv; } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCARevocation)(TCN_STDARGS, jlong ctx, jstring file, jstring path) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); TCN_ALLOC_CSTRING(file); TCN_ALLOC_CSTRING(path); jboolean rv = JNI_FALSE; X509_LOOKUP *lookup; char err[256]; UNREFERENCED(o); TCN_ASSERT(ctx != 0); if (J2S(file) == NULL && J2S(path) == NULL) return JNI_FALSE; if (!c->crl) { if ((c->crl = X509_STORE_new()) == NULL) goto cleanup; } if (J2S(file)) { lookup = X509_STORE_add_lookup(c->crl, X509_LOOKUP_file()); if (lookup == NULL) { ERR_error_string(ERR_get_error(), err); X509_STORE_free(c->crl); c->crl = NULL; tcn_Throw(e, "Lookup failed for file %s (%s)", J2S(file), err); goto cleanup; } X509_LOOKUP_load_file(lookup, J2S(file), X509_FILETYPE_PEM); } if (J2S(path)) { lookup = X509_STORE_add_lookup(c->crl, X509_LOOKUP_hash_dir()); if (lookup == NULL) { ERR_error_string(ERR_get_error(), err); X509_STORE_free(c->crl); c->crl = NULL; tcn_Throw(e, "Lookup failed for path %s (%s)", J2S(file), err); goto cleanup; } X509_LOOKUP_add_dir(lookup, J2S(path), X509_FILETYPE_PEM); } rv = JNI_TRUE; cleanup: TCN_FREE_CSTRING(file); TCN_FREE_CSTRING(path); return rv; } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCertificateChainFile)(TCN_STDARGS, jlong ctx, jstring file, jboolean skipfirst) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); jboolean rv = JNI_FALSE; TCN_ALLOC_CSTRING(file); UNREFERENCED(o); TCN_ASSERT(ctx != 0); if (!J2S(file)) return JNI_FALSE; if (SSL_CTX_use_certificate_chain(c->ctx, J2S(file), skipfirst) > 0) rv = JNI_TRUE; TCN_FREE_CSTRING(file); return rv; } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCACertificate)(TCN_STDARGS, jlong ctx, jstring file, jstring path) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); jboolean rv = JNI_TRUE; TCN_ALLOC_CSTRING(file); TCN_ALLOC_CSTRING(path); UNREFERENCED(o); TCN_ASSERT(ctx != 0); if (file == NULL && path == NULL) return JNI_FALSE; /* * Configure Client Authentication details */ if (!SSL_CTX_load_verify_locations(c->ctx, J2S(file), J2S(path))) { char err[256]; ERR_error_string(ERR_get_error(), err); tcn_Throw(e, "Unable to configure locations " "for client authentication (%s)", err); rv = JNI_FALSE; goto cleanup; } c->store = SSL_CTX_get_cert_store(c->ctx); if (c->mode) { STACK_OF(X509_NAME) *ca_certs; c->ca_certs++; ca_certs = SSL_CTX_get_client_CA_list(c->ctx); if (ca_certs == NULL) { SSL_load_client_CA_file(J2S(file)); if (ca_certs != NULL) SSL_CTX_set_client_CA_list(c->ctx, (STACK *)ca_certs); } else { if (!SSL_add_file_cert_subjects_to_stack((STACK *)ca_certs, J2S(file))) ca_certs = NULL; } if (ca_certs == NULL && c->verify_mode == SSL_CVERIFY_REQUIRE) { /* * Give a warning when no CAs were configured but client authentication * should take place. This cannot work. */ BIO_printf(c->bio_os, "[WARN] Oops, you want to request client " "authentication, but no CAs are known for " "verification!?"); } } cleanup: TCN_FREE_CSTRING(file); TCN_FREE_CSTRING(path); return rv; } TCN_IMPLEMENT_CALL(void, SSLContext, setShutdownType)(TCN_STDARGS, jlong ctx, jint type) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); UNREFERENCED_STDARGS; TCN_ASSERT(ctx != 0); c->shutdown_type = type; } TCN_IMPLEMENT_CALL(void, SSLContext, setVerify)(TCN_STDARGS, jlong ctx, jint level, jint depth) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); int verify = SSL_VERIFY_NONE; UNREFERENCED(o); TCN_ASSERT(ctx != 0); c->verify_mode = level; if (c->verify_mode == SSL_CVERIFY_UNSET) c->verify_mode = SSL_CVERIFY_NONE; if (depth > 0) c->verify_depth = depth; /* * Configure callbacks for SSL context */ if (c->verify_mode == SSL_CVERIFY_REQUIRE) verify |= SSL_VERIFY_PEER_STRICT; if ((c->verify_mode == SSL_CVERIFY_OPTIONAL) || (c->verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA)) verify |= SSL_VERIFY_PEER; if (!c->store) { if (SSL_CTX_set_default_verify_paths(c->ctx)) { c->store = SSL_CTX_get_cert_store(c->ctx); X509_STORE_set_flags(c->store, 0); } else { /* XXX: See if this is fatal */ } } SSL_CTX_set_verify(c->ctx, verify, SSL_callback_SSL_verify); } static EVP_PKEY *load_pem_key(tcn_ssl_ctxt_t *c, const char *file) { BIO *bio = NULL; EVP_PKEY *key = NULL; void *cb_data = c->cb_data; if ((bio = BIO_new(BIO_s_file())) == NULL) { return NULL; } if (BIO_read_filename(bio, file) <= 0) { BIO_free(bio); return NULL; } if (!cb_data) cb_data = &tcn_password_callback; key = PEM_read_bio_PrivateKey(bio, NULL, (pem_password_cb *)SSL_password_callback, cb_data); BIO_free(bio); return key; } static X509 *load_pem_cert(const char *file) { BIO *bio = NULL; X509 *cert = NULL; if ((bio = BIO_new(BIO_s_file())) == NULL) { return NULL; } if (BIO_read_filename(bio, file) <= 0) { BIO_free(bio); return NULL; } cert = PEM_read_bio_X509_AUX(bio, NULL, (pem_password_cb *)SSL_password_callback, NULL); BIO_free(bio); return cert; } TCN_IMPLEMENT_CALL(void, SSLContext, setRandom)(TCN_STDARGS, jlong ctx, jstring file) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); TCN_ALLOC_CSTRING(file); TCN_ASSERT(ctx != 0); UNREFERENCED(o); if (J2S(file)) c->rand_file = apr_pstrdup(c->pool, J2S(file)); TCN_FREE_CSTRING(file); } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCertificate)(TCN_STDARGS, jlong ctx, jstring cert, jstring key, jstring password, jint idx) { tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *); jboolean rv = JNI_TRUE; TCN_ALLOC_CSTRING(cert); TCN_ALLOC_CSTRING(key); TCN_ALLOC_CSTRING(password); const char *key_file, *cert_file; char err[256]; UNREFERENCED(o); TCN_ASSERT(ctx != 0); if (idx < 0 || idx >= SSL_AIDX_MAX) { /* TODO: Throw something */ rv = JNI_FALSE; goto cleanup; } if (J2S(password)) { if (!c->cb_data) c->cb_data = &tcn_password_callback; strncpy(c->cb_data->password, J2S(password), SSL_MAX_PASSWORD_LEN); c->cb_data->password[SSL_MAX_PASSWORD_LEN-1] = '\0'; } key_file = J2S(key); cert_file = J2S(cert); if (!key_file) key_file = cert_file; if (!key_file) { tcn_Throw(e, "No Certificate file specified"); rv = JNI_FALSE; goto cleanup; } if ((c->keys[idx] = load_pem_key(c, key_file)) == NULL) { ERR_error_string(ERR_get_error(), err); tcn_Throw(e, "Unable to load certificate key %s (%s)", key_file, err); rv = JNI_FALSE; goto cleanup; } if ((c->certs[idx] = load_pem_cert(cert_file)) == NULL) { ERR_error_string(ERR_get_error(), err); tcn_Throw(e, "Unable to load certificate %s (%s)", cert_file, err); rv = JNI_FALSE; goto cleanup; } if (SSL_CTX_use_certificate(c->ctx, c->certs[idx]) <= 0) { ERR_error_string(ERR_get_error(), err); tcn_Throw(e, "Error setting certificate (%s)", err); rv = JNI_FALSE; goto cleanup; } if (SSL_CTX_use_PrivateKey(c->ctx, c->keys[idx]) <= 0) { ERR_error_string(ERR_get_error(), err); tcn_Throw(e, "Error setting private key (%s)", err); rv = JNI_FALSE; goto cleanup; } if (SSL_CTX_check_private_key(c->ctx) <= 0) { ERR_error_string(ERR_get_error(), err); tcn_Throw(e, "Private key does not match the certificate public key (%s)", err); rv = JNI_FALSE; goto cleanup; } cleanup: TCN_FREE_CSTRING(cert); TCN_FREE_CSTRING(key); TCN_FREE_CSTRING(password); return rv; } #else /* OpenSSL is not supported. * Create empty stubs. */ TCN_IMPLEMENT_CALL(jlong, SSLContext, make)(TCN_STDARGS, jlong pool, jint protocol, jint mode) { UNREFERENCED_STDARGS; UNREFERENCED(pool); UNREFERENCED(protocol); UNREFERENCED(mode); return 0; } TCN_IMPLEMENT_CALL(jint, SSLContext, free)(TCN_STDARGS, jlong ctx) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); } TCN_IMPLEMENT_CALL(void, SSLContext, setContextId)(TCN_STDARGS, jlong ctx, jstring id) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(id); } TCN_IMPLEMENT_CALL(void, SSLContext, setBIO)(TCN_STDARGS, jlong ctx, jlong bio, jint dir) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(bio); UNREFERENCED(dir); } TCN_IMPLEMENT_CALL(void, SSLContext, setOptions)(TCN_STDARGS, jlong ctx, jint opt) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(opt); } TCN_IMPLEMENT_CALL(void, SSLContext, setQuietShutdown)(TCN_STDARGS, jlong ctx, jboolean mode) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(mode); } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCipherSuite)(TCN_STDARGS, jlong ctx, jstring ciphers) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(ciphers); return JNI_FALSE; } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCARevocation)(TCN_STDARGS, jlong ctx, jstring file, jstring path) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(file); UNREFERENCED(path); return JNI_FALSE; } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCertificateChainFile)(TCN_STDARGS, jlong ctx, jstring file, jboolean skipfirst) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(file); UNREFERENCED(skipfirst); return JNI_FALSE; } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCACertificate)(TCN_STDARGS, jlong ctx, jstring file, jstring path) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(file); UNREFERENCED(path); return JNI_FALSE; } TCN_IMPLEMENT_CALL(void, SSLContext, setShutdownType)(TCN_STDARGS, jlong ctx, jint type) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(type); } TCN_IMPLEMENT_CALL(void, SSLContext, setVerify)(TCN_STDARGS, jlong ctx, jint level, jint depth) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(level); UNREFERENCED(depth); } TCN_IMPLEMENT_CALL(void, SSLContext, setRandom)(TCN_STDARGS, jlong ctx, jstring file) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(file); } TCN_IMPLEMENT_CALL(jboolean, SSLContext, setCertificate)(TCN_STDARGS, jlong ctx, jstring cert, jstring key, jstring password, jint idx) { UNREFERENCED_STDARGS; UNREFERENCED(ctx); UNREFERENCED(cert); UNREFERENCED(key); UNREFERENCED(password); UNREFERENCED(idx); return JNI_FALSE; } #endif
supercj92/tomcat6
native/connector/include/tcn_api.h
<filename>native/connector/include/tcn_api.h<gh_stars>0 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * * @author <NAME> * @version $Revision: 466609 $, $Date: 2006-10-22 01:30:39 +0200 (dim., 22 oct. 2006) $ */ #ifndef TCN_API_H #define TCN_API_H #include "apr.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_portable.h" #include "apr_network_io.h" #include "apr_strings.h" #ifndef APR_HAS_THREADS #error "Missing APR_HAS_THREADS support from APR." #endif #include <jni.h> /** * TCN_DECLARE_EXPORT is defined when building the TCN dynamic library, * so that all public symbols are exported. * * TCN_DECLARE_STATIC is defined when including the TCN public headers, * to provide static linkage when the dynamic library may be unavailable. * * TCN_DECLARE_STATIC and TCN_DECLARE_EXPORT are left undefined when * including the TCN public headers, to import and link the symbols from * the dynamic TCN library and assure appropriate indirection and calling * conventions at compile time. */ #if !defined(WIN32) /** * The public TCN functions are declared with TCN_DECLARE(), so they may * use the most appropriate calling convention. Public APR functions with * variable arguments must use TCN_DECLARE_NONSTD(). * * @deffunc TCN_DECLARE(rettype) apr_func(args); */ #define TCN_DECLARE(type) type /** * The public TCN functions using variable arguments are declared with * TCN_DECLARE_NONSTD(), as they must use the C language calling convention. * * @deffunc TCN_DECLARE_NONSTD(rettype) apr_func(args, ...); */ #define TCN_DECLARE_NONSTD(type) type /** * The public TCN variables are declared with TCN_DECLARE_DATA. * This assures the appropriate indirection is invoked at compile time. * * @deffunc TCN_DECLARE_DATA type apr_variable; * @tip extern TCN_DECLARE_DATA type apr_variable; syntax is required for * declarations within headers to properly import the variable. */ #define TCN_DECLARE_DATA #elif defined(TCN_DECLARE_STATIC) #define TCN_DECLARE(type) type __stdcall #define TCN_DECLARE_NONSTD(type) type #define TCN_DECLARE_DATA #elif defined(TCN_DECLARE_EXPORT) #define TCN_DECLARE(type) __declspec(dllexport) type __stdcall #define TCN_DECLARE_NONSTD(type) __declspec(dllexport) type #define TCN_DECLARE_DATA __declspec(dllexport) #else /** * The public TCN functions are declared with TCN_DECLARE(), so they may * use the most appropriate calling convention. Public APR functions with * variable arguments must use TCN_DECLARE_NONSTD(). * */ #define TCN_DECLARE(type) __declspec(dllimport) type __stdcall /** * The public TCN functions using variable arguments are declared with * TCN_DECLARE_NONSTD(), as they must use the C language calling convention. * */ #define TCN_DECLARE_NONSTD(type) __declspec(dllimport) type /** * The public TCN variables are declared with TCN_DECLARE_DATA. * This assures the appropriate indirection is invoked at compile time. * * @remark extern TCN_DECLARE_DATA type apr_variable; syntax is required for * declarations within headers to properly import the variable. */ #define TCN_DECLARE_DATA __declspec(dllimport) #endif #if !defined(WIN32) || defined(TCN_MODULE_DECLARE_STATIC) /** * Declare a dso module's exported module structure as TCN_MODULE_DECLARE_DATA. * * Unless TCN_MODULE_DECLARE_STATIC is defined at compile time, symbols * declared with TCN_MODULE_DECLARE_DATA are always exported. * @code * module TCN_MODULE_DECLARE_DATA mod_tag * @endcode */ #if defined(WIN32) #define TCN_MODULE_DECLARE(type) type __stdcall #else #define TCN_MODULE_DECLARE(type) type #endif #define TCN_MODULE_DECLARE_NONSTD(type) type #define TCN_MODULE_DECLARE_DATA #else /** * TCN_MODULE_DECLARE_EXPORT is a no-op. Unless contradicted by the * TCN_MODULE_DECLARE_STATIC compile-time symbol, it is assumed and defined. */ #define TCN_MODULE_DECLARE_EXPORT #define TCN_MODULE_DECLARE(type) __declspec(dllexport) type __stdcall #define TCN_MODULE_DECLARE_NONSTD(type) __declspec(dllexport) type #define TCN_MODULE_DECLARE_DATA __declspec(dllexport) #endif #ifdef __cplusplus extern "C" { #endif /** * @file tcn_api.h * @brief * * Tomcat Native Public API */ /* Return global apr pool */ TCN_DECLARE(apr_pool_t *) tcn_get_global_pool(void); /* Return global String class */ TCN_DECLARE(jclass) tcn_get_string_class(void); /* Return global JVM initalized on JNI_OnLoad */ TCN_DECLARE(JavaVM *) tcn_get_java_vm(void); /* Get current thread JNIEnv */ TCN_DECLARE(jint) tcn_get_java_env(JNIEnv **); #ifdef __cplusplus } #endif #endif /* TCN_API_H */
supercj92/tomcat6
native/connector/os/unix/uxpipe.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /** UNIX AF_LOCAL network wrapper * * @author <NAME> * @version $Revision: 466609 $, $Date: 2006-10-22 01:30:39 +0200 (dim., 22 oct. 2006) $ */ #include "tcn.h" #include "apr_thread_mutex.h" #include "apr_poll.h" /* ### should be tossed in favor of APR */ #include <sys/stat.h> #include <sys/un.h> /* for sockaddr_un */ #ifdef TCN_DO_STATISTICS #include "apr_atomic.h" static volatile apr_uint32_t uxp_created = 0; static volatile apr_uint32_t uxp_closed = 0; static volatile apr_uint32_t uxp_cleared = 0; static volatile apr_uint32_t uxp_accepted = 0; void uxp_network_dump_statistics() { fprintf(stderr, "NT Network Statistics ..\n"); fprintf(stderr, "Sockets created : %d\n", uxp_created); fprintf(stderr, "Sockets accepted : %d\n", uxp_accepted); fprintf(stderr, "Sockets closed : %d\n", uxp_closed); fprintf(stderr, "Sockets cleared : %d\n", uxp_cleared); } #endif #define DEFNAME "/var/run/tomcatnativesock" #define DEFNAME_FMT "/var/run/tomcatnativesock%08x%08x" #define DEFSIZE 8192 #define DEFTIMEOUT 60000 #define TCN_UXP_UNKNOWN 0 #define TCN_UXP_CLIENT 1 #define TCN_UXP_ACCEPTED 2 #define TCN_UXP_SERVER 3 #define TCN_UNIX_MAXPATH 1024 typedef struct { apr_pool_t *pool; apr_socket_t *sock; /* APR socket */ int sd; struct sockaddr_un uxaddr; int timeout; int mode; /* Client or server mode */ char name[TCN_UNIX_MAXPATH+1]; } tcn_uxp_conn_t; static apr_status_t APR_THREAD_FUNC uxp_socket_timeout_set(apr_socket_t *sock, apr_interval_time_t t) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t *)sock; if (t < 0) con->timeout = -1; else con->timeout = (int)(apr_time_as_msec(t)); return APR_SUCCESS; } static apr_status_t APR_THREAD_FUNC uxp_socket_timeout_get(apr_socket_t *sock, apr_interval_time_t *t) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t*)sock; if (con->timeout < 0) *t = -1; else *t = con->timeout * 1000; return APR_SUCCESS; } static APR_INLINE apr_status_t APR_THREAD_FUNC uxp_socket_opt_set(apr_socket_t *sock, apr_int32_t opt, apr_int32_t on) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t *)sock; return apr_socket_opt_set(con->sock, opt, on); } static APR_INLINE apr_status_t APR_THREAD_FUNC uxp_socket_opt_get(apr_socket_t *sock, apr_int32_t opt, apr_int32_t *on) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t *)sock; return apr_socket_opt_get(con->sock, opt, on); } static apr_status_t uxp_cleanup(void *data) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t *)data; if (con) { if (con->sock) { apr_socket_close(con->sock); con->sock = NULL; } if (con->mode == TCN_UXP_SERVER) { unlink(con->name); con->mode = TCN_UXP_UNKNOWN; } } #ifdef TCN_DO_STATISTICS apr_atomic_inc32(&uxp_cleared); #endif return APR_SUCCESS; } static apr_status_t APR_THREAD_FUNC uxp_socket_shutdown(apr_socket_t *sock, apr_shutdown_how_e how) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t *)sock; return apr_socket_shutdown(con->sock, how); } static apr_status_t APR_THREAD_FUNC uxp_socket_close(apr_socket_t *sock) { #ifdef TCN_DO_STATISTICS apr_atomic_inc32(&uxp_closed); #endif return uxp_cleanup(sock); } static apr_status_t APR_THREAD_FUNC uxp_socket_recv(apr_socket_t *sock, char *buf, apr_size_t *len) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t *)sock; return apr_socket_recv(con->sock, buf, len); } static apr_status_t APR_THREAD_FUNC uxp_socket_send(apr_socket_t *sock, const char *buf, apr_size_t *len) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t *)sock; return apr_socket_send(con->sock, buf, len); } static apr_status_t APR_THREAD_FUNC uxp_socket_sendv(apr_socket_t *sock, const struct iovec *vec, apr_int32_t nvec, apr_size_t *len) { tcn_uxp_conn_t *con = (tcn_uxp_conn_t *)sock; return apr_socket_sendv(con->sock, vec, nvec, len); } static apr_status_t uxp_socket_cleanup(void *data) { tcn_socket_t *s = (tcn_socket_t *)data; if (s->net->cleanup) { (*s->net->cleanup)(s->opaque); s->net->cleanup = NULL; } #ifdef TCN_DO_STATISTICS apr_atomic_inc32(&uxp_cleared); #endif return APR_SUCCESS; } static tcn_nlayer_t uxp_socket_layer = { TCN_SOCKET_UNIX, uxp_cleanup, uxp_socket_close, uxp_socket_shutdown, uxp_socket_opt_get, uxp_socket_opt_set, uxp_socket_timeout_get, uxp_socket_timeout_set, uxp_socket_send, uxp_socket_sendv, uxp_socket_recv }; TCN_IMPLEMENT_CALL(jlong, Local, create)(TCN_STDARGS, jstring name, jlong pool) { apr_pool_t *p = J2P(pool, apr_pool_t *); tcn_socket_t *s = NULL; tcn_uxp_conn_t *con = NULL; int sd; TCN_ALLOC_CSTRING(name); UNREFERENCED(o); TCN_ASSERT(pool != 0); if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { tcn_ThrowAPRException(e, apr_get_netos_error()); return 0; } #ifdef TCN_DO_STATISTICS uxp_created++; #endif con = (tcn_uxp_conn_t *)apr_pcalloc(p, sizeof(tcn_uxp_conn_t)); con->pool = p; con->mode = TCN_UXP_UNKNOWN; con->timeout = DEFTIMEOUT; con->sd = sd; con->uxaddr.sun_family = AF_UNIX; if (J2S(name)) { strcpy(con->uxaddr.sun_path, J2S(name)); TCN_FREE_CSTRING(name); } else strcpy(con->uxaddr.sun_path, DEFNAME); s = (tcn_socket_t *)apr_pcalloc(p, sizeof(tcn_socket_t)); s->pool = p; s->net = &uxp_socket_layer; s->opaque = con; apr_pool_cleanup_register(p, (const void *)s, uxp_socket_cleanup, apr_pool_cleanup_null); apr_os_sock_put(&(con->sock), &(con->sd), p); return P2J(s); } TCN_IMPLEMENT_CALL(jint, Local, bind)(TCN_STDARGS, jlong sock, jlong sa) { tcn_socket_t *s = J2P(sock, tcn_socket_t *); UNREFERENCED_STDARGS; UNREFERENCED(sa); TCN_ASSERT(sock != 0); if (s->net->type == TCN_SOCKET_UNIX) { int rc; tcn_uxp_conn_t *c = (tcn_uxp_conn_t *)s->opaque; c->mode = TCN_UXP_SERVER; rc = bind(c->sd, (struct sockaddr *)&(c->uxaddr), sizeof(c->uxaddr)); if (rc < 0) return errno; else return APR_SUCCESS; } else return APR_EINVAL; } TCN_IMPLEMENT_CALL(jint, Local, listen)(TCN_STDARGS, jlong sock, jint backlog) { tcn_socket_t *s = J2P(sock, tcn_socket_t *); UNREFERENCED_STDARGS; TCN_ASSERT(sock != 0); if (s->net->type == TCN_SOCKET_UNIX) { tcn_uxp_conn_t *c = (tcn_uxp_conn_t *)s->opaque; c->mode = TCN_UXP_SERVER; return apr_socket_listen(c->sock, (apr_int32_t)backlog); } else return APR_EINVAL; } TCN_IMPLEMENT_CALL(jlong, Local, accept)(TCN_STDARGS, jlong sock) { tcn_socket_t *s = J2P(sock, tcn_socket_t *); apr_pool_t *p = NULL; tcn_socket_t *a = NULL; tcn_uxp_conn_t *con = NULL; UNREFERENCED(o); TCN_ASSERT(sock != 0); TCN_THROW_IF_ERR(apr_pool_create(&p, s->pool), p); if (s->net->type == TCN_SOCKET_UNIX) { apr_socklen_t len; tcn_uxp_conn_t *c = (tcn_uxp_conn_t *)s->opaque; con = (tcn_uxp_conn_t *)apr_pcalloc(p, sizeof(tcn_uxp_conn_t)); con->pool = p; con->mode = TCN_UXP_ACCEPTED; con->timeout = c->timeout; len = sizeof(c->uxaddr); /* Block until a client connects */ con->sd = accept(c->sd, (struct sockaddr *)&(con->uxaddr), &len); if (con->sd < 0) { tcn_ThrowAPRException(e, apr_get_os_error()); goto cleanup; } } else { tcn_ThrowAPRException(e, APR_ENOTIMPL); goto cleanup; } if (con) { #ifdef TCN_DO_STATISTICS apr_atomic_inc32(&uxp_accepted); #endif a = (tcn_socket_t *)apr_pcalloc(p, sizeof(tcn_socket_t)); a->pool = p; a->net = &uxp_socket_layer; a->opaque = con; apr_pool_cleanup_register(p, (const void *)a, uxp_socket_cleanup, apr_pool_cleanup_null); apr_os_sock_put(&(con->sock), &(con->sd), p); } return P2J(a); cleanup: if (p) apr_pool_destroy(p); return 0; } TCN_IMPLEMENT_CALL(jint, Local, connect)(TCN_STDARGS, jlong sock, jlong sa) { tcn_socket_t *s = J2P(sock, tcn_socket_t *); tcn_uxp_conn_t *con = NULL; int rc; UNREFERENCED(o); UNREFERENCED(sa); TCN_ASSERT(sock != 0); if (s->net->type != TCN_SOCKET_UNIX) return APR_ENOTSOCK; con = (tcn_uxp_conn_t *)s->opaque; if (con->mode != TCN_UXP_UNKNOWN) return APR_EINVAL; do { rc = connect(con->sd, (const struct sockaddr *)&(con->uxaddr), sizeof(con->uxaddr)); } while (rc == -1 && errno == EINTR); if (rc == -1 && errno != EISCONN) return errno; con->mode = TCN_UXP_CLIENT; return APR_SUCCESS; }
davepallot/OSKAR
oskar/sky/src/oskar_sky_copy_source_data.c
<reponame>davepallot/OSKAR /* * Copyright (c) 2014-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "sky/private_sky.h" #include "sky/oskar_sky.h" #include "sky/oskar_sky_copy_source_data.h" #include "sky/oskar_sky_copy_source_data_cuda.h" #include "utility/oskar_cl_utils.h" #include "utility/oskar_device_utils.h" #define CF(m) oskar_mem_float(m, status) #define CFC(m) oskar_mem_float_const(m, status) #define CD(m) oskar_mem_double(m, status) #define CDC(m) oskar_mem_double_const(m, status) #define CCL(m) oskar_mem_cl_buffer(m, status) #define CCLC(m) oskar_mem_cl_buffer_const(m, status) #define ARG_MEM_CONST(m) \ error |= clSetKernelArg(k, arg++, sizeof(cl_mem), CCLC(m)) #define ARG_MEM(m) \ error |= clSetKernelArg(k, arg++, sizeof(cl_mem), CCL(m)) #ifdef __cplusplus extern "C" { #endif #define COPY_SOURCE_DATA \ for (i = 0; i < num_in; ++i) \ if (mask[i]) \ { \ o_ra[num_out] = ra[i]; \ o_dec[num_out] = dec[i]; \ o_I[num_out] = I[i]; \ o_Q[num_out] = Q[i]; \ o_U[num_out] = U[i]; \ o_V[num_out] = V[i]; \ o_ref[num_out] = ref[i]; \ o_sp[num_out] = sp[i]; \ o_rm[num_out] = rm[i]; \ o_l[num_out] = l[i]; \ o_m[num_out] = m[i]; \ o_n[num_out] = n[i]; \ o_a[num_out] = a[i]; \ o_b[num_out] = b[i]; \ o_c[num_out] = c[i]; \ o_maj[num_out] = maj[i]; \ o_min[num_out] = min[i]; \ o_pa[num_out] = pa[i]; \ num_out++; \ } void oskar_sky_copy_source_data(const oskar_Sky* in, const oskar_Mem* horizon_mask, const oskar_Mem* indices, oskar_Sky* out, int* status) { int i, num_in, num_out = 0, location, type; const int *mask; if (*status) return; location = oskar_sky_mem_location(in); type = oskar_sky_precision(out); mask = oskar_mem_int_const(horizon_mask, status); num_in = oskar_sky_num_sources(in); if (location & OSKAR_CL) { #ifdef OSKAR_HAVE_OPENCL cl_event event; cl_kernel k = 0; cl_int error, n_in, n_out = 0; cl_uint arg = 0; size_t global_size, local_size; if (type == OSKAR_DOUBLE) k = oskar_cl_kernel("copy_source_data_double"); else if (type == OSKAR_SINGLE) k = oskar_cl_kernel("copy_source_data_float"); else { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } if (!k) { *status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE; return; } /* Set kernel arguments. */ n_in = (cl_int) num_in; error = clSetKernelArg(k, arg++, sizeof(cl_int), &n_in); ARG_MEM_CONST(horizon_mask); ARG_MEM_CONST(indices); ARG_MEM_CONST(oskar_sky_ra_rad_const(in)); ARG_MEM(oskar_sky_ra_rad(out)); ARG_MEM_CONST(oskar_sky_dec_rad_const(in)); ARG_MEM(oskar_sky_dec_rad(out)); ARG_MEM_CONST(oskar_sky_I_const(in)); ARG_MEM(oskar_sky_I(out)); ARG_MEM_CONST(oskar_sky_Q_const(in)); ARG_MEM(oskar_sky_Q(out)); ARG_MEM_CONST(oskar_sky_U_const(in)); ARG_MEM(oskar_sky_U(out)); ARG_MEM_CONST(oskar_sky_V_const(in)); ARG_MEM(oskar_sky_V(out)); ARG_MEM_CONST(oskar_sky_reference_freq_hz_const(in)); ARG_MEM(oskar_sky_reference_freq_hz(out)); ARG_MEM_CONST(oskar_sky_spectral_index_const(in)); ARG_MEM(oskar_sky_spectral_index(out)); ARG_MEM_CONST(oskar_sky_rotation_measure_rad_const(in)); ARG_MEM(oskar_sky_rotation_measure_rad(out)); ARG_MEM_CONST(oskar_sky_l_const(in)); ARG_MEM(oskar_sky_l(out)); ARG_MEM_CONST(oskar_sky_m_const(in)); ARG_MEM(oskar_sky_m(out)); ARG_MEM_CONST(oskar_sky_n_const(in)); ARG_MEM(oskar_sky_n(out)); ARG_MEM_CONST(oskar_sky_gaussian_a_const(in)); ARG_MEM(oskar_sky_gaussian_a(out)); ARG_MEM_CONST(oskar_sky_gaussian_b_const(in)); ARG_MEM(oskar_sky_gaussian_b(out)); ARG_MEM_CONST(oskar_sky_gaussian_c_const(in)); ARG_MEM(oskar_sky_gaussian_c(out)); ARG_MEM_CONST(oskar_sky_fwhm_major_rad_const(in)); ARG_MEM(oskar_sky_fwhm_major_rad(out)); ARG_MEM_CONST(oskar_sky_fwhm_minor_rad_const(in)); ARG_MEM(oskar_sky_fwhm_minor_rad(out)); ARG_MEM_CONST(oskar_sky_position_angle_rad_const(in)); ARG_MEM(oskar_sky_position_angle_rad(out)); if (error != CL_SUCCESS) { *status = OSKAR_ERR_INVALID_ARGUMENT; return; } /* Launch kernel on current command queue. */ local_size = oskar_cl_is_gpu() ? 256 : 128; global_size = ((n_in + local_size - 1) / local_size) * local_size; error = clEnqueueNDRangeKernel(oskar_cl_command_queue(), k, 1, NULL, &global_size, &local_size, 0, NULL, &event); if (error != CL_SUCCESS) { *status = OSKAR_ERR_KERNEL_LAUNCH_FAILURE; return; } /* Get the number of sources copied. */ error = clEnqueueReadBuffer(oskar_cl_command_queue(), *CCLC(indices), CL_TRUE, (n_in - 1) * sizeof(cl_int), sizeof(cl_int), &n_out, 0, NULL, NULL); if (error != CL_SUCCESS) *status = OSKAR_ERR_MEMORY_COPY_FAILURE; num_out = (int) (n_out + 1); #else *status = OSKAR_ERR_OPENCL_NOT_AVAILABLE; #endif } else { switch (type) { case OSKAR_SINGLE: { const float *ra, *dec, *I, *Q, *U, *V; const float *ref, *sp, *rm, *l, *m, *n; const float *a, *b, *c, *maj, *min, *pa; float *o_ra, *o_dec, *o_I, *o_Q, *o_U, *o_V; float *o_ref, *o_sp, *o_rm, *o_l, *o_m, *o_n; float *o_a, *o_b, *o_c, *o_maj, *o_min, *o_pa; /* Inputs. */ ra = CFC(oskar_sky_ra_rad_const(in)); dec = CFC(oskar_sky_dec_rad_const(in)); I = CFC(oskar_sky_I_const(in)); Q = CFC(oskar_sky_Q_const(in)); U = CFC(oskar_sky_U_const(in)); V = CFC(oskar_sky_V_const(in)); ref = CFC(oskar_sky_reference_freq_hz_const(in)); sp = CFC(oskar_sky_spectral_index_const(in)); rm = CFC(oskar_sky_rotation_measure_rad_const(in)); l = CFC(oskar_sky_l_const(in)); m = CFC(oskar_sky_m_const(in)); n = CFC(oskar_sky_n_const(in)); a = CFC(oskar_sky_gaussian_a_const(in)); b = CFC(oskar_sky_gaussian_b_const(in)); c = CFC(oskar_sky_gaussian_c_const(in)); maj = CFC(oskar_sky_fwhm_major_rad_const(in)); min = CFC(oskar_sky_fwhm_minor_rad_const(in)); pa = CFC(oskar_sky_position_angle_rad_const(in)); /* Outputs. */ o_ra = CF(oskar_sky_ra_rad(out)); o_dec = CF(oskar_sky_dec_rad(out)); o_I = CF(oskar_sky_I(out)); o_Q = CF(oskar_sky_Q(out)); o_U = CF(oskar_sky_U(out)); o_V = CF(oskar_sky_V(out)); o_ref = CF(oskar_sky_reference_freq_hz(out)); o_sp = CF(oskar_sky_spectral_index(out)); o_rm = CF(oskar_sky_rotation_measure_rad(out)); o_l = CF(oskar_sky_l(out)); o_m = CF(oskar_sky_m(out)); o_n = CF(oskar_sky_n(out)); o_a = CF(oskar_sky_gaussian_a(out)); o_b = CF(oskar_sky_gaussian_b(out)); o_c = CF(oskar_sky_gaussian_c(out)); o_maj = CF(oskar_sky_fwhm_major_rad(out)); o_min = CF(oskar_sky_fwhm_minor_rad(out)); o_pa = CF(oskar_sky_position_angle_rad(out)); /* Copy source data. */ if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA oskar_sky_copy_source_data_cuda_f(num_in, &num_out, mask, oskar_mem_int_const(indices, status), ra, o_ra, dec, o_dec, I, o_I, Q, o_Q, U, o_U, V, o_V, ref, o_ref, sp, o_sp, rm, o_rm, l, o_l, m, o_m, n, o_n, a, o_a, b, o_b, c, o_c, maj, o_maj, min, o_min, pa, o_pa); oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location == OSKAR_CPU) { (void) indices; COPY_SOURCE_DATA } else *status = OSKAR_ERR_BAD_LOCATION; break; } case OSKAR_DOUBLE: { const double *ra, *dec, *I, *Q, *U, *V; const double *ref, *sp, *rm, *l, *m, *n; const double *a, *b, *c, *maj, *min, *pa; double *o_ra, *o_dec, *o_I, *o_Q, *o_U, *o_V; double *o_ref, *o_sp, *o_rm, *o_l, *o_m, *o_n; double *o_a, *o_b, *o_c, *o_maj, *o_min, *o_pa; /* Inputs. */ ra = CDC(oskar_sky_ra_rad_const(in)); dec = CDC(oskar_sky_dec_rad_const(in)); I = CDC(oskar_sky_I_const(in)); Q = CDC(oskar_sky_Q_const(in)); U = CDC(oskar_sky_U_const(in)); V = CDC(oskar_sky_V_const(in)); ref = CDC(oskar_sky_reference_freq_hz_const(in)); sp = CDC(oskar_sky_spectral_index_const(in)); rm = CDC(oskar_sky_rotation_measure_rad_const(in)); l = CDC(oskar_sky_l_const(in)); m = CDC(oskar_sky_m_const(in)); n = CDC(oskar_sky_n_const(in)); a = CDC(oskar_sky_gaussian_a_const(in)); b = CDC(oskar_sky_gaussian_b_const(in)); c = CDC(oskar_sky_gaussian_c_const(in)); maj = CDC(oskar_sky_fwhm_major_rad_const(in)); min = CDC(oskar_sky_fwhm_minor_rad_const(in)); pa = CDC(oskar_sky_position_angle_rad_const(in)); /* Outputs. */ o_ra = CD(oskar_sky_ra_rad(out)); o_dec = CD(oskar_sky_dec_rad(out)); o_I = CD(oskar_sky_I(out)); o_Q = CD(oskar_sky_Q(out)); o_U = CD(oskar_sky_U(out)); o_V = CD(oskar_sky_V(out)); o_ref = CD(oskar_sky_reference_freq_hz(out)); o_sp = CD(oskar_sky_spectral_index(out)); o_rm = CD(oskar_sky_rotation_measure_rad(out)); o_l = CD(oskar_sky_l(out)); o_m = CD(oskar_sky_m(out)); o_n = CD(oskar_sky_n(out)); o_a = CD(oskar_sky_gaussian_a(out)); o_b = CD(oskar_sky_gaussian_b(out)); o_c = CD(oskar_sky_gaussian_c(out)); o_maj = CD(oskar_sky_fwhm_major_rad(out)); o_min = CD(oskar_sky_fwhm_minor_rad(out)); o_pa = CD(oskar_sky_position_angle_rad(out)); /* Copy source data. */ if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA oskar_sky_copy_source_data_cuda_d(num_in, &num_out, mask, oskar_mem_int_const(indices, status), ra, o_ra, dec, o_dec, I, o_I, Q, o_Q, U, o_U, V, o_V, ref, o_ref, sp, o_sp, rm, o_rm, l, o_l, m, o_m, n, o_n, a, o_a, b, o_b, c, o_c, maj, o_maj, min, o_min, pa, o_pa); oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location == OSKAR_CPU) { (void) indices; COPY_SOURCE_DATA } else *status = OSKAR_ERR_BAD_LOCATION; break; } default: *status = OSKAR_ERR_BAD_DATA_TYPE; break; } } /* Copy metadata. */ out->use_extended = in->use_extended; out->reference_ra_rad = in->reference_ra_rad; out->reference_dec_rad = in->reference_dec_rad; /* Set the number of sources in the output sky model. */ out->num_sources = num_out; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/convert/src/oskar_convert_brightness_to_jy.c
<reponame>davepallot/OSKAR /* * Copyright (c) 2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "convert/oskar_convert_brightness_to_jy.h" #include <string.h> #ifdef __cplusplus extern "C" { #endif enum MAP_UNITS { MK, K, JY_BEAM, JY_PIXEL }; void oskar_convert_brightness_to_jy(oskar_Mem* data, double beam_area_pixels, double pixel_area_sr, double frequency_hz, double min_peak_fraction, double min_abs_val, const char* reported_map_units, const char* default_map_units, int override_input_units, int* status) { static const double k_B = 1.3806488e-23; /* Boltzmann constant. */ double lambda, peak = 0.0, peak_min = 0.0, scaling = 1.0, val = 0.0; const char* unit_str = 0; int i = 0, num_pixels, units = 0, type; if (*status) return; /* Filter and find peak of image. */ num_pixels = (int) oskar_mem_length(data); type = oskar_mem_precision(data); if (type == OSKAR_SINGLE) { float *img = oskar_mem_float(data, status); for (i = 0; i < num_pixels; ++i) { val = img[i]; if (val > peak) peak = val; } peak_min = peak * min_peak_fraction; for (i = 0; i < num_pixels; ++i) { val = img[i]; if (val < peak_min || val < min_abs_val) img[i] = 0.0; } } else { double *img = oskar_mem_double(data, status); for (i = 0; i < num_pixels; ++i) { val = img[i]; if (val > peak) peak = val; } peak_min = peak * min_peak_fraction; for (i = 0; i < num_pixels; ++i) { val = img[i]; if (val < peak_min || val < min_abs_val) img[i] = 0.0; } } /* Find brightness units. */ unit_str = (!reported_map_units || override_input_units) ? default_map_units : reported_map_units; if (!strncmp(unit_str, "JY/BEAM", 7) || !strncmp(unit_str, "Jy/beam", 7)) units = JY_BEAM; else if (!strncmp(unit_str, "JY/PIXEL", 8) || !strncmp(unit_str, "Jy/pixel", 8)) units = JY_PIXEL; else if (!strncmp(unit_str, "mK", 2)) units = MK; else if (!strncmp(unit_str, "K", 1)) units = K; else *status = OSKAR_ERR_BAD_UNITS; /* Check if we need to convert the pixel values. */ if (units == JY_BEAM) { if (beam_area_pixels == 0.0) { fprintf(stderr, "Need beam area for maps in Jy/beam.\n"); *status = OSKAR_ERR_BAD_UNITS; } else scaling = 1.0 / beam_area_pixels; } else if (units == K || units == MK) { if (units == MK) scaling = 1e-3; /* Convert milli-Kelvin to Kelvin. */ /* Convert temperature to Jansky per pixel. */ /* Brightness temperature to flux density conversion: * http://www.iram.fr/IRAMFR/IS/IS2002/html_1/node187.html */ /* Multiply by 2.0 * k_B * pixel_area * 10^26 / lambda^2. */ lambda = 299792458.0 / frequency_hz; scaling *= (2.0 * k_B * pixel_area_sr * 1e26 / (lambda*lambda)); } /* Scale pixels into Jy. */ if (scaling != 1.0) oskar_mem_scale_real(data, scaling, status); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/sky/src/oskar_sky_scale_flux_with_frequency.c
/* * Copyright (c) 2011-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "sky/oskar_sky.h" #include "sky/oskar_sky_scale_flux_with_frequency_cuda.h" #include "sky/private_sky_scale_flux_with_frequency_inline.h" #include "utility/oskar_cl_utils.h" #include "utility/oskar_device_utils.h" #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_sky_scale_flux_with_frequency_f(int num_sources, float frequency, float* I, float* Q, float* U, float* V, float* ref_freq, const float* sp_index, const float* rm) { int i; for (i = 0; i < num_sources; ++i) { oskar_scale_flux_with_frequency_inline_f(frequency, &I[i], &Q[i], &U[i], &V[i], &ref_freq[i], sp_index[i], rm[i]); } } /* Double precision. */ void oskar_sky_scale_flux_with_frequency_d(int num_sources, double frequency, double* I, double* Q, double* U, double* V, double* ref_freq, const double* sp_index, const double* rm) { int i; for (i = 0; i < num_sources; ++i) { oskar_scale_flux_with_frequency_inline_d(frequency, &I[i], &Q[i], &U[i], &V[i], &ref_freq[i], sp_index[i], rm[i]); } } /* Wrapper. */ void oskar_sky_scale_flux_with_frequency(oskar_Sky* sky, double frequency, int* status) { int type, location, num_sources; /* Check if safe to proceed. */ if (*status) return; /* Get the type, location and dimensions. */ type = oskar_sky_precision(sky); location = oskar_sky_mem_location(sky); num_sources = oskar_sky_num_sources(sky); /* Scale the flux values. */ if (location == OSKAR_CPU) { if (type == OSKAR_SINGLE) oskar_sky_scale_flux_with_frequency_f(num_sources, frequency, oskar_mem_float(oskar_sky_I(sky), status), oskar_mem_float(oskar_sky_Q(sky), status), oskar_mem_float(oskar_sky_U(sky), status), oskar_mem_float(oskar_sky_V(sky), status), oskar_mem_float(oskar_sky_reference_freq_hz(sky), status), oskar_mem_float_const( oskar_sky_spectral_index_const(sky), status), oskar_mem_float_const( oskar_sky_rotation_measure_rad_const(sky), status)); else if (type == OSKAR_DOUBLE) oskar_sky_scale_flux_with_frequency_d(num_sources, frequency, oskar_mem_double(oskar_sky_I(sky), status), oskar_mem_double(oskar_sky_Q(sky), status), oskar_mem_double(oskar_sky_U(sky), status), oskar_mem_double(oskar_sky_V(sky), status), oskar_mem_double(oskar_sky_reference_freq_hz(sky), status), oskar_mem_double_const( oskar_sky_spectral_index_const(sky), status), oskar_mem_double_const( oskar_sky_rotation_measure_rad_const(sky), status)); else *status = OSKAR_ERR_BAD_DATA_TYPE; } else if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA if (type == OSKAR_SINGLE) oskar_sky_scale_flux_with_frequency_cuda_f(num_sources, frequency, oskar_mem_float(oskar_sky_I(sky), status), oskar_mem_float(oskar_sky_Q(sky), status), oskar_mem_float(oskar_sky_U(sky), status), oskar_mem_float(oskar_sky_V(sky), status), oskar_mem_float(oskar_sky_reference_freq_hz(sky), status), oskar_mem_float_const( oskar_sky_spectral_index_const(sky), status), oskar_mem_float_const( oskar_sky_rotation_measure_rad_const(sky), status)); else if (type == OSKAR_DOUBLE) oskar_sky_scale_flux_with_frequency_cuda_d(num_sources, frequency, oskar_mem_double(oskar_sky_I(sky), status), oskar_mem_double(oskar_sky_Q(sky), status), oskar_mem_double(oskar_sky_U(sky), status), oskar_mem_double(oskar_sky_V(sky), status), oskar_mem_double(oskar_sky_reference_freq_hz(sky), status), oskar_mem_double_const( oskar_sky_spectral_index_const(sky), status), oskar_mem_double_const( oskar_sky_rotation_measure_rad_const(sky), status)); else *status = OSKAR_ERR_BAD_DATA_TYPE; oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location & OSKAR_CL) { #ifdef OSKAR_HAVE_OPENCL cl_event event; cl_kernel k = 0; cl_int error, num; cl_uint arg = 0; size_t global_size, local_size; if (type == OSKAR_DOUBLE) k = oskar_cl_kernel("scale_flux_with_frequency_double"); else if (type == OSKAR_SINGLE) k = oskar_cl_kernel("scale_flux_with_frequency_float"); else { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } if (!k) { *status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE; return; } /* Set kernel arguments. */ num = (cl_int) num_sources; error = clSetKernelArg(k, arg++, sizeof(cl_int), &num); if (type == OSKAR_SINGLE) { const cl_float freq = (cl_float) frequency; error |= clSetKernelArg(k, arg++, sizeof(cl_float), &freq); } else if (type == OSKAR_DOUBLE) { const cl_double freq = (cl_double) frequency; error |= clSetKernelArg(k, arg++, sizeof(cl_double), &freq); } error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer(oskar_sky_I(sky), status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer(oskar_sky_Q(sky), status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer(oskar_sky_U(sky), status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer(oskar_sky_V(sky), status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer(oskar_sky_reference_freq_hz(sky), status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer_const(oskar_sky_spectral_index_const(sky), status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer_const(oskar_sky_rotation_measure_rad_const(sky), status)); if (error != CL_SUCCESS) { *status = OSKAR_ERR_INVALID_ARGUMENT; return; } /* Launch kernel on current command queue. */ local_size = oskar_cl_is_gpu() ? 256 : 128; global_size = ((num + local_size - 1) / local_size) * local_size; error = clEnqueueNDRangeKernel(oskar_cl_command_queue(), k, 1, NULL, &global_size, &local_size, 0, NULL, &event); if (error != CL_SUCCESS) *status = OSKAR_ERR_KERNEL_LAUNCH_FAILURE; #else *status = OSKAR_ERR_OPENCL_NOT_AVAILABLE; #endif } else *status = OSKAR_ERR_BAD_LOCATION; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/mem/src/oskar_mem_multiply.c
<gh_stars>1-10 /* * Copyright (c) 2012-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "mem/oskar_mem.h" #include "mem/oskar_mem_multiply_cuda.h" #include "mem/private_mem.h" #include "math/oskar_multiply_inline.h" #include "utility/oskar_cl_utils.h" #include "utility/oskar_device_utils.h" #include <stdio.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_mem_multiply_rr_r_f(size_t num, float* c, const float* a, const float* b) { size_t i; for (i = 0; i < num; ++i) { c[i] = a[i] * b[i]; } } void oskar_mem_multiply_cc_c_f(size_t num, float2* c, const float2* a, const float2* b) { size_t i; for (i = 0; i < num; ++i) { float2 ac, bc, cc; ac = a[i]; bc = b[i]; oskar_multiply_complex_f(&cc, &ac, &bc); c[i] = cc; } } void oskar_mem_multiply_cc_m_f(size_t num, float4c* c, const float2* a, const float2* b) { size_t i; for (i = 0; i < num; ++i) { float2 cc; float4c m; oskar_multiply_complex_f(&cc, &a[i], &b[i]); /* Store result in a matrix. */ m.a = cc; m.b.x = 0.0f; m.b.y = 0.0f; m.c.x = 0.0f; m.c.y = 0.0f; m.d = cc; c[i] = m; } } void oskar_mem_multiply_cm_m_f(size_t num, float4c* c, const float2* a, const float4c* b) { size_t i; for (i = 0; i < num; ++i) { float2 ac; float4c bc; ac = a[i]; bc = b[i]; oskar_multiply_complex_matrix_complex_scalar_in_place_f(&bc, &ac); c[i] = bc; } } void oskar_mem_multiply_mm_m_f(size_t num, float4c* c, const float4c* a, const float4c* b) { size_t i; for (i = 0; i < num; ++i) { float4c ac, bc; ac = a[i]; bc = b[i]; oskar_multiply_complex_matrix_in_place_f(&ac, &bc); c[i] = ac; } } /* Double precision. */ void oskar_mem_multiply_rr_r_d(size_t num, double* c, const double* a, const double* b) { size_t i; for (i = 0; i < num; ++i) { c[i] = a[i] * b[i]; } } void oskar_mem_multiply_cc_c_d(size_t num, double2* c, const double2* a, const double2* b) { size_t i; for (i = 0; i < num; ++i) { double2 ac, bc, cc; ac = a[i]; bc = b[i]; oskar_multiply_complex_d(&cc, &ac, &bc); c[i] = cc; } } void oskar_mem_multiply_cc_m_d(size_t num, double4c* c, const double2* a, const double2* b) { size_t i; for (i = 0; i < num; ++i) { double2 cc; double4c m; oskar_multiply_complex_d(&cc, &a[i], &b[i]); /* Store result in a matrix. */ m.a = cc; m.b.x = 0.0; m.b.y = 0.0; m.c.x = 0.0; m.c.y = 0.0; m.d = cc; c[i] = m; } } void oskar_mem_multiply_cm_m_d(size_t num, double4c* c, const double2* a, const double4c* b) { size_t i; for (i = 0; i < num; ++i) { double2 ac; double4c bc; ac = a[i]; bc = b[i]; oskar_multiply_complex_matrix_complex_scalar_in_place_d(&bc, &ac); c[i] = bc; } } void oskar_mem_multiply_mm_m_d(size_t num, double4c* c, const double4c* a, const double4c* b) { size_t i; for (i = 0; i < num; ++i) { double4c ac, bc; ac = a[i]; bc = b[i]; oskar_multiply_complex_matrix_in_place_d(&ac, &bc); c[i] = ac; } } void oskar_mem_multiply(oskar_Mem* c, oskar_Mem* a, const oskar_Mem* b, size_t num, int* status) { oskar_Mem *a_temp = 0, *b_temp = 0; const oskar_Mem *a_, *b_; /* Pointers. */ int use_cpu, use_cuda, use_opencl; #ifdef OSKAR_HAVE_OPENCL cl_kernel k = 0; #endif /* Check if safe to proceed. */ if (*status) return; /* Set default pointer values. */ a_ = a; b_ = b; /* Set output to 'a' if not set. */ if (!c) c = a; /* Set the number of elements to multiply. */ if (num == 0) num = a->num_elements; if (num == 0) return; /* Check that there are enough elements. */ if (b->num_elements < num || c->num_elements < num) { *status = OSKAR_ERR_DIMENSION_MISMATCH; return; } /* Create a temporary copy of the input data if required. */ use_cpu = (oskar_mem_location(c) == OSKAR_CPU); use_cuda = (oskar_mem_location(c) == OSKAR_GPU); use_opencl = (oskar_mem_location(c) & OSKAR_CL); #ifndef OSKAR_HAVE_CUDA if (use_cuda) { *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; return; } #endif #ifndef OSKAR_HAVE_OPENCL if (use_opencl) { *status = OSKAR_ERR_OPENCL_NOT_AVAILABLE; return; } #endif if (use_cpu && oskar_mem_location(a) != OSKAR_CPU) { a_temp = oskar_mem_create_copy(a, OSKAR_CPU, status); a_ = a_temp; } if (use_cpu && oskar_mem_location(b) != OSKAR_CPU) { b_temp = oskar_mem_create_copy(b, OSKAR_CPU, status); b_ = b_temp; } if (use_cuda && oskar_mem_location(a) != OSKAR_GPU) { a_temp = oskar_mem_create_copy(a, OSKAR_GPU, status); a_ = a_temp; } if (use_cuda && oskar_mem_location(b) != OSKAR_GPU) { b_temp = oskar_mem_create_copy(b, OSKAR_GPU, status); b_ = b_temp; } if (use_opencl && !(oskar_mem_location(a) & OSKAR_CL)) { a_temp = oskar_mem_create_copy(a, OSKAR_CL, status); a_ = a_temp; } if (use_opencl && !(oskar_mem_location(b) & OSKAR_CL)) { b_temp = oskar_mem_create_copy(b, OSKAR_CL, status); b_ = b_temp; } /* Multiply each element of the vectors. */ /* Early return if types are all the same. */ if (c->type == a_->type && c->type == b_->type) { switch (c->type) { case OSKAR_DOUBLE: #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_rr_r_d((int)num, (double*)c->data, (const double*)a_->data, (const double*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_rr_r_double"); else #endif oskar_mem_multiply_rr_r_d(num, (double*)c->data, (const double*)a_->data, (const double*)b_->data); break; case OSKAR_DOUBLE_COMPLEX: #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_cc_c_d((int)num, (double2*)c->data, (const double2*)a_->data, (const double2*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_cc_c_double"); else #endif oskar_mem_multiply_cc_c_d(num, (double2*)c->data, (const double2*)a_->data, (const double2*)b_->data); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_mm_m_d((int)num, (double4c*)c->data, (const double4c*)a_->data, (const double4c*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_mm_m_double"); else #endif oskar_mem_multiply_mm_m_d(num, (double4c*)c->data, (const double4c*)a_->data, (const double4c*)b_->data); break; case OSKAR_SINGLE: #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_rr_r_f((int)num, (float*)c->data, (const float*)a_->data, (const float*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_rr_r_float"); else #endif oskar_mem_multiply_rr_r_f(num, (float*)c->data, (const float*)a_->data, (const float*)b_->data); break; case OSKAR_SINGLE_COMPLEX: #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_cc_c_f((int)num, (float2*)c->data, (const float2*)a_->data, (const float2*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_cc_c_float"); else #endif oskar_mem_multiply_cc_c_f(num, (float2*)c->data, (const float2*)a_->data, (const float2*)b_->data); break; case OSKAR_SINGLE_COMPLEX_MATRIX: #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_mm_m_f((int)num, (float4c*)c->data, (const float4c*)a_->data, (const float4c*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_mm_m_float"); else #endif oskar_mem_multiply_mm_m_f(num, (float4c*)c->data, (const float4c*)a_->data, (const float4c*)b_->data); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; break; } goto done; } /* Check for allowed mixed types. */ switch (c->type) { case OSKAR_DOUBLE_COMPLEX_MATRIX: { double4c* out = (double4c*)c->data; switch (a_->type) { case OSKAR_DOUBLE_COMPLEX: { const double2* in_a = (const double2*)a_->data; if (b_->type == a_->type) { #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_cc_m_d((int)num, out, in_a, (const double2*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_cc_m_double"); else #endif oskar_mem_multiply_cc_m_d(num, out, in_a, (const double2*)b_->data); } else if (b_->type == c->type) { #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_cm_m_d((int)num, out, in_a, (const double4c*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_cm_m_double"); else #endif oskar_mem_multiply_cm_m_d(num, out, in_a, (const double4c*)b_->data); } else *status = OSKAR_ERR_TYPE_MISMATCH; break; } case OSKAR_DOUBLE_COMPLEX_MATRIX: { if (b_->type == OSKAR_DOUBLE_COMPLEX) { const double2* in_b = (const double2*)b_->data; #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_cm_m_d((int)num, out, in_b, (const double4c*)a_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_mc_m_double"); else #endif oskar_mem_multiply_cm_m_d(num, out, in_b, (const double4c*)a_->data); } else *status = OSKAR_ERR_TYPE_MISMATCH; break; } default: *status = OSKAR_ERR_TYPE_MISMATCH; break; } break; } case OSKAR_SINGLE_COMPLEX_MATRIX: { float4c* out = (float4c*)c->data; switch (a_->type) { case OSKAR_SINGLE_COMPLEX: { const float2* in_a = (const float2*)a_->data; if (b_->type == a_->type) { #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_cc_m_f((int)num, out, in_a, (const float2*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_cc_m_float"); else #endif oskar_mem_multiply_cc_m_f(num, out, in_a, (const float2*)b_->data); } else if (b_->type == c->type) { #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_cm_m_f((int)num, out, in_a, (const float4c*)b_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_cm_m_float"); else #endif oskar_mem_multiply_cm_m_f(num, out, in_a, (const float4c*)b_->data); } else *status = OSKAR_ERR_TYPE_MISMATCH; break; } case OSKAR_SINGLE_COMPLEX_MATRIX: { if (b_->type == OSKAR_SINGLE_COMPLEX) { const float2* in_b = (const float2*)b_->data; #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_mem_multiply_cuda_cm_m_f((int)num, out, in_b, (const float4c*)a_->data); else #endif #ifdef OSKAR_HAVE_OPENCL if (use_opencl) k = oskar_cl_kernel("mem_multiply_mc_m_float"); else #endif oskar_mem_multiply_cm_m_f(num, out, in_b, (const float4c*)a_->data); } else *status = OSKAR_ERR_TYPE_MISMATCH; break; } default: *status = OSKAR_ERR_TYPE_MISMATCH; break; } break; } default: *status = OSKAR_ERR_TYPE_MISMATCH; break; } done: #ifdef OSKAR_HAVE_OPENCL /* Call OpenCL kernel if required. */ if (use_opencl && !*status) { if (k) { cl_device_type dev_type; cl_int error, gpu = 1, n; size_t global_size, local_size; /* Set kernel arguments. */ clGetDeviceInfo(oskar_cl_device_id(), CL_DEVICE_TYPE, sizeof(cl_device_type), &dev_type, NULL); gpu = dev_type & CL_DEVICE_TYPE_GPU; n = (cl_int) num; error = clSetKernelArg(k, 0, sizeof(cl_int), &n); error |= clSetKernelArg(k, 1, sizeof(cl_mem), oskar_mem_cl_buffer_const(a_, status)); error |= clSetKernelArg(k, 2, sizeof(cl_mem), oskar_mem_cl_buffer_const(b_, status)); error |= clSetKernelArg(k, 3, sizeof(cl_mem), oskar_mem_cl_buffer(c, status)); if (*status) return; if (error != CL_SUCCESS) { *status = OSKAR_ERR_INVALID_ARGUMENT; return; } /* Launch kernel on current command queue. */ local_size = gpu ? 256 : 128; global_size = ((num + local_size - 1) / local_size) * local_size; error = clEnqueueNDRangeKernel(oskar_cl_command_queue(), k, 1, NULL, &global_size, &local_size, 0, NULL, NULL); if (error != CL_SUCCESS) { *status = OSKAR_ERR_KERNEL_LAUNCH_FAILURE; return; } } else { *status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE; } } #endif /* Free temporary arrays. */ #ifdef OSKAR_HAVE_CUDA if (use_cuda) oskar_device_check_error(status); #endif oskar_mem_free(a_temp, status); oskar_mem_free(b_temp, status); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/vis/src/oskar_vis_block_copy.c
/* * Copyright (c) 2015-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "vis/private_vis_block.h" #include "vis/oskar_vis_block.h" #ifdef __cplusplus extern "C" { #endif void oskar_vis_block_copy(oskar_VisBlock* dst, const oskar_VisBlock* src, int* status) { /* Check if safe to proceed. */ if (*status) return; /* Copy the meta-data. */ dst->dim_start_size[0] = src->dim_start_size[0]; dst->dim_start_size[1] = src->dim_start_size[1]; dst->dim_start_size[2] = src->dim_start_size[2]; dst->dim_start_size[3] = src->dim_start_size[3]; dst->dim_start_size[4] = src->dim_start_size[4]; dst->dim_start_size[5] = src->dim_start_size[5]; dst->has_auto_correlations = src->has_auto_correlations; dst->has_cross_correlations = src->has_cross_correlations; /* Copy the memory. */ oskar_mem_copy(dst->baseline_uu_metres, src->baseline_uu_metres, status); oskar_mem_copy(dst->baseline_vv_metres, src->baseline_vv_metres, status); oskar_mem_copy(dst->baseline_ww_metres, src->baseline_ww_metres, status); oskar_mem_copy(dst->auto_correlations, src->auto_correlations, status); oskar_mem_copy(dst->cross_correlations, src->cross_correlations, status); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/utility/src/oskar_scan_binary_file.c
/* * Copyright (c) 2012-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "utility/oskar_scan_binary_file.h" /* FIXME Remove? */ #include "binary/private_binary.h" #include "vis/oskar_vis.h" #include "sky/oskar_sky.h" #include "log/oskar_log.h" #include "binary/oskar_binary.h" #include "mem/oskar_binary_read_mem.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif void oskar_scan_binary_file(oskar_Log* log, const char* filename, int* status) { int extended_tags = 0, depth = -4, i, tag_not_present = 0; oskar_Binary* h = NULL; oskar_Mem* temp = 0; char p = 'M'; /* Log entry priority */ /* Check if safe to proceed. */ if (*status) return; /* Open the file. */ h = oskar_binary_create(filename, 'r', status); if (*status) { oskar_binary_free(h); return; } /* Log file header data. */ oskar_log_section(log, p, "File header in '%s'", filename); oskar_log_value(log, p, 1, "Binary file format version", "%d", h->bin_version); oskar_log_line(log, p, ' '); oskar_log_message(log, p, 0, "File contains %d chunks.", h->num_chunks); /* Display the run log if it is present. */ temp = oskar_mem_create(OSKAR_CHAR, OSKAR_CPU, 0, status); oskar_binary_read_mem(h, temp, OSKAR_TAG_GROUP_RUN, OSKAR_TAG_RUN_LOG, 0, &tag_not_present); oskar_mem_realloc(temp, oskar_mem_length(temp) + 1, status); oskar_mem_char(temp)[oskar_mem_length(temp) - 1] = 0; /* Null-terminate. */ if (!tag_not_present) { oskar_log_section(log, p, "Run log:"); oskar_log_message(log, p, -1, "\n%s", oskar_mem_char(temp)); } oskar_mem_free(temp, status); /* Iterate all tags in index. */ oskar_log_section(log, p, "Standard tags:"); oskar_log_message(log, p, -1, "[%3s] %-23s %5s.%-3s : %-10s (%s)", "ID", "TYPE", "GROUP", "TAG", "INDEX", "BYTES"); oskar_log_message(log, p, depth, "CONTENTS"); oskar_log_line(log, p, '-'); for (i = 0; i < h->num_chunks; ++i) { /* Check if any tags are extended. */ if (h->extended[i]) extended_tags++; else { char group, tag, type; int idx; size_t bytes; /* Get the tag data. */ group = (char) (h->id_group[i]); tag = (char) (h->id_tag[i]); type = (char) (h->data_type[i]); idx = h->user_index[i]; bytes = h->payload_size_bytes[i]; temp = oskar_mem_create(type, OSKAR_CPU, 0, status); /* Display tag data. */ oskar_log_message(log, p, -1, "[%3d] %-23s %5d.%-3d : %-10d (%ld bytes)", i, oskar_mem_data_type_string(type), group, tag, idx, bytes); /* Display more info if available. */ if (group == OSKAR_TAG_GROUP_METADATA) { if (tag == OSKAR_TAG_METADATA_DATE_TIME_STRING) { oskar_binary_read_mem(h, temp, group, tag, idx, status); oskar_log_message(log, p, depth, "Date: %s", oskar_mem_char(temp)); } else if (tag == OSKAR_TAG_METADATA_OSKAR_VERSION_STRING) { oskar_binary_read_mem(h, temp, group, tag, idx, status); oskar_log_message(log, p, depth, "OSKAR version: %s", oskar_mem_char(temp)); } else if (tag == OSKAR_TAG_METADATA_CWD) { oskar_binary_read_mem(h, temp, group, tag, idx, status); oskar_log_message(log, p, depth, "Working directory: %s", oskar_mem_char(temp)); } else if (tag == OSKAR_TAG_METADATA_USERNAME) { oskar_binary_read_mem(h, temp, group, tag, idx, status); oskar_log_message(log, p, depth, "Username: %s", oskar_mem_char(temp)); } } else if (group == OSKAR_TAG_GROUP_SETTINGS) { if (tag == OSKAR_TAG_SETTINGS) { oskar_log_message(log, p, depth, "Settings file"); } else if (tag == OSKAR_TAG_SETTINGS_PATH) { oskar_binary_read_mem(h, temp, group, tag, idx, status); oskar_log_message(log, p, depth, "Settings file path: %s", oskar_mem_char(temp)); } } else if (group == OSKAR_TAG_GROUP_RUN) { if (tag == OSKAR_TAG_RUN_LOG) { oskar_log_message(log, p, depth, "Run log"); } } else if (group == OSKAR_TAG_GROUP_VISIBILITY) { if (tag == OSKAR_VIS_TAG_TELESCOPE_PATH) { oskar_binary_read_mem(h, temp, group, tag, idx, status); oskar_log_message(log, p, depth, "Telescope model path: %s", oskar_mem_char(temp)); } else if (tag == OSKAR_VIS_TAG_NUM_CHANNELS) { int val = 0; oskar_binary_read_int(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Number of channels: %d", val); } else if (tag == OSKAR_VIS_TAG_NUM_TIMES) { int val = 0; oskar_binary_read_int(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Number of times: %d", val); } else if (tag == OSKAR_VIS_TAG_NUM_BASELINES) { int val = 0; oskar_binary_read_int(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Number of baselines: %d", val); } else if (tag == OSKAR_VIS_TAG_DIMENSION_ORDER) { oskar_log_message(log, p, depth, "Visibility dimension order"); } else if (tag == OSKAR_VIS_TAG_COORD_TYPE) { oskar_log_message(log, p, depth, "Visibility coordinate type"); } else if (tag == OSKAR_VIS_TAG_AMP_TYPE) { oskar_log_message(log, p, depth, "Visibility amplitude type"); } else if (tag == OSKAR_VIS_TAG_FREQ_START_HZ) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Frequency start [Hz]: %.3e", val); } else if (tag == OSKAR_VIS_TAG_FREQ_INC_HZ) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Frequency inc [Hz]: %.3e", val); } else if (tag == OSKAR_VIS_TAG_CHANNEL_BANDWIDTH_HZ) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Channel bandwidth [Hz]: %.3e", val); } else if (tag == OSKAR_VIS_TAG_TIME_START_MJD_UTC) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Start time [MJD, UTC]: %.5f", val); } else if (tag == OSKAR_VIS_TAG_TIME_INC_SEC) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Time inc [s]: %.1f", val); } else if (tag == OSKAR_VIS_TAG_TIME_AVERAGE_SEC) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Time average integration [s]: %.1f", val); } else if (tag == OSKAR_VIS_TAG_POL_TYPE) { oskar_log_message(log, p, depth, "Polarisation type"); } else if (tag == OSKAR_VIS_TAG_BASELINE_COORD_UNIT) { oskar_log_message(log, p, depth, "Baseline coordinate unit"); } else if (tag == OSKAR_VIS_TAG_BASELINE_UU) { oskar_log_message(log, p, depth, "Baseline UU-coordinates"); } else if (tag == OSKAR_VIS_TAG_BASELINE_VV) { oskar_log_message(log, p, depth, "Baseline VV-coordinates"); } else if (tag == OSKAR_VIS_TAG_BASELINE_WW) { oskar_log_message(log, p, depth, "Baseline WW-coordinates"); } else if (tag == OSKAR_VIS_TAG_AMPLITUDE) { oskar_log_message(log, p, depth, "Visibilities"); } else if (tag == OSKAR_VIS_TAG_PHASE_CENTRE_RA) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Phase centre RA [deg]: %.3f", val); } else if (tag == OSKAR_VIS_TAG_PHASE_CENTRE_DEC) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Phase centre Dec [deg]: %.3f", val); } else if (tag == OSKAR_VIS_TAG_TELESCOPE_LON) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Telescope longitude [deg]: %.3f", val); } else if (tag == OSKAR_VIS_TAG_TELESCOPE_LAT) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Telescope latitude [deg]: %.3f", val); } else if (tag == OSKAR_VIS_TAG_TELESCOPE_ALT) { double val = 0; oskar_binary_read_double(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Telescope altitude [m]: %.3f", val); } else if (tag == OSKAR_VIS_TAG_NUM_STATIONS) { int val = 0; oskar_binary_read_int(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Number of stations: %d", val); } else if (tag == OSKAR_VIS_TAG_STATION_COORD_UNIT) { oskar_log_message(log, p, depth, "Station coordinate unit"); } else if (tag == OSKAR_VIS_TAG_STATION_X_OFFSET_ECEF) { oskar_log_message(log, p, depth, "Station X coordinates (offset ECEF)"); } else if (tag == OSKAR_VIS_TAG_STATION_Y_OFFSET_ECEF) { oskar_log_message(log, p, depth, "Station Y coordinates (offset ECEF)"); } else if (tag == OSKAR_VIS_TAG_STATION_Z_OFFSET_ECEF) { oskar_log_message(log, p, depth, "Station Z coordinates (offset ECEF)"); } else if (tag == OSKAR_VIS_TAG_STATION_X_ENU) { oskar_log_message(log, p, depth, "Station X coordinates (ENU)"); } else if (tag == OSKAR_VIS_TAG_STATION_Y_ENU) { oskar_log_message(log, p, depth, "Station Y coordinates (ENU)"); } else if (tag == OSKAR_VIS_TAG_STATION_Z_ENU) { oskar_log_message(log, p, depth, "Station Z coordinates (ENU)"); } } else if (group == OSKAR_TAG_GROUP_SKY_MODEL) { if (tag == OSKAR_SKY_TAG_NUM_SOURCES) { int val = 0; oskar_binary_read_int(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Number of sources: %d", val); } else if (tag == OSKAR_SKY_TAG_DATA_TYPE) { int val = 0; oskar_binary_read_int(h, group, tag, idx, &val, status); oskar_log_message(log, p, depth, "Data type: %s", oskar_mem_data_type_string(val)); } else if (tag == OSKAR_SKY_TAG_RA) { oskar_log_message(log, p, depth, "Right Ascension values"); } else if (tag == OSKAR_SKY_TAG_DEC) { oskar_log_message(log, p, depth, "Declination values"); } else if (tag == OSKAR_SKY_TAG_STOKES_I) { oskar_log_message(log, p, depth, "Stokes I values"); } else if (tag == OSKAR_SKY_TAG_STOKES_Q) { oskar_log_message(log, p, depth, "Stokes Q values"); } else if (tag == OSKAR_SKY_TAG_STOKES_U) { oskar_log_message(log, p, depth, "Stokes U values"); } else if (tag == OSKAR_SKY_TAG_STOKES_V) { oskar_log_message(log, p, depth, "Stokes V values"); } else if (tag == OSKAR_SKY_TAG_REF_FREQ) { oskar_log_message(log, p, depth, "Reference frequency values"); } else if (tag == OSKAR_SKY_TAG_SPECTRAL_INDEX) { oskar_log_message(log, p, depth, "Spectral index values"); } else if (tag == OSKAR_SKY_TAG_ROTATION_MEASURE) { oskar_log_message(log, p, depth, "Rotation measure values"); } else if (tag == OSKAR_SKY_TAG_FWHM_MAJOR) { oskar_log_message(log, p, depth, "Gaussian FWHM (major) values"); } else if (tag == OSKAR_SKY_TAG_FWHM_MINOR) { oskar_log_message(log, p, depth, "Gaussian FWHM (minor) values"); } else if (tag == OSKAR_SKY_TAG_POSITION_ANGLE) { oskar_log_message(log, p, depth, "Gaussian position angle values"); } } /* Free temp array. */ oskar_mem_free(temp, status); } } /* Iterate extended tags in index. */ if (extended_tags) { oskar_log_section(log, p, "Extended tags:"); oskar_log_message(log, p, -1, "[%3s] %-23s (%s)", "ID", "TYPE", "BYTES"); oskar_log_message(log, p, depth, "%s.%s : %s", "GROUP", "TAG", "INDEX"); oskar_log_line(log, p, '-'); for (i = 0; i < h->num_chunks; ++i) { if (h->extended[i]) { char *group, *tag, type; int idx; size_t bytes; /* Get the tag data. */ group = h->name_group[i]; tag = h->name_tag[i]; type = (char) (h->data_type[i]); idx = h->user_index[i]; bytes = h->payload_size_bytes[i]; /* Display tag data. */ oskar_log_message(log, p, -1, "[%3d] %-23s (%d bytes)", i, oskar_mem_data_type_string(type), bytes); oskar_log_message(log, p, depth, "%s.%s : %d", group, tag, idx); } } } /* Release the handle. */ oskar_binary_free(h); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/imager/src/private_imager_update_plane_wproj.c
/* * Copyright (c) 2016-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "imager/private_imager.h" #include "imager/oskar_imager.h" #include "imager/private_imager_update_plane_wproj.h" #include "imager/oskar_grid_wproj.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif #define SAVE_INPUT_DAT 0 #define SAVE_OUTPUT_DAT 0 #define SAVE_GRID 0 void oskar_imager_update_plane_wproj(oskar_Imager* h, size_t num_vis, const oskar_Mem* uu, const oskar_Mem* vv, const oskar_Mem* ww, const oskar_Mem* amps, const oskar_Mem* weight, oskar_Mem* plane, double* plane_norm, size_t* num_skipped, int* status) { int grid_size; size_t num_cells; if (*status) return; grid_size = oskar_imager_plane_size(h); num_cells = grid_size * grid_size; if (oskar_mem_precision(plane) != h->imager_prec) *status = OSKAR_ERR_TYPE_MISMATCH; if (oskar_mem_length(plane) < num_cells) oskar_mem_realloc(plane, num_cells, status); if (*status) return; if (h->imager_prec == OSKAR_DOUBLE) oskar_grid_wproj_d(h->num_w_planes, oskar_mem_int_const(h->w_support, status), h->oversample, h->conv_size_half, oskar_mem_double_const(h->w_kernels, status), num_vis, oskar_mem_double_const(uu, status), oskar_mem_double_const(vv, status), oskar_mem_double_const(ww, status), oskar_mem_double_const(amps, status), oskar_mem_double_const(weight, status), h->cellsize_rad, h->w_scale, grid_size, num_skipped, plane_norm, oskar_mem_double(plane, status)); else { char *fname = 0; #if SAVE_INPUT_DAT || SAVE_OUTPUT_DAT || SAVE_GRID fname = (char*) calloc(20 + h->input_root ? strlen(h->input_root) : 0, 1); #endif #if SAVE_INPUT_DAT { const float cellsize_rad_tmp = (const float) (h->cellsize_rad); const float w_scale_tmp = (const float) (h->w_scale); const size_t num_w_planes = (size_t) (h->num_w_planes); FILE* f; sprintf(fname, "%s_INPUT.dat", h->input_root); f = fopen(fname, "wb"); fwrite(&num_w_planes, sizeof(size_t), 1, f); fwrite(oskar_mem_void_const(h->w_support), sizeof(int), num_w_planes, f); fwrite(&h->oversample, sizeof(int), 1, f); fwrite(&h->conv_size_half, sizeof(int), 1, f); fwrite(oskar_mem_void_const(h->w_kernels), 2 * sizeof(float), h->num_w_planes * h->conv_size_half * h->conv_size_half, f); fwrite(&num_vis, sizeof(size_t), 1, f); fwrite(oskar_mem_void_const(uu), sizeof(float), num_vis, f); fwrite(oskar_mem_void_const(vv), sizeof(float), num_vis, f); fwrite(oskar_mem_void_const(ww), sizeof(float), num_vis, f); fwrite(oskar_mem_void_const(amps), 2 * sizeof(float), num_vis, f); fwrite(oskar_mem_void_const(weight), sizeof(float), num_vis, f); fwrite(&cellsize_rad_tmp, sizeof(float), 1, f); fwrite(&w_scale_tmp, sizeof(float), 1, f); fwrite(&grid_size, sizeof(int), 1, f); fclose(f); } #endif oskar_grid_wproj_f(h->num_w_planes, oskar_mem_int_const(h->w_support, status), h->oversample, h->conv_size_half, oskar_mem_float_const(h->w_kernels, status), num_vis, oskar_mem_float_const(uu, status), oskar_mem_float_const(vv, status), oskar_mem_float_const(ww, status), oskar_mem_float_const(amps, status), oskar_mem_float_const(weight, status), (float) (h->cellsize_rad), (float) (h->w_scale), grid_size, num_skipped, plane_norm, oskar_mem_float(plane, status)); #if SAVE_OUTPUT_DAT { FILE* f; sprintf(fname, "%s_OUTPUT.dat", h->input_root); f = fopen(fname, "wb"); fwrite(num_skipped, sizeof(size_t), 1, f); fwrite(plane_norm, sizeof(double), 1, f); fwrite(&grid_size, sizeof(int), 1, f); fwrite(oskar_mem_void_const(plane), 2 * sizeof(float), num_cells, f); fclose(f); } #endif #if SAVE_GRID sprintf(fname, "%s_GRID", h->input_root); oskar_mem_write_fits_cube(plane, fname, grid_size, grid_size, 1, 0, status); #endif free(fname); } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/sky/oskar_sky_filter_by_flux_cuda.h
<reponame>davepallot/OSKAR<gh_stars>1-10 /* * Copyright (c) 2013-2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_SKY_FILTER_BY_FLUX_CUDA_H_ #define OSKAR_SKY_FILTER_BY_FLUX_CUDA_H_ /** * @file oskar_sky_filter_by_flux_cuda.h */ #include <oskar_global.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Removes sources outside a given flux range using CUDA (single precision). * * @details * This function removes sources from all arrays that lie outside a given * flux range specified by \p min_I and \p max_I * * @param[in] num Number of input sources. * @param[out] num_out Number of sources retained. * @param[in] min_I Minimum Stokes I flux. * @param[in] max_I Maximum Stokes I flux. * @param[in,out] ra Right ascension coordinates. * @param[in,out] dec Declination coordinates. * @param[in,out] I Stokes I values. * @param[in,out] Q Stokes Q values. * @param[in,out] U Stokes U values. * @param[in,out] V Stokes V values. * @param[in,out] ref Reference frequency values. * @param[in,out] sp Spectral index values. * @param[in,out] rm Rotation measure values. * @param[in,out] l l-direction-cosine values. * @param[in,out] m m-direction-cosine values. * @param[in,out] n n-direction-cosine values. * @param[in,out] a Gaussian parameter a values. * @param[in,out] b Gaussian parameter b values. * @param[in,out] c Gaussian parameter c values. * @param[in,out] maj Gaussian major axis values. * @param[in,out] min Gaussian minor axis values. * @param[in,out] pa Gaussian position angle values. */ OSKAR_EXPORT void oskar_sky_filter_by_flux_cuda_f(int num, int* num_out, float min_I, float max_I, float* ra, float* dec, float* I, float* Q, float* U, float* V, float* ref, float* sp, float* rm, float* l, float* m, float* n, float* a, float* b, float* c, float* maj, float* min, float* pa); /** * @brief * Removes sources outside a given flux range using CUDA (double precision). * * @details * This function removes sources from all arrays that lie outside a given * flux range specified by \p min_I and \p max_I * * @param[in] num Number of input sources. * @param[out] num_out Number of sources retained. * @param[in] min_I Minimum Stokes I flux. * @param[in] max_I Maximum Stokes I flux. * @param[in,out] ra Right ascension coordinates. * @param[in,out] dec Declination coordinates. * @param[in,out] I Stokes I values. * @param[in,out] Q Stokes Q values. * @param[in,out] U Stokes U values. * @param[in,out] V Stokes V values. * @param[in,out] ref Reference frequency values. * @param[in,out] sp Spectral index values. * @param[in,out] rm Rotation measure values. * @param[in,out] l l-direction-cosine values. * @param[in,out] m m-direction-cosine values. * @param[in,out] n n-direction-cosine values. * @param[in,out] a Gaussian parameter a values. * @param[in,out] b Gaussian parameter b values. * @param[in,out] c Gaussian parameter c values. * @param[in,out] maj Gaussian major axis values. * @param[in,out] min Gaussian minor axis values. * @param[in,out] pa Gaussian position angle values. */ OSKAR_EXPORT void oskar_sky_filter_by_flux_cuda_d(int num, int* num_out, double min_I, double max_I, double* ra, double* dec, double* I, double* Q, double* U, double* V, double* ref, double* sp, double* rm, double* l, double* m, double* n, double* a, double* b, double* c, double* maj, double* min, double* pa); #ifdef __cplusplus } #endif #endif /* OSKAR_SKY_FILTER_BY_FLUX_CUDA_H_ */
davepallot/OSKAR
oskar/settings/oskar_SettingsNode.h
/* * Copyright (c) 2015-2017, The University of Oxford * All rights reserved. * * This file is part of the OSKAR package. * Contact: oskar at oerc.ox.ac.uk * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_SETTINGS_NODE_HPP_ #define OSKAR_SETTINGS_NODE_HPP_ /** * @file oskar_SettingsNode.h */ #include <settings/oskar_SettingsItem.h> #ifdef __cplusplus namespace oskar { struct SettingsNodePrivate; /*! * @class SettingsNode * * @brief A node within the settings tree, inherits @class SettingsItem. * * @details * Settings tree node class which specialises a settings item for use within * a tree structure. */ class OSKAR_SETTINGS_EXPORT SettingsNode : public SettingsItem { public: /*! Default constructor */ SettingsNode(); /*! Constructor */ SettingsNode(const char* key, const char* label = 0, const char* description = 0, const char* type_name = 0, const char* type_default = 0, const char* type_parameters = 0, bool is_required = false, int priority = 0); /*! Destructor */ virtual ~SettingsNode(); /*! Return the number of child nodes */ int num_children() const; /*! Add a child node */ SettingsNode* add_child(SettingsNode* node); /*! Return a pointer to the child node with index @p i */ SettingsNode* child(int i); /*! Return a const pointer to the child node with index @p i */ const SettingsNode* child(int i) const; /*! Return a pointer to the child node with key @p key */ SettingsNode* child(const char* key); /*! Return a const pointer to the child node with key @p key */ const SettingsNode* child(const char* key) const; /*! Return a pointer to the node's parent */ const SettingsNode* parent() const; /*! Return the child index of the node */ int child_number() const; /*! Return true, if the item or one its children has a non-default value. */ bool value_or_child_set() const; /*! Set the value field of the node. */ bool set_value(const char* value); private: /* Disable copy constructor. */ SettingsNode(const SettingsNode&); void update_value_set_counter_(bool increment_counter); void update_priority(int priority); SettingsNodePrivate* p; }; } /* namespace oskar */ #endif /* __cplusplus */ #endif /* OSKAR_SETTINGS_NODE_HPP_ */
davepallot/OSKAR
oskar/telescope/station/oskar_vla_pbcor_inline.h
<reponame>davepallot/OSKAR /* * Copyright (c) 2013-2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_VLA_PBCOR_INLINE_H_ #define OSKAR_VLA_PBCOR_INLINE_H_ /** * @file oskar_vla_pbcor_inline.h */ #include <oskar_global.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Evaluates a scalar VLA dish beam, as implemented in the AIPS task PBCOR * (single precision). * * @details * This function evaluates a scalar VLA dish beam, as implemented in the AIPS * task PBCOR. * * See http://www.aips.nrao.edu/cgi-bin/ZXHLP2.PL?PBCOR * * @param[in] l Direction cosine of each source from phase centre. * @param[in] m Direction cosine of each source from phase centre. * @param[in] freq_ghz Current observing frequency in GHz. * @param[in] p1 Value of PBPARM(3) for this frequency. * @param[in] p2 Value of PBPARM(4) for this frequency. * @param[in] p3 Value of PBPARM(5) for this frequency. * * @return Value of VLA beam. */ OSKAR_INLINE float oskar_vla_pbcor_inline_f(const float l, const float m, const float freq_ghz, const float p1, const float p2, const float p3) { float r, t, X, cutoff_arcmin; if (l != l) return l; /* Catch and return NAN without using the macro. */ cutoff_arcmin = 44.376293f / freq_ghz; r = asinf(sqrtf(l * l + m * m)) * 3437.74677078493951f; /* rad to arcmin */ if (r < cutoff_arcmin) { t = r * freq_ghz; X = t * t; return 1.0f + X * (p1 * 1e-3f + X * (p2 * 1e-7f + X * p3 * 1e-10f)); } return 0.0f; } /** * @brief * Evaluates a scalar VLA dish beam, as implemented in the AIPS task PBCOR * (double precision). * * @details * This function evaluates a scalar VLA dish beam, as implemented in the AIPS * task PBCOR. * * See http://www.aips.nrao.edu/cgi-bin/ZXHLP2.PL?PBCOR * * @param[in] l Direction cosine of each source from phase centre. * @param[in] m Direction cosine of each source from phase centre. * @param[in] freq_ghz Current observing frequency in GHz. * @param[in] p1 Value of PBPARM(3) for this frequency. * @param[in] p2 Value of PBPARM(4) for this frequency. * @param[in] p3 Value of PBPARM(5) for this frequency. * * @return Value of VLA beam. */ OSKAR_INLINE double oskar_vla_pbcor_inline_d(const double l, const double m, const double freq_ghz, const double p1, const double p2, const double p3) { double r, t, X, cutoff_arcmin; if (l != l) return l; /* Catch and return NAN without using the macro. */ cutoff_arcmin = 44.376293 / freq_ghz; r = asin(sqrt(l * l + m * m)) * 3437.74677078493951; /* rad to arcmin */ if (r < cutoff_arcmin) { t = r * freq_ghz; X = t * t; return 1.0 + X * (p1 * 1e-3 + X * (p2 * 1e-7 + X * p3 * 1e-10)); } return 0.0; } #ifdef __cplusplus } #endif #endif /* OSKAR_VLA_PBCOR_INLINE_H_ */
davepallot/OSKAR
oskar/interferometer/oskar_evaluate_jones_E.h
/* * Copyright (c) 2011-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_EVALUATE_JONES_E_H_ #define OSKAR_EVALUATE_JONES_E_H_ /** * @file oskar_evaluate_jones_E.h */ #include <oskar_global.h> #include <telescope/oskar_telescope.h> #include <interferometer/oskar_jones.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Evaluates a set of E-Jones matrices for a number of stations and * source positions. * * @details * Evaluates station beams for a telescope model at the specified source * positions, storing the results in the Jones matrix data structure. * * If all stations are marked as identical, the results for the first station * are copied into the results for the others. * * @param[out] E Output set of Jones matrices. * @param[in] num_points Number of direction cosines given. * @param[in] coord_type Type of direction cosines * (OSKAR_RELATIVE_DIRECTIONS or * OSKAR_ENU_DIRECTIONS). * @param[in] x Direction cosines (x direction). * @param[in] y Direction cosines (y direction). * @param[in] z Direction cosines (z direction). * @param[in] tel Input telescope model. * @param[in] gast The Greenwich Apparent Sidereal Time, in radians. * @param[in] frequency_hz The observing frequency, in Hz. * @param[in] work Pointer to structure holding work arrays. * @param[in] time_index Simulation time index. * @param[in,out] status Status return code. */ OSKAR_EXPORT void oskar_evaluate_jones_E(oskar_Jones* E, int num_points, int coord_type, oskar_Mem* x, oskar_Mem* y, oskar_Mem* z, const oskar_Telescope* tel, double gast, double frequency_hz, oskar_StationWork* work, int time_index, int* status); #ifdef __cplusplus } #endif #endif /* OSKAR_EVALUATE_JONES_E_H_ */
davepallot/OSKAR
oskar/telescope/station/src/oskar_station_work.c
<reponame>davepallot/OSKAR /* * Copyright (c) 2012-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/oskar_station_work.h" #include "telescope/station/private_station_work.h" #ifdef __cplusplus extern "C" { #endif static void get_mem_from_template(oskar_Mem** b, const oskar_Mem* a, size_t length, int* status); oskar_StationWork* oskar_station_work_create(int type, int location, int* status) { oskar_StationWork* work = 0; /* Allocate memory for the structure. */ work = (oskar_StationWork*) malloc(sizeof(oskar_StationWork)); /* Check the base type is correct. */ if (type != OSKAR_SINGLE && type != OSKAR_DOUBLE) *status = OSKAR_ERR_BAD_DATA_TYPE; /* Initialise arrays. */ work->horizon_mask = oskar_mem_create(OSKAR_INT, location, 0, status); work->source_indices = oskar_mem_create(OSKAR_INT, location, 0, status); work->theta_modified = oskar_mem_create(type, location, 0, status); work->phi_modified = oskar_mem_create(type, location, 0, status); work->enu_direction_x = oskar_mem_create(type, location, 0, status); work->enu_direction_y = oskar_mem_create(type, location, 0, status); work->enu_direction_z = oskar_mem_create(type, location, 0, status); work->weights = oskar_mem_create((type | OSKAR_COMPLEX), location, 0, status); work->weights_error = oskar_mem_create((type | OSKAR_COMPLEX), location, 0, status); work->array_pattern = oskar_mem_create((type | OSKAR_COMPLEX), location, 0, status); work->normalised_beam = 0; work->num_depths = 0; work->beam = 0; return work; } void oskar_station_work_free(oskar_StationWork* work, int* status) { int i; if (!work) return; oskar_mem_free(work->horizon_mask, status); oskar_mem_free(work->source_indices, status); oskar_mem_free(work->theta_modified, status); oskar_mem_free(work->phi_modified, status); oskar_mem_free(work->enu_direction_x, status); oskar_mem_free(work->enu_direction_y, status); oskar_mem_free(work->enu_direction_z, status); oskar_mem_free(work->weights, status); oskar_mem_free(work->weights_error, status); oskar_mem_free(work->array_pattern, status); oskar_mem_free(work->normalised_beam, status); for (i = 0; i < work->num_depths; ++i) { oskar_mem_free(work->beam[i], status); } /* Free the structure. */ free(work); } oskar_Mem* oskar_station_work_horizon_mask(oskar_StationWork* work) { return work->horizon_mask; } oskar_Mem* oskar_station_work_source_indices(oskar_StationWork* work) { return work->source_indices; } oskar_Mem* oskar_station_work_enu_direction_x(oskar_StationWork* work) { return work->enu_direction_x; } oskar_Mem* oskar_station_work_enu_direction_y(oskar_StationWork* work) { return work->enu_direction_y; } oskar_Mem* oskar_station_work_enu_direction_z(oskar_StationWork* work) { return work->enu_direction_z; } oskar_Mem* oskar_station_work_normalised_beam(oskar_StationWork* work, const oskar_Mem* output_beam, int* status) { get_mem_from_template(&work->normalised_beam, output_beam, 1 + oskar_mem_length(output_beam), status); return work->normalised_beam; } oskar_Mem* oskar_station_work_beam(oskar_StationWork* work, const oskar_Mem* output_beam, size_t length, int depth, int* status) { if (depth > work->num_depths - 1) { int i, old_num_depths; old_num_depths = work->num_depths; work->num_depths = depth + 1; work->beam = realloc(work->beam, work->num_depths * sizeof(oskar_Mem*)); for (i = old_num_depths; i < work->num_depths; ++i) { work->beam[i] = 0; } } get_mem_from_template(&work->beam[depth], output_beam, length, status); return work->beam[depth]; } static void get_mem_from_template(oskar_Mem** b, const oskar_Mem* a, size_t length, int* status) { int type, loc; type = oskar_mem_type(a); loc = oskar_mem_location(a); /* Check if the array exists with an incorrect type and location. */ if (*b && (oskar_mem_type(*b) != type || oskar_mem_location(*b) != loc)) { oskar_mem_free(*b, status); *b = 0; } /* Create or resize the array. */ if (!*b) *b = oskar_mem_create(type, loc, length, status); else if (oskar_mem_length(*b) < length) oskar_mem_realloc(*b, length, status); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/utility/src/oskar_string_to_array.c
/* * Copyright (c) 2011-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "utility/oskar_string_to_array.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 #define strtok_r(s,d,p) strtok_s(s,d,p) #else /* Ensure function is declared for strange string.h header. */ char* strtok_r(char*, const char*, char**); #endif #define DELIMITERS ", \t" /* Integer. */ size_t oskar_string_to_array_i(char* str, size_t n, int* data) { size_t i = 0; char *save_ptr = 0, *token = 0; do { token = strtok_r(str, DELIMITERS, &save_ptr); str = NULL; if (!token) break; if (token[0] == '#') break; if (sscanf(token, "%i", &data[i]) > 0) i++; } while (i < n); return i; } /* Single precision. */ size_t oskar_string_to_array_f(char* str, size_t n, float* data) { size_t i = 0; char *save_ptr = 0, *token = 0; do { token = strtok_r(str, DELIMITERS, &save_ptr); str = NULL; if (!token) break; if (token[0] == '#') break; if (sscanf(token, "%f", &data[i]) > 0) i++; } while (i < n); return i; } /* Double precision. */ size_t oskar_string_to_array_d(char* str, size_t n, double* data) { size_t i = 0; char *save_ptr = 0, *token = 0; do { token = strtok_r(str, DELIMITERS, &save_ptr); str = NULL; if (!token) break; if (token[0] == '#') break; if (sscanf(token, "%lf", &data[i]) > 0) i++; } while (i < n); return i; } /* String array. */ size_t oskar_string_to_array_s(char* str, size_t n, char** data) { size_t i; char *save_ptr = 0; for (i = 0; i < n; ++i) { data[i] = strtok_r(str, DELIMITERS, &save_ptr); str = NULL; if (!data[i]) break; if (data[i][0] == '#') break; } return i; } /* String array. */ size_t oskar_string_to_array_realloc_s(char* str, size_t* n, char*** data) { size_t i; char *save_ptr = 0, *token = 0; for (i = 0; ; ++i) { token = strtok_r(str, DELIMITERS, &save_ptr); str = NULL; if (!token) break; if (token[0] == '#') break; /* Ensure array is big enough. */ if (*n <= i || !(*data)) { void* t; t = realloc(*data, ((*n) + 1) * sizeof(char*)); if (!t) break; *data = t; ++(*n); } (*data)[i] = token; } return i; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/log/src/oskar_log_write.c
/* * Copyright (c) 2012-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "log/private_log.h" #include "log/oskar_log.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #ifdef __cplusplus extern "C" { #endif /* Static function prototypes. */ static void print_entry(FILE* stream, char priority, char code, int depth, const char* prefix, int width, const char* format, va_list args); static void oskar_log_update_record(oskar_Log* log, char code); static int oskar_log_priority_level(char code); static int should_print_term_entry(oskar_Log* log, char priority); static int should_print_file_entry(oskar_Log* log, char priority); void oskar_log_write(oskar_Log* log, FILE* stream, char priority, char code, int depth, const char* prefix, const char* format, va_list args) { int width = 0, is_file = 0; /* If both strings are NULL and not printing a line the entry is invalid */ if (!format && !prefix && depth != OSKAR_LOG_LINE) return; width = log ? log->value_width : OSKAR_LOG_DEFAULT_VALUE_WIDTH; is_file = (stream == stdout || stream == stderr) ? 0 : 1; /* Write the entry to the terminal */ if (!is_file && should_print_term_entry(log, priority)) { print_entry(stream, priority, code, depth, prefix, width, format, args); fflush(stream); } /* Write the entry to the log file */ else if (is_file && log && log->file && should_print_file_entry(log, priority)) { print_entry(log->file, priority, code, depth, prefix, width, format, args); oskar_log_update_record(log, code); } } /* * Update the record meta data. As the length of a log entry cannot be known * a-priori in C89 the length of each entry is determined from the log file * * **IMPORTANT**: This function should be called **AFTER** the log entry has * been written to file and inside a omp mutex lock (if using OpenMP threads) */ static void oskar_log_update_record(oskar_Log* log, char code) { if (!log) return; /* Resize arrays in log structure if required. */ if (log->size % 100 == 0) { int i; i = log->size + 100; log->code = realloc(log->code, i); log->offset = realloc(log->offset, i * sizeof(int)); log->length = realloc(log->length, i * sizeof(int)); log->timestamp = realloc(log->timestamp, i * sizeof(time_t)); log->capacity = i; } /* Store the code and time stamp of the entry. */ log->code[log->size] = code; log->timestamp[log->size] = time(NULL); log->offset[log->size] = 0; log->length[log->size] = 0; /* Check if log file exists. */ if (log->file) { /* Store the offset of the entry. */ if (log->size > 0) log->offset[log->size] = log->offset[log->size-1] + log->length[log->size-1]; else log->offset[log->size] = 0; /* Store the length of the log entry. */ log->length[log->size] = ftell(log->file) - log->offset[log->size]; } /* Increment the log entry counter. */ log->size++; } char oskar_log_get_entry_code(char priority) { switch (priority) { case 'E': case 'e': return 'E'; case 'W': case 'w': return 'W'; case 'M': case 'm': case ' ': case 'S': /* Status */ case 's': /* Status */ return ' '; case 'D': case 'd': return 'D'; default: return 'U'; }; return 'U'; } static void print_entry(FILE* stream, char priority, char code, int depth, const char* prefix, int width, const char* format, va_list args) { int i; /* Ensure code is a printable character. */ if (code < 32) code += 48; /* Check if depth signifies a line. */ if (depth == OSKAR_LOG_LINE) { char priority_code = oskar_log_get_entry_code(priority); fprintf(stream, "%c|", priority_code); for (i = 0; i < 67; ++i) fprintf(stream, "%c", code); fprintf(stream, "\n"); return; } /* Print the message code. */ fprintf(stream, "%c|", code); /* Print leading whitespace and symbol for this depth. */ if (depth >= 0) { char list_symbols[3] = {'+', '-', '*'}; for (i = 0; i < depth; ++i) fprintf(stream, " "); fprintf(stream, " %c ", list_symbols[depth%3]); } else { /* Negative depth codes with special meaning */ switch (depth) { case OSKAR_LOG_INFO_PREFIX: case OSKAR_LOG_SECTION: break; default: /* Negative depth means no symbol. */ for (i = 0; i < abs(depth); ++i) fprintf(stream, " "); break; } } /* Check if a prefix string is present. */ if (prefix && *prefix > 0) { /* Print prefix. */ fprintf(stream, "%s", prefix); /* Print trailing whitespace if format string is present. */ if (format && *format > 0) { int n; n = abs(2 * depth + 4 + (int)strlen(prefix)); for (i = 0; i < width - n; ++i) fprintf(stream, " "); if (depth != OSKAR_LOG_SECTION) fprintf(stream, ": "); } } /* Print main message from format string and arguments. */ if (format && *format > 0) { vfprintf(stream, format, args); } fprintf(stream, "\n"); } /* * Returns the enumerated priority level for the given message code. * * Code to integer conversion is performed to make priority comparison * easier */ static int oskar_log_priority_level(char code) { switch (code) { case 'n': case 'N': return OSKAR_LOG_NONE; case 'e': case 'E': return OSKAR_LOG_ERROR; case 'w': case 'W': return OSKAR_LOG_WARNING; case 'm': case 'M': return OSKAR_LOG_MESSAGE; case 's': case 'S': return OSKAR_LOG_STATUS; case 'd': case 'D': return OSKAR_LOG_DEBUG; default: return OSKAR_LOG_NONE; }; return OSKAR_LOG_NONE; } static int should_print_term_entry(oskar_Log* log, char priority) { int log_priority = log ? log->term_priority : OSKAR_LOG_DEFAULT_PRIORITY; return (oskar_log_priority_level(priority) <= log_priority)? 1 : 0; } static int should_print_file_entry(oskar_Log* log, char priority) { int log_priority = log ? log->file_priority : OSKAR_LOG_DEFAULT_PRIORITY; return (oskar_log_priority_level(priority) <= log_priority)? 1 : 0; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/convert/oskar_convert_apparent_ra_dec_to_az_el.h
<gh_stars>1-10 /* * Copyright (c) 2013, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_CONVERT_APPARENT_RA_DEC_TO_AZ_EL_H_ #define OSKAR_CONVERT_APPARENT_RA_DEC_TO_AZ_EL_H_ /** * @file oskar_convert_apparent_ra_dec_to_az_el.h */ #include <oskar_global.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Equatorial to horizontal coordinates (single precision). * * @details * This function computes the azimuth and elevation of the specified points * in the horizontal coordinate system. * * @param[in] n The number of points. * @param[in] ra The input Right Ascensions, in radians. * @param[in] dec The input Declinations, in radians. * @param[in] lst The current local sidereal time, in radians. * @param[in] lat The geodetic latitude of the origin of the horizon system. * @param[in] work Work array of length n. * @param[out] az The azimuths, in radians. * @param[out] el The elevations, in radians. */ OSKAR_EXPORT void oskar_convert_apparent_ra_dec_to_az_el_f(int n, const float* ra, const float* dec, float lst, float lat, float* work, float* az, float* el); /** * @brief * Equatorial to horizontal coordinates (double precision). * * @details * This function computes the azimuth and elevation of the specified points * in the horizontal coordinate system. * * @param[in] n The number of points. * @param[in] ra The input Right Ascensions, in radians. * @param[in] dec The input Declinations, in radians. * @param[in] lst The current local sidereal time, in radians. * @param[in] lat The geodetic latitude of the origin of the horizon system. * @param[in] work Work array of length n. * @param[out] az The azimuths, in radians. * @param[out] el The elevations, in radians. */ OSKAR_EXPORT void oskar_convert_apparent_ra_dec_to_az_el_d(int n, const double* ra, const double* dec, double lst, double lat, double* work, double* az, double* el); #ifdef __cplusplus } #endif #endif /* OSKAR_CONVERT_APPARENT_RA_DEC_TO_AZ_EL_H_ */
davepallot/OSKAR
oskar/beam_pattern/oskar_beam_pattern_accessors.h
<filename>oskar/beam_pattern/oskar_beam_pattern_accessors.h /* * Copyright (c) 2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_BEAM_PATTERN_ACCESSORS_H_ #define OSKAR_BEAM_PATTERN_ACCESSORS_H_ /** * @file oskar_beam_pattern_accessors.h */ #include <oskar_global.h> #include <log/oskar_log.h> #include <telescope/oskar_telescope.h> #ifdef __cplusplus extern "C" { #endif OSKAR_EXPORT int oskar_beam_pattern_num_gpus(const oskar_BeamPattern* h); OSKAR_EXPORT void oskar_beam_pattern_set_auto_power_fits(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_auto_power_text(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_average_time_and_channel(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_average_single_axis(oskar_BeamPattern* h, char option); OSKAR_EXPORT void oskar_beam_pattern_set_cross_power_amp_fits(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_cross_power_amp_text(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_cross_power_phase_fits(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_cross_power_phase_text(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_cross_power_raw_text(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_coordinate_frame(oskar_BeamPattern* h, char option); OSKAR_EXPORT void oskar_beam_pattern_set_coordinate_type(oskar_BeamPattern* h, char option); OSKAR_EXPORT void oskar_beam_pattern_set_gpus(oskar_BeamPattern* h, int num_gpus, const int* cuda_device_ids, int* status); OSKAR_EXPORT void oskar_beam_pattern_set_image_size(oskar_BeamPattern* h, int width, int height); OSKAR_EXPORT void oskar_beam_pattern_set_image_fov(oskar_BeamPattern* h, double width_deg, double height_deg); OSKAR_EXPORT void oskar_beam_pattern_set_log(oskar_BeamPattern* h, oskar_Log* log); OSKAR_EXPORT void oskar_beam_pattern_set_max_chunk_size(oskar_BeamPattern* h, int value); OSKAR_EXPORT void oskar_beam_pattern_set_num_devices(oskar_BeamPattern* h, int value); OSKAR_EXPORT void oskar_beam_pattern_set_observation_frequency(oskar_BeamPattern* h, double start_hz, double inc_hz, int num_channels); OSKAR_EXPORT void oskar_beam_pattern_set_observation_time(oskar_BeamPattern* h, double time_start_mjd_utc, double inc_sec, int num_time_steps); OSKAR_EXPORT void oskar_beam_pattern_set_root_path(oskar_BeamPattern* h, const char* path); OSKAR_EXPORT void oskar_beam_pattern_set_separate_time_and_channel(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_sky_model_file(oskar_BeamPattern* h, const char* path); OSKAR_EXPORT void oskar_beam_pattern_set_station_ids(oskar_BeamPattern* h, int num_stations, const int* ids); OSKAR_EXPORT void oskar_beam_pattern_set_stokes(oskar_BeamPattern* h, const char* stokes); OSKAR_EXPORT void oskar_beam_pattern_set_telescope_model(oskar_BeamPattern* h, const oskar_Telescope* model, int* status); OSKAR_EXPORT void oskar_beam_pattern_set_voltage_amp_fits(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_voltage_amp_text(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_voltage_phase_fits(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_voltage_phase_text(oskar_BeamPattern* h, int flag); OSKAR_EXPORT void oskar_beam_pattern_set_voltage_raw_text(oskar_BeamPattern* h, int flag); #ifdef __cplusplus } #endif #endif /* OSKAR_BEAM_PATTERN_ACCESSORS_H_ */
davepallot/OSKAR
oskar/vis/src/oskar_vis_read.c
/* * Copyright (c) 2011-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "vis/private_vis.h" #include "vis/oskar_vis.h" #include "vis/oskar_vis_header.h" #include "vis/oskar_vis_block.h" #include "binary/oskar_binary.h" #include "mem/oskar_binary_read_mem.h" #include <math.h> #ifdef __cplusplus extern "C" { #endif static oskar_Vis* oskar_vis_read_new(oskar_Binary* h, int* status); oskar_Vis* oskar_vis_read(oskar_Binary* h, int* status) { /* Visibility metadata. */ int num_channels = 0, num_times = 0, num_stations = 0, tag_error = 0; int amp_type = 0; unsigned char grp = OSKAR_TAG_GROUP_VISIBILITY; oskar_Vis* vis = 0; /* Check if safe to proceed. */ if (*status) return 0; /* Read visibility dimensions. */ oskar_binary_read_int(h, grp, OSKAR_VIS_TAG_NUM_CHANNELS, 0, &num_channels, status); if (*status == OSKAR_ERR_BINARY_TAG_NOT_FOUND) { /* Try to read a new format visibility file. */ *status = 0; return oskar_vis_read_new(h, status); } else if (*status) return 0; oskar_binary_read_int(h, grp, OSKAR_VIS_TAG_NUM_TIMES, 0, &num_times, status); oskar_binary_read_int(h, grp, OSKAR_VIS_TAG_NUM_STATIONS, 0, &num_stations, &tag_error); if (tag_error == OSKAR_ERR_BINARY_TAG_NOT_FOUND) { /* Check for number of baselines if number of stations not present. */ int num_baselines = 0; oskar_binary_read_int(h, grp, OSKAR_VIS_TAG_NUM_BASELINES, 0, &num_baselines, status); /* Convert baselines to stations (care using floating point here). */ num_stations = (int) floor(0.5 + (1.0 + sqrt(1.0 + 8.0 * num_baselines)) / 2.0); } else if (tag_error) *status = tag_error; oskar_binary_read_int(h, grp, OSKAR_VIS_TAG_AMP_TYPE, 0, &amp_type, status); /* Check if safe to proceed. */ if (*status) return 0; /* Create the visibility structure. */ vis = oskar_vis_create(amp_type, OSKAR_CPU, num_channels, num_times, num_stations, status); /* Optionally read the settings path (ignore the error code). */ tag_error = 0; oskar_binary_read_mem(h, vis->settings_path, OSKAR_TAG_GROUP_SETTINGS, OSKAR_TAG_SETTINGS_PATH, 0, &tag_error); /* Optionally read the settings data (ignore the error code). */ tag_error = 0; oskar_binary_read_mem(h, vis->settings, OSKAR_TAG_GROUP_SETTINGS, OSKAR_TAG_SETTINGS, 0, &tag_error); /* Optionally read the telescope model path (ignore the error code). */ tag_error = 0; oskar_binary_read_mem(h, vis->telescope_path, grp, OSKAR_VIS_TAG_TELESCOPE_PATH, 0, &tag_error); /* Read visibility metadata. */ oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_FREQ_START_HZ, 0, &vis->freq_start_hz, status); oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_FREQ_INC_HZ, 0, &vis->freq_inc_hz, status); oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_TIME_START_MJD_UTC, 0, &vis->time_start_mjd_utc, status); oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_TIME_INC_SEC, 0, &vis->time_inc_sec, status); oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_PHASE_CENTRE_RA, 0, &vis->phase_centre_ra_deg, status); oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_PHASE_CENTRE_DEC, 0, &vis->phase_centre_dec_deg, status); /* Read the baseline coordinate arrays. */ oskar_binary_read_mem(h, vis->baseline_uu_metres, grp, OSKAR_VIS_TAG_BASELINE_UU, 0, status); oskar_binary_read_mem(h, vis->baseline_vv_metres, grp, OSKAR_VIS_TAG_BASELINE_VV, 0, status); oskar_binary_read_mem(h, vis->baseline_ww_metres, grp, OSKAR_VIS_TAG_BASELINE_WW, 0, status); /* Read the visibility data. */ oskar_binary_read_mem(h, vis->amplitude, grp, OSKAR_VIS_TAG_AMPLITUDE, 0, status); /* Optionally read station coordinates (ignore the error code). */ tag_error = 0; oskar_binary_read_mem(h, vis->station_x_offset_ecef_metres, grp, OSKAR_VIS_TAG_STATION_X_OFFSET_ECEF, 0, &tag_error); oskar_binary_read_mem(h, vis->station_y_offset_ecef_metres, grp, OSKAR_VIS_TAG_STATION_Y_OFFSET_ECEF, 0, &tag_error); oskar_binary_read_mem(h, vis->station_z_offset_ecef_metres, grp, OSKAR_VIS_TAG_STATION_Z_OFFSET_ECEF, 0, &tag_error); /* Optionally read telescope lon., lat., alt. (ignore the error code) */ tag_error = 0; oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_TELESCOPE_LON, 0, &vis->telescope_lon_deg, &tag_error); oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_TELESCOPE_LAT, 0, &vis->telescope_lat_deg, &tag_error); oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_TELESCOPE_ALT, 0, &vis->telescope_alt_metres, &tag_error); /* Optionally read the channel bandwidth value. */ tag_error = 0; oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_CHANNEL_BANDWIDTH_HZ, 0, &vis->channel_bandwidth_hz, &tag_error); /* Optionally read the time integration value. */ tag_error = 0; oskar_binary_read_double(h, grp, OSKAR_VIS_TAG_TIME_AVERAGE_SEC, 0, &vis->time_average_sec, &tag_error); /* Return a handle to the new structure. */ return vis; } /* * Translation layer from new file format to old structure. * This will be deleted when the old oskar_Vis structure is fully retired. */ oskar_Vis* oskar_vis_read_new(oskar_Binary* h, int* status) { oskar_VisHeader* hdr = 0; oskar_VisBlock* blk = 0; oskar_Vis* vis = 0; oskar_Mem* amp = 0; const oskar_Mem* xcorr = 0; int amp_type, max_times_per_block, num_channels, num_stations, num_times; int i, num_blocks; double freq_ref_hz, freq_inc_hz, time_ref_mjd_utc, time_inc_sec; /* Try to read the new header. */ hdr = oskar_vis_header_read(h, status); if (*status) { oskar_vis_header_free(hdr, status); return 0; } /* Create the old vis structure. */ amp_type = oskar_vis_header_amp_type(hdr); max_times_per_block = oskar_vis_header_max_times_per_block(hdr); num_channels = oskar_vis_header_num_channels_total(hdr); num_stations = oskar_vis_header_num_stations(hdr); num_times = oskar_vis_header_num_times_total(hdr); vis = oskar_vis_create(amp_type, OSKAR_CPU, num_channels, num_times, num_stations, status); if (*status) { oskar_vis_header_free(hdr, status); oskar_vis_free(vis, status); return 0; } /* Copy station coordinates and metadata. */ freq_ref_hz = oskar_vis_header_freq_start_hz(hdr); freq_inc_hz = oskar_vis_header_freq_inc_hz(hdr); time_ref_mjd_utc = oskar_vis_header_time_start_mjd_utc(hdr); time_inc_sec = oskar_vis_header_time_inc_sec(hdr); oskar_mem_copy(oskar_vis_station_x_offset_ecef_metres(vis), oskar_vis_header_station_x_offset_ecef_metres_const(hdr), status); oskar_mem_copy(oskar_vis_station_y_offset_ecef_metres(vis), oskar_vis_header_station_y_offset_ecef_metres_const(hdr), status); oskar_mem_copy(oskar_vis_station_z_offset_ecef_metres(vis), oskar_vis_header_station_z_offset_ecef_metres_const(hdr), status); oskar_mem_copy(oskar_vis_settings(vis), oskar_vis_header_settings_const(hdr), status); oskar_mem_copy(oskar_vis_telescope_path(vis), oskar_vis_header_telescope_path_const(hdr), status); oskar_vis_set_channel_bandwidth_hz(vis, oskar_vis_header_channel_bandwidth_hz(hdr)); oskar_vis_set_freq_inc_hz(vis, freq_inc_hz); oskar_vis_set_freq_start_hz(vis, freq_ref_hz); oskar_vis_set_phase_centre(vis, oskar_vis_header_phase_centre_ra_deg(hdr), oskar_vis_header_phase_centre_dec_deg(hdr)); oskar_vis_set_telescope_position(vis, oskar_vis_header_telescope_lon_deg(hdr), oskar_vis_header_telescope_lat_deg(hdr), oskar_vis_header_telescope_alt_metres(hdr)); oskar_vis_set_time_average_sec(vis, oskar_vis_header_time_average_sec(hdr)); oskar_vis_set_time_inc_sec(vis, time_inc_sec); oskar_vis_set_time_start_mjd_utc(vis, time_ref_mjd_utc); /* Create a visibility block to read into. */ blk = oskar_vis_block_create_from_header(OSKAR_CPU, hdr, status); amp = oskar_vis_amplitude(vis); xcorr = oskar_vis_block_cross_correlations_const(blk); /* Work out the number of blocks. */ num_blocks = (num_times + max_times_per_block - 1) / max_times_per_block; for (i = 0; i < num_blocks; ++i) { int block_length, num_baselines, time_offset, total_baselines, t, c; /* Read the block. */ oskar_vis_block_read(blk, hdr, h, i, status); num_baselines = oskar_vis_block_num_baselines(blk); block_length = oskar_vis_block_num_times(blk); /* Copy the baseline coordinate data. */ time_offset = i * max_times_per_block * num_baselines; total_baselines = num_baselines * block_length; oskar_mem_copy_contents(oskar_vis_baseline_uu_metres(vis), oskar_vis_block_baseline_uu_metres_const(blk), time_offset, 0, total_baselines, status); oskar_mem_copy_contents(oskar_vis_baseline_vv_metres(vis), oskar_vis_block_baseline_vv_metres_const(blk), time_offset, 0, total_baselines, status); oskar_mem_copy_contents(oskar_vis_baseline_ww_metres(vis), oskar_vis_block_baseline_ww_metres_const(blk), time_offset, 0, total_baselines, status); /* Fill the array in the old dimension order. */ for (t = 0; t < block_length; ++t) { for (c = 0; c < num_channels; ++c) { oskar_mem_copy_contents(amp, xcorr, num_baselines * (c * num_times + i * max_times_per_block + t), num_baselines * (t * num_channels + c), num_baselines, status); } } } /* Clean up and return. */ oskar_vis_block_free(blk, status); oskar_vis_header_free(hdr, status); return vis; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/utility/src/oskar_binary_write_metadata.c
<gh_stars>1-10 /* * Copyright (c) 2012-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "utility/oskar_binary_write_metadata.h" #include "oskar_version.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #ifdef OSKAR_OS_WIN #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <unistd.h> #endif #ifdef __cplusplus extern "C" { #endif void oskar_binary_write_metadata(oskar_Binary* handle, int* status) { char* str; size_t len; static char time_str[80]; time_t unix_time; struct tm* timeinfo; /* Check if safe to proceed. */ if (*status) return; /* Write the system date and time. */ unix_time = time(0); timeinfo = localtime(&unix_time); strftime(time_str, sizeof(time_str), "%Y-%m-%d, %H:%M:%S (%Z)", timeinfo); len = 1 + strlen(time_str); oskar_binary_write(handle, OSKAR_CHAR, OSKAR_TAG_GROUP_METADATA, OSKAR_TAG_METADATA_DATE_TIME_STRING, 0, len, time_str, status); /* Write the OSKAR version string. */ len = 1 + strlen(OSKAR_VERSION_STR); oskar_binary_write(handle, OSKAR_CHAR, OSKAR_TAG_GROUP_METADATA, OSKAR_TAG_METADATA_OSKAR_VERSION_STRING, 0, len, OSKAR_VERSION_STR, status); /* Write the current working directory. */ str = 0; len = 0; #ifdef OSKAR_OS_WIN len = GetCurrentDirectory(0, NULL); str = (char*) calloc(len, sizeof(char)); GetCurrentDirectory((DWORD) len, str); #else do { len += 256; str = (char*) realloc(str, len); } while (getcwd(str, len) == NULL); #endif if (str) { len = 1 + strlen(str); oskar_binary_write(handle, OSKAR_CHAR, OSKAR_TAG_GROUP_METADATA, OSKAR_TAG_METADATA_CWD, 0, len, str, status); } free(str); /* Write the username. */ str = getenv("USERNAME"); if (!str) str = getenv("USER"); if (str) { len = 1 + strlen(str); oskar_binary_write(handle, OSKAR_CHAR, OSKAR_TAG_GROUP_METADATA, OSKAR_TAG_METADATA_USERNAME, 0, len, str, status); } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/interferometer/src/oskar_evaluate_jones_E.c
/* * Copyright (c) 2011-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "interferometer/oskar_evaluate_jones_E.h" #include "interferometer/oskar_jones_get_station_pointer.h" #include "telescope/station/oskar_evaluate_station_beam.h" #ifdef __cplusplus extern "C" { #endif void oskar_evaluate_jones_E(oskar_Jones* E, int num_points, int coord_type, oskar_Mem* x, oskar_Mem* y, oskar_Mem* z, const oskar_Telescope* tel, double gast, double frequency_hz, oskar_StationWork* work, int time_index, int* status) { int i, num_stations; oskar_Mem *E_st; /* Check if safe to proceed. */ if (*status) return; /* Check number of stations. */ num_stations = oskar_telescope_num_stations(tel); if (num_stations == 0) { *status = OSKAR_ERR_MEMORY_NOT_ALLOCATED; return; } /* Evaluate the station beams. */ E_st = oskar_mem_create_alias(0, 0, 0, status); if (oskar_telescope_allow_station_beam_duplication(tel) && oskar_telescope_identical_stations(tel)) { /* Identical stations. */ oskar_Mem *E0; /* Pointer to row of E for station 0. */ const oskar_Station* station0; /* Evaluate the beam pattern for station 0 */ E0 = oskar_mem_create_alias(0, 0, 0, status); station0 = oskar_telescope_station_const(tel, 0); oskar_jones_get_station_pointer(E0, E, 0, status); oskar_evaluate_station_beam(E0, num_points, coord_type, x, y, z, oskar_telescope_phase_centre_ra_rad(tel), oskar_telescope_phase_centre_dec_rad(tel), station0, work, time_index, frequency_hz, gast, status); /* Copy E for station 0 into memory for other stations. */ for (i = 1; i < num_stations; ++i) { oskar_jones_get_station_pointer(E_st, E, i, status); oskar_mem_copy_contents(E_st, E0, 0, 0, oskar_mem_length(E0), status); } oskar_mem_free(E0, status); } else { /* Different stations. */ for (i = 0; i < num_stations; ++i) { const oskar_Station* station; station = oskar_telescope_station_const(tel, i); oskar_jones_get_station_pointer(E_st, E, i, status); oskar_evaluate_station_beam(E_st, num_points, coord_type, x, y, z, oskar_telescope_phase_centre_ra_rad(tel), oskar_telescope_phase_centre_dec_rad(tel), station, work, time_index, frequency_hz, gast, status); } } oskar_mem_free(E_st, status); } #ifdef __cplusplus } #endif
davepallot/OSKAR
python/oskar/src/oskar_vis_block_lib.c
<gh_stars>1-10 /* * Copyright (c) 2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <Python.h> #include <oskar.h> #include <string.h> /* http://docs.scipy.org/doc/numpy-dev/reference/c-api.deprecations.html */ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/arrayobject.h> static const char module_doc[] = "This module provides an interface to an OSKAR visibility block."; static const char name[] = "oskar_VisBlock"; static void* get_handle(PyObject* capsule, const char* name) { void* h = 0; if (!PyCapsule_CheckExact(capsule)) { PyErr_SetString(PyExc_RuntimeError, "Object is not a PyCapsule."); return 0; } if (!(h = PyCapsule_GetPointer(capsule, name))) { PyErr_Format(PyExc_RuntimeError, "Capsule is not of type %s.", name); return 0; } return h; } static void vis_block_free(PyObject* capsule) { int status = 0; oskar_vis_block_free((oskar_VisBlock*) get_handle(capsule, name), &status); } static PyObject* auto_correlations(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; oskar_Mem* m = 0; PyObject *capsule = 0; PyArrayObject *array = 0; npy_intp dims[4]; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; /* Check that auto-correlations exist. */ if (!oskar_vis_block_has_auto_correlations(h)) { PyErr_SetString(PyExc_RuntimeError, "No auto-correlations in block."); return 0; } /* Return an array reference to Python. */ m = oskar_vis_block_auto_correlations(h); dims[0] = oskar_vis_block_num_times(h); dims[1] = oskar_vis_block_num_channels(h); dims[2] = oskar_vis_block_num_stations(h); dims[3] = oskar_vis_block_num_pols(h); array = (PyArrayObject*)PyArray_SimpleNewFromData(4, dims, (oskar_mem_is_double(m) ? NPY_CDOUBLE : NPY_CFLOAT), oskar_mem_void(m)); return Py_BuildValue("N", array); /* Don't increment refcount. */ } static PyObject* capsule_name(PyObject* self, PyObject* args) { PyObject *capsule = 0; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!PyCapsule_CheckExact(capsule)) { PyErr_SetString(PyExc_RuntimeError, "Object is not a PyCapsule."); return 0; } return Py_BuildValue("s", PyCapsule_GetName(capsule)); } static PyObject* create_from_header(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; oskar_VisHeader* hdr = 0; PyObject *capsule = 0, *header = 0; int status = 0; if (!PyArg_ParseTuple(args, "O", &header)) return 0; if (!(hdr = (oskar_VisHeader*) get_handle(header, "oskar_VisHeader"))) return 0; h = oskar_vis_block_create_from_header(OSKAR_CPU, hdr, &status); capsule = PyCapsule_New((void*)h, name, (PyCapsule_Destructor)vis_block_free); return Py_BuildValue("N", capsule); /* Don't increment refcount. */ } static PyObject* baseline_uu_metres(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; oskar_Mem* m = 0; PyObject *capsule = 0; PyArrayObject *array = 0; npy_intp dims[2]; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; /* Check that cross-correlations exist. */ if (!oskar_vis_block_has_cross_correlations(h)) { PyErr_SetString(PyExc_RuntimeError, "No cross-correlations in block."); return 0; } /* Return an array reference to Python. */ m = oskar_vis_block_baseline_uu_metres(h); dims[0] = oskar_vis_block_num_times(h); dims[1] = oskar_vis_block_num_baselines(h); array = (PyArrayObject*)PyArray_SimpleNewFromData(2, dims, (oskar_mem_is_double(m) ? NPY_DOUBLE : NPY_FLOAT), oskar_mem_void(m)); return Py_BuildValue("N", array); /* Don't increment refcount. */ } static PyObject* baseline_vv_metres(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; oskar_Mem* m = 0; PyObject *capsule = 0; PyArrayObject *array = 0; npy_intp dims[2]; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; /* Check that cross-correlations exist. */ if (!oskar_vis_block_has_cross_correlations(h)) { PyErr_SetString(PyExc_RuntimeError, "No cross-correlations in block."); return 0; } /* Return an array reference to Python. */ m = oskar_vis_block_baseline_vv_metres(h); dims[0] = oskar_vis_block_num_times(h); dims[1] = oskar_vis_block_num_baselines(h); array = (PyArrayObject*)PyArray_SimpleNewFromData(2, dims, (oskar_mem_is_double(m) ? NPY_DOUBLE : NPY_FLOAT), oskar_mem_void(m)); return Py_BuildValue("N", array); /* Don't increment refcount. */ } static PyObject* baseline_ww_metres(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; oskar_Mem* m = 0; PyObject *capsule = 0; PyArrayObject *array = 0; npy_intp dims[2]; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; /* Check that cross-correlations exist. */ if (!oskar_vis_block_has_cross_correlations(h)) { PyErr_SetString(PyExc_RuntimeError, "No cross-correlations in block."); return 0; } /* Return an array reference to Python. */ m = oskar_vis_block_baseline_ww_metres(h); dims[0] = oskar_vis_block_num_times(h); dims[1] = oskar_vis_block_num_baselines(h); array = (PyArrayObject*)PyArray_SimpleNewFromData(2, dims, (oskar_mem_is_double(m) ? NPY_DOUBLE : NPY_FLOAT), oskar_mem_void(m)); return Py_BuildValue("N", array); /* Don't increment refcount. */ } static PyObject* cross_correlations(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; oskar_Mem* m = 0; PyObject *capsule = 0; PyArrayObject *array = 0; npy_intp dims[4]; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; /* Check that cross-correlations exist. */ if (!oskar_vis_block_has_cross_correlations(h)) { PyErr_SetString(PyExc_RuntimeError, "No cross-correlations in block."); return 0; } /* Return an array reference to Python. */ m = oskar_vis_block_cross_correlations(h); dims[0] = oskar_vis_block_num_times(h); dims[1] = oskar_vis_block_num_channels(h); dims[2] = oskar_vis_block_num_baselines(h); dims[3] = oskar_vis_block_num_pols(h); array = (PyArrayObject*)PyArray_SimpleNewFromData(4, dims, (oskar_mem_is_double(m) ? NPY_CDOUBLE : NPY_CFLOAT), oskar_mem_void(m)); return Py_BuildValue("N", array); /* Don't increment refcount. */ } static PyObject* num_baselines(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; PyObject* capsule = 0; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; return Py_BuildValue("i", oskar_vis_block_num_baselines(h)); } static PyObject* num_channels(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; PyObject* capsule = 0; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; return Py_BuildValue("i", oskar_vis_block_num_channels(h)); } static PyObject* num_pols(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; PyObject* capsule = 0; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; return Py_BuildValue("i", oskar_vis_block_num_pols(h)); } static PyObject* num_stations(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; PyObject* capsule = 0; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; return Py_BuildValue("i", oskar_vis_block_num_stations(h)); } static PyObject* num_times(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; PyObject* capsule = 0; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; return Py_BuildValue("i", oskar_vis_block_num_times(h)); } static PyObject* start_channel_index(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; PyObject* capsule = 0; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; return Py_BuildValue("i", oskar_vis_block_start_channel_index(h)); } static PyObject* start_time_index(PyObject* self, PyObject* args) { oskar_VisBlock* h = 0; PyObject* capsule = 0; if (!PyArg_ParseTuple(args, "O", &capsule)) return 0; if (!(h = (oskar_VisBlock*) get_handle(capsule, name))) return 0; return Py_BuildValue("i", oskar_vis_block_start_time_index(h)); } /* Method table. */ static PyMethodDef methods[] = { {"auto_correlations", (PyCFunction)auto_correlations, METH_VARARGS, "auto_correlations()"}, {"capsule_name", (PyCFunction)capsule_name, METH_VARARGS, "capsule_name()"}, {"create_from_header", (PyCFunction)create_from_header, METH_VARARGS, "create_from_header(header)"}, {"baseline_uu_metres", (PyCFunction)baseline_uu_metres, METH_VARARGS, "baseline_uu_metres()"}, {"baseline_vv_metres", (PyCFunction)baseline_vv_metres, METH_VARARGS, "baseline_vv_metres()"}, {"baseline_ww_metres", (PyCFunction)baseline_ww_metres, METH_VARARGS, "baseline_ww_metres()"}, {"cross_correlations", (PyCFunction)cross_correlations, METH_VARARGS, "cross_correlations()"}, {"num_baselines", (PyCFunction)num_baselines, METH_VARARGS, "num_baselines()"}, {"num_channels", (PyCFunction)num_channels, METH_VARARGS, "num_channels()"}, {"num_pols", (PyCFunction)num_pols, METH_VARARGS, "num_pols()"}, {"num_stations", (PyCFunction)num_stations, METH_VARARGS, "num_stations()"}, {"num_times", (PyCFunction)num_times, METH_VARARGS, "num_times()"}, {"start_channel_index", (PyCFunction)start_channel_index, METH_VARARGS, "start_channel_index()"}, {"start_time_index", (PyCFunction)start_time_index, METH_VARARGS, "start_time_index()"}, {NULL, NULL, 0, NULL} }; #if PY_MAJOR_VERSION >= 3 static PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_vis_block_lib", /* m_name */ module_doc, /* m_doc */ -1, /* m_size */ methods /* m_methods */ }; #endif static PyObject* moduleinit(void) { PyObject* m; #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else m = Py_InitModule3("_vis_block_lib", methods, module_doc); #endif return m; } #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit__vis_block_lib(void) { import_array(); return moduleinit(); } #else /* The init function name has to match that of the compiled module * with the pattern 'init<module name>'. This module is called '_vis_block_lib' */ PyMODINIT_FUNC init_vis_block_lib(void) { import_array(); moduleinit(); return; } #endif
davepallot/OSKAR
oskar/telescope/station/element/src/oskar_element_evaluate.c
/* * Copyright (c) 2012-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/element/private_element.h" #include "telescope/station/element/oskar_element.h" #include "telescope/station/element/oskar_apply_element_taper_cosine.h" #include "telescope/station/element/oskar_apply_element_taper_gaussian.h" #include "telescope/station/element/oskar_evaluate_dipole_pattern.h" #include "telescope/station/element/oskar_evaluate_geometric_dipole_pattern.h" #include "convert/oskar_convert_enu_directions_to_theta_phi.h" #include "convert/oskar_convert_ludwig3_to_theta_phi_components.h" #include "math/oskar_find_closest_match.h" #include "math/oskar_cmath.h" #define C_0 299792458.0 #ifdef __cplusplus extern "C" { #endif void oskar_element_evaluate(const oskar_Element* model, oskar_Mem* output, double orientation_x, double orientation_y, int num_points, const oskar_Mem* x, const oskar_Mem* y, const oskar_Mem* z, double frequency_hz, oskar_Mem* theta, oskar_Mem* phi, int* status) { int element_type, taper_type, freq_id; double dipole_length_m; /* Check if safe to proceed. */ if (*status) return; /* Check that the output array is complex. */ if (!oskar_mem_is_complex(output)) { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } /* Resize output array if required. */ if ((int)oskar_mem_length(output) < num_points) oskar_mem_realloc(output, num_points, status); /* Get the element model properties. */ element_type = model->element_type; taper_type = model->taper_type; dipole_length_m = model->dipole_length; if (model->dipole_length_units == OSKAR_WAVELENGTHS) dipole_length_m *= (C_0 / frequency_hz); /* Check if element type is isotropic. */ if (element_type == OSKAR_ELEMENT_TYPE_ISOTROPIC) oskar_mem_set_value_real(output, 1.0, 0, 0, status); /* Ensure there is enough space in the theta and phi work arrays. */ if ((int)oskar_mem_length(theta) < num_points) oskar_mem_realloc(theta, num_points, status); if ((int)oskar_mem_length(phi) < num_points) oskar_mem_realloc(phi, num_points, status); /* Compute modified theta and phi coordinates for dipole X. */ oskar_convert_enu_directions_to_theta_phi(num_points, x, y, z, M_PI_2 - orientation_x, theta, phi, status); /* Evaluate polarised response if output array is matrix type. */ if (oskar_mem_is_matrix(output)) { /* Check if spline data present for dipole X. */ if (oskar_element_has_x_spline_data(model)) { /* Get the frequency index. */ freq_id = oskar_find_closest_match_d(frequency_hz, oskar_element_num_freq(model), oskar_element_freqs_hz_const(model)); /* Evaluate spline pattern for dipole X. */ oskar_splines_evaluate(output, 0, 8, model->x_h_re[freq_id], num_points, theta, phi, status); oskar_splines_evaluate(output, 1, 8, model->x_h_im[freq_id], num_points, theta, phi, status); oskar_splines_evaluate(output, 2, 8, model->x_v_re[freq_id], num_points, theta, phi, status); oskar_splines_evaluate(output, 3, 8, model->x_v_im[freq_id], num_points, theta, phi, status); /* Convert from Ludwig-3 to spherical representation. */ oskar_convert_ludwig3_to_theta_phi_components(output, 0, 4, num_points, phi, status); } else if (element_type == OSKAR_ELEMENT_TYPE_DIPOLE) { /* Evaluate dipole pattern for dipole X. */ oskar_evaluate_dipole_pattern(output, num_points, theta, phi, frequency_hz, dipole_length_m, 0, 4, status); } else if (element_type == OSKAR_ELEMENT_TYPE_GEOMETRIC_DIPOLE) { /* Evaluate dipole pattern for dipole X. */ oskar_evaluate_geometric_dipole_pattern(output, num_points, theta, phi, 0, 4, status); } /* Compute modified theta and phi coordinates for dipole Y. */ oskar_convert_enu_directions_to_theta_phi(num_points, x, y, z, M_PI_2 - orientation_y, theta, phi, status); /* Check if spline data present for dipole Y. */ if (oskar_element_has_y_spline_data(model)) { /* Get the frequency index. */ freq_id = oskar_find_closest_match_d(frequency_hz, oskar_element_num_freq(model), oskar_element_freqs_hz_const(model)); /* Evaluate spline pattern for dipole Y. */ oskar_splines_evaluate(output, 4, 8, model->y_h_re[freq_id], num_points, theta, phi, status); oskar_splines_evaluate(output, 5, 8, model->y_h_im[freq_id], num_points, theta, phi, status); oskar_splines_evaluate(output, 6, 8, model->y_v_re[freq_id], num_points, theta, phi, status); oskar_splines_evaluate(output, 7, 8, model->y_v_im[freq_id], num_points, theta, phi, status); /* Convert from Ludwig-3 to spherical representation. */ oskar_convert_ludwig3_to_theta_phi_components(output, 2, 4, num_points, phi, status); } else if (element_type == OSKAR_ELEMENT_TYPE_DIPOLE) { /* Evaluate dipole pattern for dipole Y. */ oskar_evaluate_dipole_pattern(output, num_points, theta, phi, frequency_hz, dipole_length_m, 2, 4, status); } else if (element_type == OSKAR_ELEMENT_TYPE_GEOMETRIC_DIPOLE) { /* Evaluate dipole pattern for dipole Y. */ oskar_evaluate_geometric_dipole_pattern(output, num_points, theta, phi, 2, 4, status); } } /* Scalar response. */ else { /* Check if scalar spline data present. */ if (oskar_element_has_scalar_spline_data(model)) { /* Get the frequency index. */ freq_id = oskar_find_closest_match_d(frequency_hz, oskar_element_num_freq(model), oskar_element_freqs_hz_const(model)); oskar_splines_evaluate(output, 0, 2, model->scalar_re[freq_id], num_points, theta, phi, status); oskar_splines_evaluate(output, 1, 2, model->scalar_im[freq_id], num_points, theta, phi, status); } else if (element_type == OSKAR_ELEMENT_TYPE_DIPOLE) { oskar_evaluate_dipole_pattern(output, num_points, theta, phi, frequency_hz, dipole_length_m, 0, 1, status); } else if (element_type == OSKAR_ELEMENT_TYPE_GEOMETRIC_DIPOLE) { oskar_evaluate_geometric_dipole_pattern(output, num_points, theta, phi, 0, 1, status); } } /* Apply element tapering, if specified. */ if (taper_type == OSKAR_ELEMENT_TAPER_COSINE) { oskar_apply_element_taper_cosine(output, num_points, model->cosine_power, theta, status); } else if (taper_type == OSKAR_ELEMENT_TAPER_GAUSSIAN) { oskar_apply_element_taper_gaussian(output, num_points, model->gaussian_fwhm_rad, theta, status); } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/convert/oskar_convert_enu_directions_to_theta_phi_cuda.h
<filename>oskar/convert/oskar_convert_enu_directions_to_theta_phi_cuda.h /* * Copyright (c) 2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_CONVERT_ENU_DIRECTIONS_TO_THETA_PHI_CUDA_H_ #define OSKAR_CONVERT_ENU_DIRECTIONS_TO_THETA_PHI_CUDA_H_ /** * @file oskar_convert_enu_directions_to_theta_phi_cuda.h */ #include <oskar_global.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * CUDA function to compute theta and phi angles from horizontal direction * cosines (single precision). * * @details * Computes the angles theta and phi from the given horizontal direction * cosines. * * The directions are: * - x: pointing East, * - y: pointing North, * - z: pointing to the zenith. * * Theta is the polar angle from the z-axis to the xy-plane, and phi is the * azimuthal angle from the x-axis to the y-axis. * * Note that all pointers refer to device memory. * * @param[in] num_points The number of points. * @param[in] d_x The x-direction-cosines. * @param[in] d_y The y-direction-cosines. * @param[in] d_z The z-direction-cosines. * @param[in] delta_phi Angle to add to computed values of phi. * @param[out] d_theta The theta angles, in radians. * @param[out] d_phi The phi angles, in radians. */ OSKAR_EXPORT void oskar_convert_enu_directions_to_theta_phi_cuda_f(int num_points, const float* d_x, const float* d_y, const float* d_z, float delta_phi, float* d_theta, float* d_phi); /** * @brief * Function to compute azimuth and elevation from horizontal direction * cosines (double precision). * * @details * Computes the angles theta and phi from the given horizontal direction * cosines. * * The directions are: * - x: pointing East, * - y: pointing North, * - z: pointing to the zenith. * * Theta is the polar angle from the z-axis to the xy-plane, and phi is the * azimuthal angle from the x-axis to the y-axis. * * Note that all pointers refer to device memory. * * @param[in] num_points The number of points. * @param[in] d_x The x-direction-cosines. * @param[in] d_y The y-direction-cosines. * @param[in] d_z The z-direction-cosines. * @param[in] delta_phi Angle to add to computed values of phi. * @param[out] d_theta The theta angles, in radians. * @param[out] d_phi The phi angles, in radians. */ OSKAR_EXPORT void oskar_convert_enu_directions_to_theta_phi_cuda_d(int num_points, const double* d_x, const double* d_y, const double* d_z, double delta_phi, double* d_theta, double* d_phi); #ifdef __CUDACC__ /* Kernels. */ __global__ void oskar_convert_enu_directions_to_theta_phi_cudak_f( const int num_points, const float* restrict x, const float* restrict y, const float* restrict z, const float delta_phi, float* restrict theta, float* restrict phi); __global__ void oskar_convert_enu_directions_to_theta_phi_cudak_d( const int num_points, const double* restrict x, const double* restrict y, const double* restrict z, const double delta_phi, double* restrict theta, double* restrict phi); #endif /* __CUDACC__ */ #ifdef __cplusplus } #endif #endif /* OSKAR_CONVERT_ENU_DIRECTIONS_TO_THETA_PHI_CUDA_H_ */
davepallot/OSKAR
oskar/beam_pattern/src/oskar_beam_pattern_run.c
/* * Copyright (c) 2012-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "beam_pattern/oskar_beam_pattern.h" #include "beam_pattern/private_beam_pattern.h" #include "convert/oskar_convert_mjd_to_gast_fast.h" #include "correlate/oskar_evaluate_auto_power.h" #include "correlate/oskar_evaluate_cross_power.h" #include "telescope/station/oskar_evaluate_station_beam.h" #include "math/oskar_cmath.h" #include "math/private_cond2_2x2.h" #include "utility/oskar_cuda_mem_log.h" #include "utility/oskar_device_utils.h" #include "utility/oskar_file_exists.h" #include "utility/oskar_get_memory_usage.h" #include "oskar_version.h" #include <stdlib.h> #include <string.h> #include <fitsio.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef __cplusplus extern "C" { #endif static void* run_blocks(void* arg); static void sim_chunks(oskar_BeamPattern* h, int i_chunk_start, int i_time, int i_channel, int i_active, int device_id, int* status); static void write_chunks(oskar_BeamPattern* h, int i_chunk_start, int i_time, int i_channel, int i_active, int* status); static void write_pixels(oskar_BeamPattern* h, int i_chunk, int i_time, int i_channel, int num_pix, int channel_average, int time_average, const oskar_Mem* in, int chunk_desc, int stokes_in, int* status); static void complex_to_amp(const oskar_Mem* complex_in, const int offset, const int stride, const int num_points, oskar_Mem* output, int* status); static void complex_to_phase(const oskar_Mem* complex_in, const int offset, const int stride, const int num_points, oskar_Mem* output, int* status); static void jones_to_ixr(const oskar_Mem* complex_in, const int offset, const int num_points, oskar_Mem* output, int* status); static void power_to_stokes_I(const oskar_Mem* power_in, const int offset, const int num_points, oskar_Mem* output, int* status); static void power_to_stokes_Q(const oskar_Mem* power_in, const int offset, const int num_points, oskar_Mem* output, int* status); static void power_to_stokes_U(const oskar_Mem* power_in, const int offset, const int num_points, oskar_Mem* output, int* status); static void power_to_stokes_V(const oskar_Mem* power_in, const int offset, const int num_points, oskar_Mem* output, int* status); static void record_timing(oskar_BeamPattern* h); static unsigned int disp_width(unsigned int value); struct ThreadArgs { oskar_BeamPattern* h; int num_threads, thread_id; }; typedef struct ThreadArgs ThreadArgs; void oskar_beam_pattern_run(oskar_BeamPattern* h, int* status) { int i, num_threads; oskar_Thread** threads = 0; ThreadArgs* args = 0; if (*status || !h) return; /* Check root name exists. */ if (!h->root_path) { oskar_log_error(h->log, "No output file name specified."); *status = OSKAR_ERR_FILE_IO; return; } /* Initialise if required. */ oskar_beam_pattern_check_init(h, status); /* Set up worker threads. */ num_threads = h->num_devices + 1; oskar_barrier_set_num_threads(h->barrier, num_threads); threads = (oskar_Thread**) calloc(num_threads, sizeof(oskar_Thread*)); args = (ThreadArgs*) calloc(num_threads, sizeof(ThreadArgs)); for (i = 0; i < num_threads; ++i) { args[i].h = h; args[i].num_threads = num_threads; args[i].thread_id = i; } /* Record memory usage. */ if (h->log && !*status) { #ifdef OSKAR_HAVE_CUDA oskar_log_section(h->log, 'M', "Initial memory usage"); for (i = 0; i < h->num_gpus; ++i) oskar_cuda_mem_log(h->log, 0, h->gpu_ids[i]); #endif oskar_log_section(h->log, 'M', "Starting simulation..."); } /* Set status code. */ h->status = *status; /* Start simulation timer. */ oskar_timer_start(h->tmr_sim); /* Start the worker threads. */ for (i = 0; i < num_threads; ++i) threads[i] = oskar_thread_create(run_blocks, (void*)&args[i], 0); /* Wait for worker threads to finish. */ for (i = 0; i < num_threads; ++i) { oskar_thread_join(threads[i]); oskar_thread_free(threads[i]); } free(threads); free(args); /* Get status code. */ *status = h->status; /* Record memory usage. */ if (h->log && !*status) { #ifdef OSKAR_HAVE_CUDA oskar_log_section(h->log, 'M', "Final memory usage"); for (i = 0; i < h->num_gpus; ++i) oskar_cuda_mem_log(h->log, 0, h->gpu_ids[i]); #endif /* Record time taken. */ oskar_log_set_value_width(h->log, 25); record_timing(h); } /* Finalise. */ oskar_beam_pattern_reset_cache(h, status); } /* Private methods. */ static void* run_blocks(void* arg) { oskar_BeamPattern* h; int i_inner, i_outer, num_inner, num_outer, c, t, f; int thread_id, device_id, num_threads, *status; /* Loop indices for previous iteration (accessed only by thread 0). */ int cp = 0, tp = 0, fp = 0; /* Get thread function arguments. */ h = ((ThreadArgs*)arg)->h; num_threads = ((ThreadArgs*)arg)->num_threads; thread_id = ((ThreadArgs*)arg)->thread_id; device_id = thread_id - 1; status = &(h->status); #ifdef _OPENMP /* Disable any nested parallelism. */ omp_set_nested(0); omp_set_num_threads(1); #endif if (device_id >= 0 && device_id < h->num_gpus) oskar_device_set(h->gpu_ids[device_id], status); /* Set ranges of inner and outer loops based on averaging mode. */ if (h->average_single_axis != 'T') { num_outer = h->num_time_steps; num_inner = h->num_channels; /* Channel on inner loop. */ } else { num_outer = h->num_channels; num_inner = h->num_time_steps; /* Time on inner loop. */ } /* Loop over image pixel chunks, running simulation and file writing one * chunk at a time. Simulation and file output are overlapped by using * double buffering, and a dedicated thread is used for file output. * * Thread 0 is used for file writes. * Threads 1 to n (mapped to compute devices) do the simulation. */ for (c = 0; c < h->num_chunks; c += h->num_devices) { for (i_outer = 0; i_outer < num_outer; ++i_outer) { for (i_inner = 0; i_inner < num_inner; ++i_inner) { /* Set time and channel indices based on averaging mode. */ if (h->average_single_axis != 'T') { t = i_outer; f = i_inner; } else { f = i_outer; t = i_inner; } if (thread_id > 0 || num_threads == 1) sim_chunks(h, c, t, f, h->i_global & 1, device_id, status); if (thread_id == 0 && h->i_global > 0) write_chunks(h, cp, tp, fp, h->i_global & 1, status); /* Barrier 1: Set indices of the previous chunk(s). */ oskar_barrier_wait(h->barrier); if (thread_id == 0) { cp = c; tp = t; fp = f; h->i_global++; } /* Barrier 2: Check sim and write are done. */ oskar_barrier_wait(h->barrier); } } } /* Write the very last chunk(s). */ if (thread_id == 0) write_chunks(h, cp, tp, fp, h->i_global & 1, status); return 0; } static void sim_chunks(oskar_BeamPattern* h, int i_chunk_start, int i_time, int i_channel, int i_active, int device_id, int* status) { int chunk_size, i_chunk, i; double dt_dump, mjd, gast, freq_hz; oskar_Mem *input_alias, *output_alias; DeviceData* d; /* Check if safe to proceed. */ if (*status) return; /* Get chunk index from GPU ID and chunk start, * and return immediately if it's out of range. */ d = &h->d[device_id]; i_chunk = i_chunk_start + device_id; if (i_chunk >= h->num_chunks) return; /* Get time and frequency values. */ oskar_timer_resume(d->tmr_compute); dt_dump = h->time_inc_sec / 86400.0; mjd = h->time_start_mjd_utc + dt_dump * (i_time + 0.5); gast = oskar_convert_mjd_to_gast_fast(mjd); freq_hz = h->freq_start_hz + i_channel * h->freq_inc_hz; /* Work out the size of the chunk. */ chunk_size = h->max_chunk_size; if ((i_chunk + 1) * h->max_chunk_size > h->num_pixels) chunk_size = h->num_pixels - i_chunk * h->max_chunk_size; /* Copy pixel chunk coordinate data to GPU only if chunk is different. */ if (i_chunk != d->previous_chunk_index) { d->previous_chunk_index = i_chunk; oskar_mem_copy_contents(d->x, h->x, 0, i_chunk * h->max_chunk_size, chunk_size, status); oskar_mem_copy_contents(d->y, h->y, 0, i_chunk * h->max_chunk_size, chunk_size, status); oskar_mem_copy_contents(d->z, h->z, 0, i_chunk * h->max_chunk_size, chunk_size, status); } /* Generate beam for this pixel chunk, for all active stations. */ input_alias = oskar_mem_create_alias(0, 0, 0, status); output_alias = oskar_mem_create_alias(0, 0, 0, status); for (i = 0; i < h->num_active_stations; ++i) { oskar_mem_set_alias(input_alias, d->jones_data, i * chunk_size, chunk_size, status); oskar_mem_set_alias(output_alias, d->jones_data, i * chunk_size, chunk_size, status); oskar_evaluate_station_beam(output_alias, chunk_size, h->coord_type, d->x, d->y, d->z, oskar_telescope_phase_centre_ra_rad(d->tel), oskar_telescope_phase_centre_dec_rad(d->tel), oskar_telescope_station_const(d->tel, h->station_ids[i]), d->work, i_time, freq_hz, gast, status); if (d->auto_power[I]) { oskar_mem_set_alias(output_alias, d->auto_power[I], i * chunk_size, chunk_size, status); oskar_evaluate_auto_power(chunk_size, input_alias, output_alias, status); } #if 0 if (d->auto_power[Q]) { oskar_mem_set_alias(output_alias, d->auto_power[Q], i * chunk_size, chunk_size, status); oskar_evaluate_auto_power_stokes_q(chunk_size, input_alias, output_alias, status); } if (d->auto_power[U]) { oskar_mem_set_alias(output_alias, d->auto_power[U], i * chunk_size, chunk_size, status); oskar_evaluate_auto_power_stokes_u(chunk_size, input_alias, output_alias, status); } #endif } if (d->cross_power[I]) oskar_evaluate_cross_power(chunk_size, h->num_active_stations, d->jones_data, d->cross_power[I], status); oskar_mem_free(input_alias, status); oskar_mem_free(output_alias, status); /* Copy the output data into host memory. */ if (d->jones_data_cpu[i_active]) oskar_mem_copy_contents(d->jones_data_cpu[i_active], d->jones_data, 0, 0, chunk_size * h->num_active_stations, status); for (i = 0; i < 4; ++i) { if (d->auto_power[i]) oskar_mem_copy_contents(d->auto_power_cpu[i][i_active], d->auto_power[i], 0, 0, chunk_size * h->num_active_stations, status); if (d->cross_power[i]) oskar_mem_copy_contents(d->cross_power_cpu[i][i_active], d->cross_power[i], 0, 0, chunk_size, status); } if (h->log) { oskar_mutex_lock(h->mutex); oskar_log_message(h->log, 'S', 1, "Chunk %*i/%i, " "Time %*i/%i, Channel %*i/%i [Device %i]", disp_width(h->num_chunks), i_chunk+1, h->num_chunks, disp_width(h->num_time_steps), i_time+1, h->num_time_steps, disp_width(h->num_channels), i_channel+1, h->num_channels, device_id); oskar_mutex_unlock(h->mutex); } oskar_timer_pause(d->tmr_compute); } static void write_chunks(oskar_BeamPattern* h, int i_chunk_start, int i_time, int i_channel, int i_active, int* status) { int i, i_chunk, chunk_sources, chunk_size, stokes; if (*status) return; /* Write inactive chunk(s) from all GPUs. */ oskar_timer_resume(h->tmr_write); for (i = 0; i < h->num_devices; ++i) { DeviceData* d = &h->d[i]; /* Get chunk index from GPU ID & chunk start. Stop if out of range. */ i_chunk = i_chunk_start + i; if (i_chunk >= h->num_chunks || *status) break; /* Get the size of the chunk. */ chunk_sources = h->max_chunk_size; if ((i_chunk + 1) * h->max_chunk_size > h->num_pixels) chunk_sources = h->num_pixels - i_chunk * h->max_chunk_size; chunk_size = chunk_sources * h->num_active_stations; /* Write non-averaged raw data, if required. */ write_pixels(h, i_chunk, i_time, i_channel, chunk_sources, 0, 0, d->jones_data_cpu[!i_active], JONES_DATA, -1, status); /* Loop over Stokes parameters. */ for (stokes = 0; stokes < 4; ++stokes) { /* Write non-averaged data, if required. */ write_pixels(h, i_chunk, i_time, i_channel, chunk_sources, 0, 0, d->auto_power_cpu[stokes][!i_active], AUTO_POWER_DATA, stokes, status); write_pixels(h, i_chunk, i_time, i_channel, chunk_sources, 0, 0, d->cross_power_cpu[stokes][!i_active], CROSS_POWER_DATA, stokes, status); /* Time-average the data if required. */ if (d->auto_power_time_avg[stokes]) oskar_mem_add(d->auto_power_time_avg[stokes], d->auto_power_time_avg[stokes], d->auto_power_cpu[stokes][!i_active], chunk_size, status); if (d->cross_power_time_avg[stokes]) oskar_mem_add(d->cross_power_time_avg[stokes], d->cross_power_time_avg[stokes], d->cross_power_cpu[stokes][!i_active], chunk_sources, status); /* Channel-average the data if required. */ if (d->auto_power_channel_avg[stokes]) oskar_mem_add(d->auto_power_channel_avg[stokes], d->auto_power_channel_avg[stokes], d->auto_power_cpu[stokes][!i_active], chunk_size, status); if (d->cross_power_channel_avg[stokes]) oskar_mem_add(d->cross_power_channel_avg[stokes], d->cross_power_channel_avg[stokes], d->cross_power_cpu[stokes][!i_active], chunk_sources, status); /* Channel- and time-average the data if required. */ if (d->auto_power_channel_and_time_avg[stokes]) oskar_mem_add(d->auto_power_channel_and_time_avg[stokes], d->auto_power_channel_and_time_avg[stokes], d->auto_power_cpu[stokes][!i_active], chunk_size, status); if (d->cross_power_channel_and_time_avg[stokes]) oskar_mem_add(d->cross_power_channel_and_time_avg[stokes], d->cross_power_channel_and_time_avg[stokes], d->cross_power_cpu[stokes][!i_active], chunk_sources, status); /* Write time-averaged data. */ if (i_time == h->num_time_steps - 1) { if (d->auto_power_time_avg[stokes]) { oskar_mem_scale_real(d->auto_power_time_avg[stokes], 1.0 / h->num_time_steps, status); write_pixels(h, i_chunk, 0, i_channel, chunk_sources, 0, 1, d->auto_power_time_avg[stokes], AUTO_POWER_DATA, stokes, status); oskar_mem_clear_contents(d->auto_power_time_avg[stokes], status); } if (d->cross_power_time_avg[stokes]) { oskar_mem_scale_real(d->cross_power_time_avg[stokes], 1.0 / h->num_time_steps, status); write_pixels(h, i_chunk, 0, i_channel, chunk_sources, 0, 1, d->cross_power_time_avg[stokes], CROSS_POWER_DATA, stokes, status); oskar_mem_clear_contents(d->cross_power_time_avg[stokes], status); } } /* Write channel-averaged data. */ if (i_channel == h->num_channels - 1) { if (d->auto_power_channel_avg[stokes]) { oskar_mem_scale_real(d->auto_power_channel_avg[stokes], 1.0 / h->num_channels, status); write_pixels(h, i_chunk, i_time, 0, chunk_sources, 1, 0, d->auto_power_channel_avg[stokes], AUTO_POWER_DATA, stokes, status); oskar_mem_clear_contents(d->auto_power_channel_avg[stokes], status); } if (d->cross_power_channel_avg[stokes]) { oskar_mem_scale_real(d->cross_power_channel_avg[stokes], 1.0 / h->num_channels, status); write_pixels(h, i_chunk, i_time, 0, chunk_sources, 1, 0, d->cross_power_channel_avg[stokes], CROSS_POWER_DATA, stokes, status); oskar_mem_clear_contents( d->cross_power_channel_avg[stokes], status); } } /* Write channel- and time-averaged data. */ if ((i_time == h->num_time_steps - 1) && (i_channel == h->num_channels - 1)) { if (d->auto_power_channel_and_time_avg[stokes]) { oskar_mem_scale_real( d->auto_power_channel_and_time_avg[stokes], 1.0 / (h->num_channels * h->num_time_steps), status); write_pixels(h, i_chunk, 0, 0, chunk_sources, 1, 1, d->auto_power_channel_and_time_avg[stokes], AUTO_POWER_DATA, stokes, status); oskar_mem_clear_contents( d->auto_power_channel_and_time_avg[stokes], status); } if (d->cross_power_channel_and_time_avg[stokes]) { oskar_mem_scale_real( d->cross_power_channel_and_time_avg[stokes], 1.0 / (h->num_channels * h->num_time_steps), status); write_pixels(h, i_chunk, 0, 0, chunk_sources, 1, 1, d->cross_power_channel_and_time_avg[stokes], CROSS_POWER_DATA, stokes, status); oskar_mem_clear_contents( d->cross_power_channel_and_time_avg[stokes], status); } } } } oskar_timer_pause(h->tmr_write); } static void write_pixels(oskar_BeamPattern* h, int i_chunk, int i_time, int i_channel, int num_pix, int channel_average, int time_average, const oskar_Mem* in, int chunk_desc, int stokes_in, int* status) { int i, num_pol; if (!in) return; /* Loop over data products. */ num_pol = h->pol_mode == OSKAR_POL_MODE_FULL ? 4 : 1; for (i = 0; i < h->num_data_products; ++i) { fitsfile* f; FILE* t; int dp, stokes_out, i_station, off; /* Get data product info. */ f = h->data_products[i].fits_file; t = h->data_products[i].text_file; dp = h->data_products[i].type; stokes_out = h->data_products[i].stokes_out; i_station = h->data_products[i].i_station; /* Check averaging mode and polarisation input type. */ if (h->data_products[i].time_average != time_average || h->data_products[i].channel_average != channel_average || h->data_products[i].stokes_in != stokes_in) continue; /* Treat raw data output as special case, as it doesn't go via pix. */ if (dp == RAW_COMPLEX && chunk_desc == JONES_DATA && t) { oskar_Mem* station_data; station_data = oskar_mem_create_alias(in, i_station * num_pix, num_pix, status); oskar_mem_save_ascii(t, 1, num_pix, status, station_data); oskar_mem_free(station_data, status); continue; } if (dp == CROSS_POWER_RAW_COMPLEX && chunk_desc == CROSS_POWER_DATA && t) { oskar_mem_save_ascii(t, 1, num_pix, status, in); continue; } /* Convert complex values to pixel data. */ oskar_mem_clear_contents(h->pix, status); if (chunk_desc == JONES_DATA && dp == AMP) { off = i_station * num_pix * num_pol; if (stokes_out == XX || stokes_out == -1) complex_to_amp(in, off, num_pol, num_pix, h->pix, status); else if (stokes_out == XY) complex_to_amp(in, off + 1, num_pol, num_pix, h->pix, status); else if (stokes_out == YX) complex_to_amp(in, off + 2, num_pol, num_pix, h->pix, status); else if (stokes_out == YY) complex_to_amp(in, off + 3, num_pol, num_pix, h->pix, status); else continue; } else if (chunk_desc == JONES_DATA && dp == PHASE) { off = i_station * num_pix * num_pol; if (stokes_out == XX || stokes_out == -1) complex_to_phase(in, off, num_pol, num_pix, h->pix, status); else if (stokes_out == XY) complex_to_phase(in, off + 1, num_pol, num_pix, h->pix, status); else if (stokes_out == XY) complex_to_phase(in, off + 2, num_pol, num_pix, h->pix, status); else if (stokes_out == YX) complex_to_phase(in, off + 3, num_pol, num_pix, h->pix, status); else continue; } else if (chunk_desc == JONES_DATA && dp == IXR) jones_to_ixr(in, i_station * num_pix, num_pix, h->pix, status); else if (chunk_desc == AUTO_POWER_DATA || chunk_desc == CROSS_POWER_DATA) { off = i_station * num_pix; /* Station offset. */ if (off < 0 || chunk_desc == CROSS_POWER_DATA) off = 0; if (chunk_desc == CROSS_POWER_DATA && dp == AUTO_POWER) continue; if (chunk_desc == AUTO_POWER_DATA && (dp == CROSS_POWER_AMP || dp == CROSS_POWER_PHASE)) continue; if (stokes_out == I) power_to_stokes_I(in, off, num_pix, h->ctemp, status); else if (stokes_out == Q) power_to_stokes_Q(in, off, num_pix, h->ctemp, status); else if (stokes_out == U) power_to_stokes_U(in, off, num_pix, h->ctemp, status); else if (stokes_out == V) power_to_stokes_V(in, off, num_pix, h->ctemp, status); else continue; if (dp == AUTO_POWER || dp == CROSS_POWER_AMP) complex_to_amp(h->ctemp, 0, 1, num_pix, h->pix, status); else if (dp == CROSS_POWER_PHASE) complex_to_phase(h->ctemp, 0, 1, num_pix, h->pix, status); else continue; } else continue; /* Check for FITS file. */ if (f && h->width && h->height) { long firstpix[4]; firstpix[0] = 1 + (i_chunk * h->max_chunk_size) % h->width; firstpix[1] = 1 + (i_chunk * h->max_chunk_size) / h->width; firstpix[2] = 1 + i_channel; firstpix[3] = 1 + i_time; fits_write_pix(f, (h->prec == OSKAR_DOUBLE ? TDOUBLE : TFLOAT), firstpix, num_pix, oskar_mem_void(h->pix), status); } /* Check for text file. */ if (t) oskar_mem_save_ascii(t, 1, num_pix, status, h->pix); } } static void complex_to_amp(const oskar_Mem* complex_in, const int offset, const int stride, const int num_points, oskar_Mem* output, int* status) { int i, j; if (oskar_mem_precision(output) == OSKAR_SINGLE) { float *out, x, y; const float2* in; in = oskar_mem_float2_const(complex_in, status) + offset; out = oskar_mem_float(output, status); for (i = 0; i < num_points; ++i) { j = i * stride; x = in[j].x; y = in[j].y; out[i] = sqrt(x*x + y*y); } } else { double *out, x, y; const double2* in; in = oskar_mem_double2_const(complex_in, status) + offset; out = oskar_mem_double(output, status); for (i = 0; i < num_points; ++i) { j = i * stride; x = in[j].x; y = in[j].y; out[i] = sqrt(x*x + y*y); } } } static void complex_to_phase(const oskar_Mem* complex_in, const int offset, const int stride, const int num_points, oskar_Mem* output, int* status) { int i, j; if (oskar_mem_precision(output) == OSKAR_SINGLE) { float *out; const float2* in; in = oskar_mem_float2_const(complex_in, status) + offset; out = oskar_mem_float(output, status); for (i = 0; i < num_points; ++i) { j = i * stride; out[i] = atan2(in[j].y, in[j].x); } } else { double *out; const double2* in; in = oskar_mem_double2_const(complex_in, status) + offset; out = oskar_mem_double(output, status); for (i = 0; i < num_points; ++i) { j = i * stride; out[i] = atan2(in[j].y, in[j].x); } } } static void jones_to_ixr(const oskar_Mem* jones, const int offset, const int num_points, oskar_Mem* output, int* status) { int i; /* Check for fully polarised data. */ if (!oskar_mem_is_matrix(jones) || !oskar_mem_is_complex(jones)) return; if (oskar_mem_precision(output) == OSKAR_SINGLE) { float *out, cond, ixr; const float4c* in; in = oskar_mem_float4c_const(jones, status) + offset; out = oskar_mem_float(output, status); for (i = 0; i < num_points; ++i) { cond = oskar_cond2_2x2_inline_f(in + i); ixr = (cond + 1.0f) / (cond - 1.0f); ixr *= ixr; if (ixr > 1e6) ixr = 1e6; out[i] = ixr; } } else { double *out, cond, ixr; const double4c* in; in = oskar_mem_double4c_const(jones, status) + offset; out = oskar_mem_double(output, status); for (i = 0; i < num_points; ++i) { cond = oskar_cond2_2x2_inline_d(in + i); ixr = (cond + 1.0) / (cond - 1.0); ixr *= ixr; if (ixr > 1e8) ixr = 1e8; out[i] = ixr; } } } static void power_to_stokes_I(const oskar_Mem* power_in, const int offset, const int num_points, oskar_Mem* output, int* status) { /* Both arrays must be complex: this allows cross-power Stokes I. */ if (!oskar_mem_is_complex(power_in) || !oskar_mem_is_complex(output)) return; /* Generate 0.5 * (XX + YY) from input. */ if (!oskar_mem_is_matrix(power_in)) oskar_mem_copy_contents(output, power_in, 0, offset, num_points, status); else { int i; if (oskar_mem_is_double(power_in)) { double2* out; const double4c* in; out = oskar_mem_double2(output, status); in = oskar_mem_double4c_const(power_in, status) + offset; for (i = 0; i < num_points; ++i) { out[i].x = 0.5 * (in[i].a.x + in[i].d.x); out[i].y = 0.5 * (in[i].a.y + in[i].d.y); } } else { float2* out; const float4c* in; out = oskar_mem_float2(output, status); in = oskar_mem_float4c_const(power_in, status) + offset; for (i = 0; i < num_points; ++i) { out[i].x = 0.5 * (in[i].a.x + in[i].d.x); out[i].y = 0.5 * (in[i].a.y + in[i].d.y); } } } } static void power_to_stokes_Q(const oskar_Mem* power_in, const int offset, const int num_points, oskar_Mem* output, int* status) { int i; /* Both arrays must be complex: this allows cross-power Stokes Q. */ if (!oskar_mem_is_complex(power_in) || !oskar_mem_is_matrix(power_in) || !oskar_mem_is_complex(output)) return; /* Generate 0.5 * (XX - YY) from input. */ if (oskar_mem_is_double(power_in)) { double2* out; const double4c* in; out = oskar_mem_double2(output, status); in = oskar_mem_double4c_const(power_in, status) + offset; for (i = 0; i < num_points; ++i) { out[i].x = 0.5 * (in[i].a.x - in[i].d.x); out[i].y = 0.5 * (in[i].a.y - in[i].d.y); } } else { float2* out; const float4c* in; out = oskar_mem_float2(output, status); in = oskar_mem_float4c_const(power_in, status) + offset; for (i = 0; i < num_points; ++i) { out[i].x = 0.5 * (in[i].a.x - in[i].d.x); out[i].y = 0.5 * (in[i].a.y - in[i].d.y); } } } static void power_to_stokes_U(const oskar_Mem* power_in, const int offset, const int num_points, oskar_Mem* output, int* status) { int i; /* Both arrays must be complex: this allows cross-power Stokes U. */ if (!oskar_mem_is_complex(power_in) || !oskar_mem_is_matrix(power_in) || !oskar_mem_is_complex(output)) return; /* Generate 0.5 * (XY + YX) from input. */ if (oskar_mem_is_double(power_in)) { double2* out; const double4c* in; out = oskar_mem_double2(output, status); in = oskar_mem_double4c_const(power_in, status) + offset; for (i = 0; i < num_points; ++i) { out[i].x = 0.5 * (in[i].b.x + in[i].c.x); out[i].y = 0.5 * (in[i].b.y + in[i].c.y); } } else { float2* out; const float4c* in; out = oskar_mem_float2(output, status); in = oskar_mem_float4c_const(power_in, status) + offset; for (i = 0; i < num_points; ++i) { out[i].x = 0.5 * (in[i].b.x + in[i].c.x); out[i].y = 0.5 * (in[i].b.y + in[i].c.y); } } } static void power_to_stokes_V(const oskar_Mem* power_in, const int offset, const int num_points, oskar_Mem* output, int* status) { int i; /* Both arrays must be complex: this allows cross-power Stokes V. */ if (!oskar_mem_is_complex(power_in) || !oskar_mem_is_matrix(power_in) || !oskar_mem_is_complex(output)) return; /* Generate -0.5i * (XY - YX) from input. */ if (oskar_mem_is_double(power_in)) { double2* out; const double4c* in; out = oskar_mem_double2(output, status); in = oskar_mem_double4c_const(power_in, status) + offset; for (i = 0; i < num_points; ++i) { out[i].x = 0.5 * (in[i].b.y - in[i].c.y); out[i].y = -0.5 * (in[i].b.x - in[i].c.x); } } else { float2* out; const float4c* in; out = oskar_mem_float2(output, status); in = oskar_mem_float4c_const(power_in, status) + offset; for (i = 0; i < num_points; ++i) { out[i].x = 0.5 * (in[i].b.y - in[i].c.y); out[i].y = -0.5 * (in[i].b.x - in[i].c.x); } } } static void record_timing(oskar_BeamPattern* h) { int i; oskar_log_section(h->log, 'M', "Simulation timing"); oskar_log_value(h->log, 'M', 0, "Total wall time", "%.3f s", oskar_timer_elapsed(h->tmr_sim)); for (i = 0; i < h->num_devices; ++i) { oskar_log_value(h->log, 'M', 0, "Compute", "%.3f s [Device %i]", oskar_timer_elapsed(h->d[i].tmr_compute), i); } oskar_log_value(h->log, 'M', 0, "Write", "%.3f s", oskar_timer_elapsed(h->tmr_write)); } static unsigned int disp_width(unsigned int v) { return (v >= 100000u) ? 6 : (v >= 10000u) ? 5 : (v >= 1000u) ? 4 : (v >= 100u) ? 3 : (v >= 10u) ? 2u : 1u; /* return v == 1u ? 1u : (unsigned)log10(v)+1 */ } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/src/oskar_evaluate_vla_beam_pbcor.c
/* * Copyright (c) 2013-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include "telescope/station/oskar_evaluate_vla_beam_pbcor.h" #include "telescope/station/oskar_evaluate_vla_beam_pbcor_cuda.h" #include "telescope/station/oskar_vla_pbcor_inline.h" #include "utility/oskar_device_utils.h" #include "math/oskar_find_closest_match.h" #ifdef __cplusplus extern "C" { #endif static const double freqs_ghz[] = {0.0738, 0.3275, 1.465, 4.885, 8.435, 14.965, 22.485, 43.315}; static const double p1s[] = {-0.897, -0.935, -1.343, -1.372, -1.306, -1.305, -1.417, -1.321}; static const double p2s[] = {2.71, 3.23, 6.579, 6.940, 6.253, 6.155, 7.332, 6.185}; static const double p3s[] = {-0.242, -0.378, -1.186, -1.309, -1.100, -1.030, -1.352, -0.983}; void oskar_evaluate_vla_beam_pbcor_f(float* beam, int num_sources, const float* l, const float* m, const float freq_ghz, const float p1, const float p2, const float p3) { int i; for (i = 0; i < num_sources; ++i) { beam[i] = oskar_vla_pbcor_inline_f(l[i], m[i], freq_ghz, p1, p2, p3); } } void oskar_evaluate_vla_beam_pbcor_complex_f(float2* beam, int num_sources, const float* l, const float* m, const float freq_ghz, const float p1, const float p2, const float p3) { int i; for (i = 0; i < num_sources; ++i) { beam[i].x = oskar_vla_pbcor_inline_f(l[i], m[i], freq_ghz, p1, p2, p3); beam[i].y = 0.0f; } } void oskar_evaluate_vla_beam_pbcor_matrix_f(float4c* beam, int num_sources, const float* l, const float* m, const float freq_ghz, const float p1, const float p2, const float p3) { int i; for (i = 0; i < num_sources; ++i) { float t; t = oskar_vla_pbcor_inline_f(l[i], m[i], freq_ghz, p1, p2, p3); beam[i].a.x = t; beam[i].a.y = 0.0f; beam[i].b.x = 0.0f; beam[i].b.y = 0.0f; beam[i].c.x = 0.0f; beam[i].c.y = 0.0f; beam[i].d.x = t; beam[i].d.y = 0.0f; } } void oskar_evaluate_vla_beam_pbcor_d(double* beam, int num_sources, const double* l, const double* m, const double freq_ghz, const double p1, const double p2, const double p3) { int i; for (i = 0; i < num_sources; ++i) { beam[i] = oskar_vla_pbcor_inline_d(l[i], m[i], freq_ghz, p1, p2, p3); } } void oskar_evaluate_vla_beam_pbcor_complex_d(double2* beam, int num_sources, const double* l, const double* m, const double freq_ghz, const double p1, const double p2, const double p3) { int i; for (i = 0; i < num_sources; ++i) { beam[i].x = oskar_vla_pbcor_inline_d(l[i], m[i], freq_ghz, p1, p2, p3); beam[i].y = 0.0; } } void oskar_evaluate_vla_beam_pbcor_matrix_d(double4c* beam, int num_sources, const double* l, const double* m, const double freq_ghz, const double p1, const double p2, const double p3) { int i; for (i = 0; i < num_sources; ++i) { double t; t = oskar_vla_pbcor_inline_d(l[i], m[i], freq_ghz, p1, p2, p3); beam[i].a.x = t; beam[i].a.y = 0.0; beam[i].b.x = 0.0; beam[i].b.y = 0.0; beam[i].c.x = 0.0; beam[i].c.y = 0.0; beam[i].d.x = t; beam[i].d.y = 0.0; } } void oskar_evaluate_vla_beam_pbcor(oskar_Mem* beam, int num_sources, const oskar_Mem* l, const oskar_Mem* m, double frequency_hz, int* status) { int index, precision, type, location; double f, p1, p2, p3; /* Check if safe to proceed. */ if (*status) return; /* Check type and location. */ precision = oskar_mem_precision(beam); type = oskar_mem_type(beam); location = oskar_mem_location(beam); if (precision != oskar_mem_type(l) || precision != oskar_mem_type(m)) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } if (location != oskar_mem_location(l) || location != oskar_mem_location(m)) { *status = OSKAR_ERR_LOCATION_MISMATCH; return; } /* Find the nearest frequency at which data exists. */ index = oskar_find_closest_match_d(frequency_hz / 1.0e9, sizeof(freqs_ghz) / sizeof(double), freqs_ghz); f = frequency_hz / 1.0e9; p1 = p1s[index]; p2 = p2s[index]; p3 = p3s[index]; /* Switch on precision. */ if (precision == OSKAR_SINGLE) { const float *l_, *m_; l_ = oskar_mem_float_const(l, status); m_ = oskar_mem_float_const(m, status); if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA if (type == OSKAR_SINGLE) { oskar_evaluate_vla_beam_pbcor_cuda_f( oskar_mem_float(beam, status), num_sources, l_, m_, f, p1, p2, p3); } else if (type == OSKAR_SINGLE_COMPLEX) { oskar_evaluate_vla_beam_pbcor_complex_cuda_f( oskar_mem_float2(beam, status), num_sources, l_, m_, f, p1, p2, p3); } else if (type == OSKAR_SINGLE_COMPLEX_MATRIX) { oskar_evaluate_vla_beam_pbcor_matrix_cuda_f( oskar_mem_float4c(beam, status), num_sources, l_, m_, f, p1, p2, p3); } oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location == OSKAR_CPU) { if (type == OSKAR_SINGLE) { oskar_evaluate_vla_beam_pbcor_f( oskar_mem_float(beam, status), num_sources, l_, m_, f, p1, p2, p3); } else if (type == OSKAR_SINGLE_COMPLEX) { oskar_evaluate_vla_beam_pbcor_complex_f( oskar_mem_float2(beam, status), num_sources, l_, m_, f, p1, p2, p3); } else if (type == OSKAR_SINGLE_COMPLEX_MATRIX) { oskar_evaluate_vla_beam_pbcor_matrix_f( oskar_mem_float4c(beam, status), num_sources, l_, m_, f, p1, p2, p3); } } } else if (precision == OSKAR_DOUBLE) { const double *l_, *m_; l_ = oskar_mem_double_const(l, status); m_ = oskar_mem_double_const(m, status); if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA if (type == OSKAR_DOUBLE) { oskar_evaluate_vla_beam_pbcor_cuda_d( oskar_mem_double(beam, status), num_sources, l_, m_, f, p1, p2, p3); } else if (type == OSKAR_DOUBLE_COMPLEX) { oskar_evaluate_vla_beam_pbcor_complex_cuda_d( oskar_mem_double2(beam, status), num_sources, l_, m_, f, p1, p2, p3); } else if (type == OSKAR_DOUBLE_COMPLEX_MATRIX) { oskar_evaluate_vla_beam_pbcor_matrix_cuda_d( oskar_mem_double4c(beam, status), num_sources, l_, m_, f, p1, p2, p3); } oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location == OSKAR_CPU) { if (type == OSKAR_DOUBLE) { oskar_evaluate_vla_beam_pbcor_d( oskar_mem_double(beam, status), num_sources, l_, m_, f, p1, p2, p3); } else if (type == OSKAR_DOUBLE_COMPLEX) { oskar_evaluate_vla_beam_pbcor_complex_d( oskar_mem_double2(beam, status), num_sources, l_, m_, f, p1, p2, p3); } else if (type == OSKAR_DOUBLE_COMPLEX_MATRIX) { oskar_evaluate_vla_beam_pbcor_matrix_d( oskar_mem_double4c(beam, status), num_sources, l_, m_, f, p1, p2, p3); } } } else { *status = OSKAR_ERR_BAD_DATA_TYPE; } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/math/src/oskar_dftw_c2c_3d_omp.c
<reponame>davepallot/OSKAR /* * Copyright (c) 2013, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "math/oskar_dftw_c2c_3d_omp.h" #include <math.h> #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_dftw_c2c_3d_omp_f(const int n_in, const float wavenumber, const float* x_in, const float* y_in, const float* z_in, const float2* weights_in, const int n_out, const float* x_out, const float* y_out, const float* z_out, const float2* data, float2* output) { int i_out = 0; /* Loop over output points. */ #pragma omp parallel for private(i_out) for (i_out = 0; i_out < n_out; ++i_out) { int i; float xp_out, yp_out, zp_out; float2 out; /* Clear output value. */ out.x = 0.0f; out.y = 0.0f; /* Get the output position. */ xp_out = wavenumber * x_out[i_out]; yp_out = wavenumber * y_out[i_out]; zp_out = wavenumber * z_out[i_out]; /* Loop over input points. */ for (i = 0; i < n_in; ++i) { float2 temp, w; float a; /* Calculate the phase for the output position. */ a = xp_out * x_in[i] + yp_out * y_in[i] + zp_out * z_in[i]; temp.x = cosf(a); temp.y = sinf(a); /* Multiply the supplied DFT weight by the computed phase. */ w = weights_in[i]; a = w.x; w.x *= temp.x; w.x -= w.y * temp.y; w.y *= temp.x; w.y += a * temp.y; /* Perform complex multiply-accumulate. */ temp = data[i * n_out + i_out]; out.x += w.x * temp.x; out.x -= w.y * temp.y; out.y += w.y * temp.x; out.y += w.x * temp.y; } /* Store the output point. */ output[i_out] = out; } } /* Double precision. */ void oskar_dftw_c2c_3d_omp_d(const int n_in, const double wavenumber, const double* x_in, const double* y_in, const double* z_in, const double2* weights_in, const int n_out, const double* x_out, const double* y_out, const double* z_out, const double2* data, double2* output) { int i_out = 0; /* Loop over output points. */ #pragma omp parallel for private(i_out) for (i_out = 0; i_out < n_out; ++i_out) { int i; double xp_out, yp_out, zp_out; double2 out; /* Clear output value. */ out.x = 0.0; out.y = 0.0; /* Get the output position. */ xp_out = wavenumber * x_out[i_out]; yp_out = wavenumber * y_out[i_out]; zp_out = wavenumber * z_out[i_out]; /* Loop over input points. */ for (i = 0; i < n_in; ++i) { double2 temp, w; double a; /* Calculate the phase for the output position. */ a = xp_out * x_in[i] + yp_out * y_in[i] + zp_out * z_in[i]; temp.x = cos(a); temp.y = sin(a); /* Multiply the supplied DFT weight by the computed phase. */ w = weights_in[i]; a = w.x; w.x *= temp.x; w.x -= w.y * temp.y; w.y *= temp.x; w.y += a * temp.y; /* Perform complex multiply-accumulate. */ temp = data[i * n_out + i_out]; out.x += w.x * temp.x; out.x -= w.y * temp.y; out.y += w.y * temp.x; out.y += w.x * temp.y; } /* Store the output point. */ output[i_out] = out; } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/vis/src/oskar_vis_accessors.c
/* * Copyright (c) 2013-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "vis/private_vis.h" #include "vis/oskar_vis.h" #ifdef __cplusplus extern "C" { #endif int oskar_vis_location(const oskar_Vis* vis) { return oskar_mem_location(vis->amplitude); } oskar_Mem* oskar_vis_settings_path(oskar_Vis* vis) { return vis->settings_path; } const oskar_Mem* oskar_vis_settings_path_const(const oskar_Vis* vis) { return vis->settings_path; } oskar_Mem* oskar_vis_telescope_path(oskar_Vis* vis) { return vis->telescope_path; } const oskar_Mem* oskar_vis_telescope_path_const(const oskar_Vis* vis) { return vis->telescope_path; } oskar_Mem* oskar_vis_settings(oskar_Vis* vis) { return vis->settings; } const oskar_Mem* oskar_vis_settings_const(const oskar_Vis* vis) { return vis->settings; } int oskar_vis_num_channels(const oskar_Vis* vis) { return vis->num_channels; } int oskar_vis_num_times(const oskar_Vis* vis) { return vis->num_times; } int oskar_vis_num_stations(const oskar_Vis* vis) { return vis->num_stations; } int oskar_vis_num_baselines(const oskar_Vis* vis) { return vis->num_baselines; } int oskar_vis_num_pols(const oskar_Vis* vis) { return oskar_mem_is_matrix(vis->amplitude) ? 4 : 1; } double oskar_vis_freq_start_hz(const oskar_Vis* vis) { return vis->freq_start_hz; } double oskar_vis_freq_inc_hz(const oskar_Vis* vis) { return vis->freq_inc_hz; } double oskar_vis_channel_bandwidth_hz(const oskar_Vis* vis) { return vis->channel_bandwidth_hz; } double oskar_vis_time_start_mjd_utc(const oskar_Vis* vis) { return vis->time_start_mjd_utc; } double oskar_vis_time_inc_sec(const oskar_Vis* vis) { return vis->time_inc_sec; } double oskar_vis_time_average_sec(const oskar_Vis* vis) { return vis->time_average_sec; } double oskar_vis_phase_centre_ra_deg(const oskar_Vis* vis) { return vis->phase_centre_ra_deg; } double oskar_vis_phase_centre_dec_deg(const oskar_Vis* vis) { return vis->phase_centre_dec_deg; } double oskar_vis_telescope_lon_deg(const oskar_Vis* vis) { return vis->telescope_lon_deg; } double oskar_vis_telescope_lat_deg(const oskar_Vis* vis) { return vis->telescope_lat_deg; } double oskar_vis_telescope_alt_metres(const oskar_Vis* vis) { return vis->telescope_alt_metres; } oskar_Mem* oskar_vis_station_x_offset_ecef_metres(oskar_Vis* vis) { return vis->station_x_offset_ecef_metres; } const oskar_Mem* oskar_vis_station_x_offset_ecef_metres_const( const oskar_Vis* vis) { return vis->station_x_offset_ecef_metres; } oskar_Mem* oskar_vis_station_y_offset_ecef_metres(oskar_Vis* vis) { return vis->station_y_offset_ecef_metres; } const oskar_Mem* oskar_vis_station_y_offset_ecef_metres_const( const oskar_Vis* vis) { return vis->station_y_offset_ecef_metres; } oskar_Mem* oskar_vis_station_z_offset_ecef_metres(oskar_Vis* vis) { return vis->station_z_offset_ecef_metres; } const oskar_Mem* oskar_vis_station_z_offset_ecef_metres_const( const oskar_Vis* vis) { return vis->station_z_offset_ecef_metres; } oskar_Mem* oskar_vis_baseline_uu_metres(oskar_Vis* vis) { return vis->baseline_uu_metres; } const oskar_Mem* oskar_vis_baseline_uu_metres_const(const oskar_Vis* vis) { return vis->baseline_uu_metres; } oskar_Mem* oskar_vis_baseline_vv_metres(oskar_Vis* vis) { return vis->baseline_vv_metres; } const oskar_Mem* oskar_vis_baseline_vv_metres_const(const oskar_Vis* vis) { return vis->baseline_vv_metres; } oskar_Mem* oskar_vis_baseline_ww_metres(oskar_Vis* vis) { return vis->baseline_ww_metres; } const oskar_Mem* oskar_vis_baseline_ww_metres_const(const oskar_Vis* vis) { return vis->baseline_ww_metres; } oskar_Mem* oskar_vis_amplitude(oskar_Vis* vis) { return vis->amplitude; } const oskar_Mem* oskar_vis_amplitude_const(const oskar_Vis* vis) { return vis->amplitude; } void oskar_vis_set_freq_start_hz(oskar_Vis* vis, double value) { vis->freq_start_hz = value; } void oskar_vis_set_freq_inc_hz(oskar_Vis* vis, double value) { vis->freq_inc_hz = value; } void oskar_vis_set_channel_bandwidth_hz(oskar_Vis* vis, double value) { vis->channel_bandwidth_hz = value; } void oskar_vis_set_time_start_mjd_utc(oskar_Vis* vis, double value) { vis->time_start_mjd_utc = value; } void oskar_vis_set_time_inc_sec(oskar_Vis* vis, double value) { vis->time_inc_sec = value; } void oskar_vis_set_time_average_sec(oskar_Vis* vis, double value) { vis->time_average_sec = value; } void oskar_vis_set_phase_centre(oskar_Vis* vis, double ra_deg, double dec_deg) { vis->phase_centre_ra_deg = ra_deg; vis->phase_centre_dec_deg = dec_deg; } void oskar_vis_set_telescope_position(oskar_Vis* vis, double lon_deg, double lat_deg, double alt_metres) { vis->telescope_lon_deg = lon_deg; vis->telescope_lat_deg = lat_deg; vis->telescope_alt_metres = alt_metres; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/vis/oskar_vis.h
<filename>oskar/vis/oskar_vis.h /* * Copyright (c) 2012-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_VIS_H_ #define OSKAR_VIS_H_ /** * @file oskar_vis.h * * @deprecated * The oskar_Vis structure is deprecated. * Do not use these functions or enumerators in new code. */ #ifdef __cplusplus extern "C" { #endif struct oskar_Vis; #ifndef OSKAR_VIS_TYPEDEF_ #define OSKAR_VIS_TYPEDEF_ typedef struct oskar_Vis oskar_Vis; #endif /* OSKAR_VIS_TYPEDEF_ */ /* To maintain binary compatibility, do not change the values * in the lists below. */ enum OSKAR_VIS_TAGS { OSKAR_VIS_TAG_NUM_CHANNELS = 1, OSKAR_VIS_TAG_NUM_TIMES = 2, OSKAR_VIS_TAG_NUM_BASELINES = 3, OSKAR_VIS_TAG_DIMENSION_ORDER = 4, OSKAR_VIS_TAG_COORD_TYPE = 5, OSKAR_VIS_TAG_AMP_TYPE = 6, OSKAR_VIS_TAG_FREQ_START_HZ = 7, OSKAR_VIS_TAG_FREQ_INC_HZ = 8, OSKAR_VIS_TAG_TIME_START_MJD_UTC = 9, OSKAR_VIS_TAG_TIME_INC_SEC = 10, OSKAR_VIS_TAG_POL_TYPE = 11, OSKAR_VIS_TAG_BASELINE_COORD_UNIT = 12, OSKAR_VIS_TAG_BASELINE_UU = 13, OSKAR_VIS_TAG_BASELINE_VV = 14, OSKAR_VIS_TAG_BASELINE_WW = 15, OSKAR_VIS_TAG_AMPLITUDE = 16, OSKAR_VIS_TAG_PHASE_CENTRE_RA = 17, OSKAR_VIS_TAG_PHASE_CENTRE_DEC = 18, OSKAR_VIS_TAG_NUM_STATIONS = 19, OSKAR_VIS_TAG_STATION_COORD_UNIT = 20, OSKAR_VIS_TAG_STATION_X_OFFSET_ECEF = 21, OSKAR_VIS_TAG_STATION_Y_OFFSET_ECEF = 22, OSKAR_VIS_TAG_STATION_Z_OFFSET_ECEF = 23, OSKAR_VIS_TAG_CHANNEL_BANDWIDTH_HZ = 24, OSKAR_VIS_TAG_TIME_AVERAGE_SEC = 25, OSKAR_VIS_TAG_TELESCOPE_PATH = 26, OSKAR_VIS_TAG_STATION_LON = 27, OSKAR_VIS_TAG_STATION_LAT = 28, OSKAR_VIS_TAG_STATION_ORIENTATION_X = 29, OSKAR_VIS_TAG_STATION_ORIENTATION_Y = 30, OSKAR_VIS_TAG_TELESCOPE_LON = 31, OSKAR_VIS_TAG_TELESCOPE_LAT = 32, OSKAR_VIS_TAG_TELESCOPE_ALT = 33, OSKAR_VIS_TAG_STATION_X_ENU = 34, OSKAR_VIS_TAG_STATION_Y_ENU = 35, OSKAR_VIS_TAG_STATION_Z_ENU = 36 }; /* Do not change the values below - these are merely dimension labels, not the * actual dimension order. */ enum OSKAR_VIS_DIM { OSKAR_VIS_DIM_CHANNEL = 0, OSKAR_VIS_DIM_TIME = 1, OSKAR_VIS_DIM_BASELINE = 2, OSKAR_VIS_DIM_POLARISATION = 3 }; enum OSKAR_VIS_POL_TYPE { OSKAR_VIS_POL_TYPE_NONE = 0, OSKAR_VIS_POL_TYPE_LINEAR = 1 }; enum OSKAR_VIS_BASELINE_COORD_UNIT { OSKAR_VIS_BASELINE_COORD_UNIT_METRES = 1 }; enum OSKAR_VIS_STATION_COORD_UNIT { OSKAR_VIS_STATION_COORD_UNIT_METRES = 1 }; #ifdef __cplusplus } #endif #include <vis/oskar_vis_accessors.h> #include <vis/oskar_vis_create.h> #include <vis/oskar_vis_free.h> #include <vis/oskar_vis_read.h> #include <vis/oskar_vis_write.h> #endif /* OSKAR_VIS_H_ */
davepallot/OSKAR
oskar/imager/src/oskar_imager_reset_cache.c
/* * Copyright (c) 2016-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifdef OSKAR_HAVE_CUDA #include <cufft.h> #endif #include "imager/private_imager.h" #include "imager/oskar_imager_reset_cache.h" #include <fitsio.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif void oskar_imager_reset_cache(oskar_Imager* h, int* status) { int i; /* Clear selected axes. */ free(h->sel_freqs); free(h->im_freqs); h->sel_freqs = 0; h->im_freqs = 0; h->num_sel_freqs = 0; h->num_im_channels = 0; /* Clear FFT caches. */ oskar_mem_free(h->corr_func, status); oskar_mem_free(h->fftpack_wsave, status); oskar_mem_free(h->fftpack_work, status); #ifdef OSKAR_HAVE_CUDA cufftDestroy(h->cufft_plan); h->cufft_plan = 0; #endif h->corr_func = 0; h->fftpack_wsave = 0; h->fftpack_work = 0; /* Clear algorithm-specific caches. */ oskar_mem_free(h->l, status); h->l = 0; oskar_mem_free(h->m, status); h->m = 0; oskar_mem_free(h->n, status); h->n = 0; oskar_mem_free(h->conv_func, status); h->conv_func = 0; oskar_mem_free(h->w_kernels, status); h->w_kernels = 0; oskar_mem_free(h->w_support, status); h->w_support = 0; oskar_mem_free(h->w_kernels_compact, status); h->w_kernels_compact = 0; oskar_mem_free(h->w_kernel_start, status); h->w_kernel_start = 0; /* Free the image planes. */ if (h->planes) for (i = 0; i < h->num_planes; ++i) oskar_mem_free(h->planes[i], status); free(h->planes); h->planes = 0; free(h->plane_norm); h->plane_norm = 0; /* Free the weights grids if they exist. */ if (h->weights_grids) for (i = 0; i < h->num_planes; ++i) oskar_mem_free(h->weights_grids[i], status); free(h->weights_grids); h->weights_grids = 0; /* Collapse temp arrays. */ oskar_mem_realloc(h->uu_im, 0, status); oskar_mem_realloc(h->vv_im, 0, status); oskar_mem_realloc(h->ww_im, 0, status); oskar_mem_realloc(h->uu_tmp, 0, status); oskar_mem_realloc(h->vv_tmp, 0, status); oskar_mem_realloc(h->ww_tmp, 0, status); oskar_mem_realloc(h->vis_im, 0, status); oskar_mem_realloc(h->weight_im, 0, status); oskar_mem_realloc(h->weight_tmp, 0, status); oskar_mem_realloc(h->time_im, 0, status); oskar_mem_free(h->stokes, status); h->stokes = 0; /* Close any open FITS files. */ for (i = 0; i < h->num_im_pols; ++i) { if (h->fits_file[i]) ffclos(h->fits_file[i], status); h->fits_file[i] = 0; free(h->output_name[i]); h->output_name[i] = 0; } /* Clear the number of image planes. */ h->num_planes = 0; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/vis/private_vis_block.h
<filename>oskar/vis/private_vis_block.h /* * Copyright (c) 2015-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_PRIVATE_VIS_BLOCK_H_ #define OSKAR_PRIVATE_VIS_BLOCK_H_ #include <mem/oskar_mem.h> /* * This structure holds visibility data for all baselines, and a set of times * and channels. * * The dimension order is fixed. The polarisation dimension is implicit in the * data type (matrix or scalar) and is therefore the fastest varying. * From slowest to fastest varying, the remaining dimensions are: * * - Time (slowest) * - Channel * - Baseline (fastest) * * Note that it is different to that used by earlier versions of OSKAR, * where the order of the time and channel dimensions was swapped. * In addition, the Measurement Set format swaps the order of the channel * and baseline dimensions (so the dimension order there is * time, baseline, channel). * * The number of polarisations is determined by the choice of matrix or * scalar amplitude types. Matrix amplitude types represent 4 polarisation * dimensions, whereas scalar types represent Stokes-I only. */ struct oskar_VisBlock { /* Global start time index, start channel index, * and maximum dimension sizes: time, channel, baseline, station. */ int dim_start_size[6]; int has_cross_correlations; int has_auto_correlations; /* Cross-correlation amplitude array has size: * num_baselines * num_times * num_channels. * Autocorrelation amplitude array has size: * num_stations * num_times * num_channels. * Polarisation dimension is implicit, and therefore fastest varying. */ /* [complex / complex matrix] */ oskar_Mem* cross_correlations; /* Cross-correlation visibility amplitudes. */ oskar_Mem* auto_correlations; /* Autocorrelation visibility amplitudes. */ /* Coordinate arrays have sizes num_baselines * num_times. */ /* [real] */ oskar_Mem* baseline_uu_metres; /* Baseline coordinates, in metres. */ oskar_Mem* baseline_vv_metres; /* Baseline coordinates, in metres. */ oskar_Mem* baseline_ww_metres; /* Baseline coordinates, in metres. */ }; #ifndef OSKAR_VIS_BLOCK_TYPEDEF_ #define OSKAR_VIS_BLOCK_TYPEDEF_ typedef struct oskar_VisBlock oskar_VisBlock; #endif /* OSKAR_VIS_BLOCK_TYPEDEF_ */ #endif /* OSKAR_PRIVATE_VIS_BLOCK_H_ */
davepallot/OSKAR
oskar/sky/src/oskar_sky_load.c
/* * Copyright (c) 2011-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "sky/oskar_sky.h" #include "utility/oskar_getline.h" #include "utility/oskar_string_to_array.h" #include <stdio.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif static const double deg2rad = 1.74532925199432957692369e-2; static const double arcsec2rad = 4.84813681109535993589914e-6; oskar_Sky* oskar_sky_load(const char* filename, int type, int* status) { int n = 0; FILE* file; char* line = 0; size_t bufsize = 0; oskar_Sky* sky; /* Check if safe to proceed. */ if (*status) return 0; /* Get the data type. */ if (type != OSKAR_SINGLE && type != OSKAR_DOUBLE) { *status = OSKAR_ERR_BAD_DATA_TYPE; return 0; } /* Open the file. */ file = fopen(filename, "r"); if (!file) { *status = OSKAR_ERR_FILE_IO; return 0; } /* Initialise the sky model. */ sky = oskar_sky_create(type, OSKAR_CPU, 0, status); /* Loop over lines in file. */ while (oskar_getline(&line, &bufsize, file) != OSKAR_ERR_EOF) { /* Set defaults. */ /* RA, Dec, I, Q, U, V, freq0, spix, RM, FWHM maj, FWHM min, PA */ double par[] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.}; size_t num_param = sizeof(par) / sizeof(double); size_t num_required = 3, num_read = 0; /* Load source parameters (require at least RA, Dec, Stokes I). */ num_read = oskar_string_to_array_d(line, num_param, par); if (num_read < num_required) continue; /* Ensure enough space in arrays. */ if (oskar_sky_num_sources(sky) <= n) { oskar_sky_resize(sky, n + 100, status); if (*status) break; } if (num_read <= 9) { /* RA, Dec, I, Q, U, V, freq0, spix, RM */ oskar_sky_set_source(sky, n, par[0] * deg2rad, par[1] * deg2rad, par[2], par[3], par[4], par[5], par[6], par[7], par[8], 0.0, 0.0, 0.0, status); } else if (num_read == 11) { /* Old format, with no rotation measure. */ /* RA, Dec, I, Q, U, V, freq0, spix, FWHM maj, FWHM min, PA */ oskar_sky_set_source(sky, n, par[0] * deg2rad, par[1] * deg2rad, par[2], par[3], par[4], par[5], par[6], par[7], 0.0, par[8] * arcsec2rad, par[9] * arcsec2rad, par[10] * deg2rad, status); } else if (num_read == 12) { /* New format. */ /* RA, Dec, I, Q, U, V, freq0, spix, RM, FWHM maj, FWHM min, PA */ oskar_sky_set_source(sky, n, par[0] * deg2rad, par[1] * deg2rad, par[2], par[3], par[4], par[5], par[6], par[7], par[8], par[9] * arcsec2rad, par[10] * arcsec2rad, par[11] * deg2rad, status); } else { /* Error. */ *status = OSKAR_ERR_BAD_SKY_FILE; break; } ++n; } /* Set the size to be the actual number of elements loaded. */ oskar_sky_resize(sky, n, status); /* Free the line buffer and close the file. */ if (line) free(line); fclose(file); /* Check if an error occurred. */ if (*status) { oskar_sky_free(sky, status); sky = 0; } /* Return a handle to the sky model. */ return sky; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/math/oskar_kahan_sum.h
<gh_stars>1-10 /* * Copyright (c) 2013-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_KAHAN_SUM_H_ #define OSKAR_KAHAN_SUM_H_ /** * @file oskar_kahan_sum.h */ #include <oskar_global.h> #include <utility/oskar_vector_types.h> /** * @brief * Performs Kahan summation. * * @details * Performs Kahan summation to avoid loss of precision. * * @param[in] REAL Either 'float' or 'double'. * @param[in,out] SUM Updated sum. * @param[in] VAL Value to add to sum. * @param[in,out] GUARD Guard value (initially 0; preserve between calls). */ #define OSKAR_KAHAN_SUM(REAL, SUM, VAL, GUARD) { \ const REAL y__ = VAL - GUARD; \ const REAL t__ = SUM + y__; \ GUARD = (t__ - SUM) - y__; \ SUM = t__; } /** * @brief * Performs Kahan summation of a complex number. * * @details * Performs Kahan summation to avoid loss of precision. * * @param[in] REAL Either 'float' or 'double'. * @param[in,out] SUM Updated sum. * @param[in] VAL Value to add to sum. * @param[in,out] GUARD Guard value (initially 0; preserve between calls). */ #define OSKAR_KAHAN_SUM_COMPLEX(REAL, SUM, VAL, GUARD) { \ OSKAR_KAHAN_SUM(REAL, SUM.x, VAL.x, GUARD.x); \ OSKAR_KAHAN_SUM(REAL, SUM.y, VAL.y, GUARD.y); } /** * @brief * Performs Kahan multiply-add of a complex number. * * @details * Performs Kahan summation to avoid loss of precision. * * @param[in] REAL Either 'float' or 'double'. * @param[in,out] SUM Updated sum. * @param[in] VAL Value to add to sum. * @param[in] F Factor by which to multiply input value before summation. * @param[in,out] GUARD Guard value (initially 0; preserve between calls). */ #define OSKAR_KAHAN_SUM_MULTIPLY_COMPLEX(REAL, SUM, VAL, F, GUARD) { \ OSKAR_KAHAN_SUM(REAL, SUM.x, (VAL.x * F), GUARD.x); \ OSKAR_KAHAN_SUM(REAL, SUM.y, (VAL.y * F), GUARD.y); } /** * @brief * Performs Kahan summation of a complex matrix. * * @details * Performs Kahan summation to avoid loss of precision. * * @param[in] REAL Either 'float' or 'double'. * @param[in,out] SUM Updated sum. * @param[in] VAL Value to add to sum. * @param[in,out] GUARD Guard value (initially 0; preserve between calls). */ #define OSKAR_KAHAN_SUM_COMPLEX_MATRIX(REAL, SUM, VAL, GUARD) { \ OSKAR_KAHAN_SUM_COMPLEX(REAL, SUM.a, VAL.a, GUARD.a); \ OSKAR_KAHAN_SUM_COMPLEX(REAL, SUM.b, VAL.b, GUARD.b); \ OSKAR_KAHAN_SUM_COMPLEX(REAL, SUM.c, VAL.c, GUARD.c); \ OSKAR_KAHAN_SUM_COMPLEX(REAL, SUM.d, VAL.d, GUARD.d); } /** * @brief * Performs Kahan multiply-add of a complex matrix. * * @details * Performs Kahan summation to avoid loss of precision. * * @param[in] REAL Either 'float' or 'double'. * @param[in,out] SUM Updated sum. * @param[in] VAL Value to add to sum. * @param[in] F Factor by which to multiply input value before summation. * @param[in,out] GUARD Guard value (initially 0; preserve between calls). */ #define OSKAR_KAHAN_SUM_MULTIPLY_COMPLEX_MATRIX(REAL, SUM, VAL, F, GUARD) {\ OSKAR_KAHAN_SUM_MULTIPLY_COMPLEX(REAL, SUM.a, VAL.a, F, GUARD.a); \ OSKAR_KAHAN_SUM_MULTIPLY_COMPLEX(REAL, SUM.b, VAL.b, F, GUARD.b); \ OSKAR_KAHAN_SUM_MULTIPLY_COMPLEX(REAL, SUM.c, VAL.c, F, GUARD.c); \ OSKAR_KAHAN_SUM_MULTIPLY_COMPLEX(REAL, SUM.d, VAL.d, F, GUARD.d); } #endif /* OSKAR_KAHAN_SUM_H_ */
davepallot/OSKAR
oskar/convert/src/oskar_convert_lon_lat_to_relative_directions.c
<filename>oskar/convert/src/oskar_convert_lon_lat_to_relative_directions.c /* * Copyright (c) 2013-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "convert/oskar_convert_lon_lat_to_relative_directions.h" #include "convert/oskar_convert_lon_lat_to_relative_directions_cuda.h" #include "convert/private_convert_lon_lat_to_relative_directions_inline.h" #include "utility/oskar_device_utils.h" #include <math.h> #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_convert_lon_lat_to_relative_directions_f(int num_points, const float* lon_rad, const float* lat_rad, float lon0_rad, float lat0_rad, float* l, float* m, float* n) { int i; float sin_lat0, cos_lat0; sin_lat0 = (float) sin(lat0_rad); cos_lat0 = (float) cos(lat0_rad); #pragma omp parallel for private(i) for (i = 0; i < num_points; ++i) { oskar_convert_lon_lat_to_relative_directions_inline_f( lon_rad[i], lat_rad[i], lon0_rad, cos_lat0, sin_lat0, &l[i], &m[i], &n[i]); } } /* Double precision. */ void oskar_convert_lon_lat_to_relative_directions_d(int num_points, const double* lon_rad, const double* lat_rad, double lon0_rad, double lat0_rad, double* l, double* m, double* n) { int i; double sin_lat0, cos_lat0; sin_lat0 = sin(lat0_rad); cos_lat0 = cos(lat0_rad); #pragma omp parallel for private(i) for (i = 0; i < num_points; ++i) { oskar_convert_lon_lat_to_relative_directions_inline_d( lon_rad[i], lat_rad[i], lon0_rad, cos_lat0, sin_lat0, &l[i], &m[i], &n[i]); } } /* Single precision. */ void oskar_convert_lon_lat_to_relative_directions_2d_f(int num_points, const float* lon_rad, const float* lat_rad, float lon0_rad, float lat0_rad, float* l, float* m) { int i; float sin_lat0, cos_lat0; sin_lat0 = sinf(lat0_rad); cos_lat0 = cosf(lat0_rad); #pragma omp parallel for private(i) for (i = 0; i < num_points; ++i) { float cos_lat, sin_lat, sin_lon, cos_lon, rel_lon, p_lat, l_, m_; p_lat = lat_rad[i]; rel_lon = lon_rad[i]; rel_lon -= lon0_rad; sin_lon = sinf(rel_lon); cos_lon = cosf(rel_lon); sin_lat = sinf(p_lat); cos_lat = cosf(p_lat); l_ = cos_lat * sin_lon; m_ = cos_lat0 * sin_lat - sin_lat0 * cos_lat * cos_lon; l[i] = l_; m[i] = m_; } } /* Double precision. */ void oskar_convert_lon_lat_to_relative_directions_2d_d(int num_points, const double* lon_rad, const double* lat_rad, double lon0_rad, double lat0_rad, double* l, double* m) { int i; double sin_lat0, cos_lat0; sin_lat0 = sin(lat0_rad); cos_lat0 = cos(lat0_rad); #pragma omp parallel for private(i) for (i = 0; i < num_points; ++i) { double cos_lat, sin_lat, sin_lon, cos_lon, rel_lon, p_lat, l_, m_; p_lat = lat_rad[i]; rel_lon = lon_rad[i]; rel_lon -= lon0_rad; sin_lon = sin(rel_lon); cos_lon = cos(rel_lon); sin_lat = sin(p_lat); cos_lat = cos(p_lat); l_ = cos_lat * sin_lon; m_ = cos_lat0 * sin_lat - sin_lat0 * cos_lat * cos_lon; l[i] = l_; m[i] = m_; } } /* Wrapper. */ void oskar_convert_lon_lat_to_relative_directions(int num_points, const oskar_Mem* lon_rad, const oskar_Mem* lat_rad, double lon0_rad, double lat0_rad, oskar_Mem* l, oskar_Mem* m, oskar_Mem* n, int* status) { int type, location; /* Check if safe to proceed. */ if (*status) return; /* Get the meta-data. */ type = oskar_mem_type(lon_rad); location = oskar_mem_location(lon_rad); /* Check type consistency. */ if (oskar_mem_type(lat_rad) != type || oskar_mem_type(l) != type || oskar_mem_type(m) != type || oskar_mem_type(n) != type) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } if (type != OSKAR_SINGLE && type != OSKAR_DOUBLE) { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } /* Check location consistency. */ if (oskar_mem_location(lat_rad) != location || oskar_mem_location(l) != location || oskar_mem_location(m) != location || oskar_mem_location(n) != location) { *status = OSKAR_ERR_LOCATION_MISMATCH; return; } /* Check memory is allocated. */ if (!oskar_mem_allocated(lon_rad) || !oskar_mem_allocated(lat_rad)) { *status = OSKAR_ERR_MEMORY_NOT_ALLOCATED; return; } /* Check dimensions. */ if ((int)oskar_mem_length(lon_rad) < num_points || (int)oskar_mem_length(lat_rad) < num_points) { *status = OSKAR_ERR_DIMENSION_MISMATCH; return; } /* Resize output arrays if needed. */ if ((int)oskar_mem_length(l) < num_points) oskar_mem_realloc(l, num_points, status); if ((int)oskar_mem_length(m) < num_points) oskar_mem_realloc(m, num_points, status); if ((int)oskar_mem_length(n) < num_points) oskar_mem_realloc(n, num_points, status); /* Check if safe to proceed. */ if (*status) return; /* Convert coordinates. */ if (type == OSKAR_SINGLE) { const float *lon_, *lat_; float *l_, *m_, *n_; lon_ = oskar_mem_float_const(lon_rad, status); lat_ = oskar_mem_float_const(lat_rad, status); l_ = oskar_mem_float(l, status); m_ = oskar_mem_float(m, status); n_ = oskar_mem_float(n, status); if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA oskar_convert_lon_lat_to_relative_directions_cuda_f( num_points, lon_, lat_, (float)lon0_rad, (float)lat0_rad, l_, m_, n_); oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else { oskar_convert_lon_lat_to_relative_directions_f( num_points, lon_, lat_, (float)lon0_rad, (float)lat0_rad, l_, m_, n_); } } else { const double *lon_, *lat_; double *l_, *m_, *n_; lon_ = oskar_mem_double_const(lon_rad, status); lat_ = oskar_mem_double_const(lat_rad, status); l_ = oskar_mem_double(l, status); m_ = oskar_mem_double(m, status); n_ = oskar_mem_double(n, status); if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA oskar_convert_lon_lat_to_relative_directions_cuda_d( num_points, lon_, lat_, lon0_rad, lat0_rad, l_, m_, n_); oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else { oskar_convert_lon_lat_to_relative_directions_d( num_points, lon_, lat_, lon0_rad, lat0_rad, l_, m_, n_); } } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/convert/oskar_convert_apparent_ha_dec_to_enu_directions.h
/* * Copyright (c) 2013, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_CONVERT_APPARENT_HA_DEC_TO_ENU_DIRECTIONS_H_ #define OSKAR_CONVERT_APPARENT_HA_DEC_TO_ENU_DIRECTIONS_H_ /** * @file oskar_convert_apparent_ha_dec_to_enu_directions.h */ #include <oskar_global.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Equatorial to horizontal 3D direction cosines (single precision). * * @details * This function computes the x,y,z direction cosines of the specified points * in the horizontal coordinate system. * * Points where z is negative are below the local horizon. * * @param[in] n The number points to convert. * @param[in] ha The input source Hour Angles in radians. * @param[in] dec The input source Declinations in radians. * @param[in] lat The geodetic latitude of the origin of the horizon frame. * @param[out] x The x-direction-cosines in the horizontal system. * @param[out] y The y-direction-cosines in the horizontal system. * @param[out] z The z-direction-cosines in the horizontal system. */ OSKAR_EXPORT void oskar_convert_apparent_ha_dec_to_enu_directions_f(int n, const float* ha, const float* dec, float lat, float* x, float* y, float* z); /** * @brief * Equatorial to horizontal 3D direction cosines (double precision). * * @details * This function computes the x,y,z direction cosines of the specified points * in the horizontal coordinate system. * * Points where z is negative are below the local horizon. * * @param[in] n The number of points to convert. * @param[in] ha The input source Hour Angles in radians. * @param[in] dec The input source Declinations in radians. * @param[in] lat The geodetic latitude of the origin of the horizon frame. * @param[out] x The x-direction-cosines in the horizontal system. * @param[out] y The y-direction-cosines in the horizontal system. * @param[out] z The z-direction-cosines in the horizontal system. */ OSKAR_EXPORT void oskar_convert_apparent_ha_dec_to_enu_directions_d(int n, const double* ha, const double* dec, double lat, double* x, double* y, double* z); #ifdef __cplusplus } #endif #endif /* OSKAR_CONVERT_APPARENT_HA_DEC_TO_ENU_DIRECTIONS_H_ */
davepallot/OSKAR
oskar/correlate/src/oskar_auto_correlate_scalar_omp.c
<reponame>davepallot/OSKAR<gh_stars>1-10 /* * Copyright (c) 2015-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "correlate/oskar_auto_correlate_scalar_omp.h" #include "math/oskar_kahan_sum.h" #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_auto_correlate_scalar_omp_f(const int num_sources, const int num_stations, const float2* jones, const float* source_I, float2* vis) { int i, s; #pragma omp parallel for private(i, s) for (s = 0; s < num_stations; ++s) { float sum = 0.0f, guard = 0.0f; const float2 *const jones_station = &jones[s * num_sources]; for (i = 0; i < num_sources; ++i) { const float2 t = jones_station[i]; const float val = (t.x * t.x + t.y * t.y) * source_I[i]; OSKAR_KAHAN_SUM(float, sum, val, guard) } vis[s].x += sum; } } /* Double precision. */ void oskar_auto_correlate_scalar_omp_d(const int num_sources, const int num_stations, const double2* jones, const double* source_I, double2* vis) { int i, s; #pragma omp parallel for private(i, s) for (s = 0; s < num_stations; ++s) { double sum = 0.0; const double2 *const jones_station = &jones[s * num_sources]; for (i = 0; i < num_sources; ++i) { const double2 t = jones_station[i]; sum += (t.x * t.x + t.y * t.y) * source_I[i]; } vis[s].x += sum; } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/vis/oskar_vis_accessors.h
/* * Copyright (c) 2013-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_VIS_ACCESSORS_H_ #define OSKAR_VIS_ACCESSORS_H_ /** * @file oskar_vis_accessors.h */ #include <oskar_global.h> #include <mem/oskar_mem.h> #ifdef __cplusplus extern "C" { #endif OSKAR_EXPORT int oskar_vis_location(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_settings_path(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_settings_path_const(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_telescope_path(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_telescope_path_const(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_settings(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_settings_const(const oskar_Vis* vis); OSKAR_EXPORT int oskar_vis_num_channels(const oskar_Vis* vis); OSKAR_EXPORT int oskar_vis_num_times(const oskar_Vis* vis); OSKAR_EXPORT int oskar_vis_num_stations(const oskar_Vis* vis); OSKAR_EXPORT int oskar_vis_num_baselines(const oskar_Vis* vis); OSKAR_EXPORT int oskar_vis_num_pols(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_freq_start_hz(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_freq_inc_hz(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_channel_bandwidth_hz(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_time_start_mjd_utc(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_time_inc_sec(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_time_average_sec(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_phase_centre_ra_deg(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_phase_centre_dec_deg(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_telescope_lon_deg(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_telescope_lat_deg(const oskar_Vis* vis); OSKAR_EXPORT double oskar_vis_telescope_alt_metres(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_station_x_offset_ecef_metres(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_station_x_offset_ecef_metres_const(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_station_y_offset_ecef_metres(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_station_y_offset_ecef_metres_const(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_station_z_offset_ecef_metres(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_station_z_offset_ecef_metres_const(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_baseline_uu_metres(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_baseline_uu_metres_const(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_baseline_vv_metres(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_baseline_vv_metres_const(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_baseline_ww_metres(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_baseline_ww_metres_const(const oskar_Vis* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_amplitude(oskar_Vis* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_amplitude_const(const oskar_Vis* vis); /* Setters. */ OSKAR_EXPORT void oskar_vis_set_freq_start_hz(oskar_Vis* vis, double value); OSKAR_EXPORT void oskar_vis_set_freq_inc_hz(oskar_Vis* vis, double value); OSKAR_EXPORT void oskar_vis_set_channel_bandwidth_hz(oskar_Vis* vis, double value); OSKAR_EXPORT void oskar_vis_set_time_start_mjd_utc(oskar_Vis* vis, double value); OSKAR_EXPORT void oskar_vis_set_time_inc_sec(oskar_Vis* vis, double value); OSKAR_EXPORT void oskar_vis_set_time_average_sec(oskar_Vis* vis, double value); OSKAR_EXPORT void oskar_vis_set_phase_centre(oskar_Vis* vis, double ra_deg, double dec_deg); OSKAR_EXPORT void oskar_vis_set_telescope_position(oskar_Vis* vis, double lon_deg, double lat_deg, double alt_metres); #ifdef __cplusplus } #endif #endif /* OSKAR_VIS_ACCESSORS_H_ */
davepallot/OSKAR
oskar/telescope/station/element/src/oskar_element_load_cst.c
/* * Copyright (c) 2012-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/element/private_element.h" #include "telescope/station/element/oskar_element.h" #include "utility/oskar_getline.h" #include "math/oskar_cmath.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <float.h> #ifdef __cplusplus extern "C" { #endif #define DEG2RAD (M_PI/180.0) static void fit_splines(oskar_Log* log, oskar_Splines* splines, int n, oskar_Mem* theta, oskar_Mem* phi, oskar_Mem* data, oskar_Mem* weight, double closeness, double closeness_inc, const char* name, int* status); void oskar_element_load_cst(oskar_Element* data, oskar_Log* log, int port, double freq_hz, const char* filename, double closeness, double closeness_inc, int ignore_at_poles, int ignore_below_horizon, int* status) { int i, n = 0, type = OSKAR_DOUBLE; size_t fname_len; oskar_Splines *data_h_re = 0, *data_h_im = 0; oskar_Splines *data_v_re = 0, *data_v_im = 0; oskar_Mem *theta, *phi, *h_re, *h_im, *v_re, *v_im, *weight; /* Declare the line buffer. */ char *line = 0, *dbi = 0, *ludwig3 = 0; size_t bufsize = 0; FILE* file; /* Check if safe to proceed. */ if (*status) return; /* Check port number. */ if (port != 0 && port != 1 && port != 2) { *status = OSKAR_ERR_INVALID_ARGUMENT; return; } /* Check the data type. */ if (oskar_element_precision(data) != type) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } /* Check the location. */ if (oskar_element_mem_location(data) != OSKAR_CPU) { *status = OSKAR_ERR_BAD_LOCATION; return; } /* Check if this frequency has already been set, and get its index if so. */ n = data->num_freq; for (i = 0; i < n; ++i) { if (fabs(data->freqs_hz[i] - freq_hz) <= freq_hz * DBL_EPSILON) break; } /* Expand arrays to hold data for a new frequency, if needed. */ if (i >= data->num_freq) { i = data->num_freq; oskar_element_resize_freq_data(data, i + 1, status); data->freqs_hz[i] = freq_hz; } /* Get pointers to surface data based on port number and frequency index. */ if (port == 1 || port == 0) { data_h_re = oskar_element_x_h_re(data, i); data_h_im = oskar_element_x_h_im(data, i); data_v_re = oskar_element_x_v_re(data, i); data_v_im = oskar_element_x_v_im(data, i); } else if (port == 2) { data_h_re = oskar_element_y_h_re(data, i); data_h_im = oskar_element_y_h_im(data, i); data_v_re = oskar_element_y_v_re(data, i); data_v_im = oskar_element_y_v_im(data, i); } /* Open the file. */ fname_len = 1 + strlen(filename); file = fopen(filename, "r"); if (!file) { *status = OSKAR_ERR_FILE_IO; return; } /* Read the first line to check units and coordinate system. */ if (oskar_getline(&line, &bufsize, file) < 0) { *status = OSKAR_ERR_FILE_IO; free(line); fclose(file); return; } /* Check for presence of "dBi". */ dbi = strstr(line, "dBi"); /* Check for data in Ludwig-3 polarisation system. */ ludwig3 = strstr(line, "Horiz"); /* Create local arrays to hold data for fitting. */ theta = oskar_mem_create(type, OSKAR_CPU, 0, status); phi = oskar_mem_create(type, OSKAR_CPU, 0, status); h_re = oskar_mem_create(type, OSKAR_CPU, 0, status); h_im = oskar_mem_create(type, OSKAR_CPU, 0, status); v_re = oskar_mem_create(type, OSKAR_CPU, 0, status); v_im = oskar_mem_create(type, OSKAR_CPU, 0, status); weight = oskar_mem_create(type, OSKAR_CPU, 0, status); if (*status) return; /* Loop over and read each line in the file. */ n = 0; while (oskar_getline(&line, &bufsize, file) != OSKAR_ERR_EOF) { double t = 0., p = 0., abs_theta_horiz, phase_theta_horiz; double abs_phi_verti, phase_phi_verti; double theta_horiz_re, theta_horiz_im, phi_verti_re, phi_verti_im; double h_re_, h_im_, v_re_, v_im_; void *p_theta = 0, *p_phi = 0, *p_h_re = 0, *p_h_im = 0, *p_v_re = 0; void *p_v_im = 0, *p_weight = 0; /* Parse the line, and skip if data were not read correctly. */ if (sscanf(line, "%lf %lf %*f %lf %lf %lf %lf %*f", &t, &p, &abs_theta_horiz, &phase_theta_horiz, &abs_phi_verti, &phase_phi_verti) != 6) continue; /* Ignore data below horizon if requested. */ if (ignore_below_horizon && t > 90.0) continue; /* Ignore data at poles if requested. */ if (ignore_at_poles) if (t < 1e-6 || t > (180.0 - 1e-6)) continue; /* Convert angular measures to radians. */ t *= DEG2RAD; p *= DEG2RAD; phase_theta_horiz *= DEG2RAD; phase_phi_verti *= DEG2RAD; /* Ensure enough space in arrays. */ if (n % 100 == 0) { int size; size = n + 100; oskar_mem_realloc(theta, size, status); oskar_mem_realloc(phi, size, status); oskar_mem_realloc(h_re, size, status); oskar_mem_realloc(h_im, size, status); oskar_mem_realloc(v_re, size, status); oskar_mem_realloc(v_im, size, status); oskar_mem_realloc(weight, size, status); if (*status) break; } p_theta = oskar_mem_void(theta); p_phi = oskar_mem_void(phi); p_h_re = oskar_mem_void(h_re); p_h_im = oskar_mem_void(h_im); p_v_re = oskar_mem_void(v_re); p_v_im = oskar_mem_void(v_im); p_weight = oskar_mem_void(weight); /* Convert decibel to linear scale if necessary. */ if (dbi) { abs_theta_horiz = pow(10.0, abs_theta_horiz / 10.0); abs_phi_verti = pow(10.0, abs_phi_verti / 10.0); } /* Amp,phase to real,imag conversion. */ theta_horiz_re = abs_theta_horiz * cos(phase_theta_horiz); theta_horiz_im = abs_theta_horiz * sin(phase_theta_horiz); phi_verti_re = abs_phi_verti * cos(phase_phi_verti); phi_verti_im = abs_phi_verti * sin(phase_phi_verti); /* Convert to Ludwig-3 polarisation system if required. */ if (ludwig3) { /* Already in Ludwig-3: No conversion required. */ h_re_ = theta_horiz_re; h_im_ = theta_horiz_im; v_re_ = phi_verti_re; v_im_ = phi_verti_im; } else { /* Convert from theta/phi to Ludwig-3. */ double cos_p, sin_p; sin_p = sin(p); cos_p = cos(p); h_re_ = theta_horiz_re * cos_p - phi_verti_re * sin_p; h_im_ = theta_horiz_im * cos_p - phi_verti_im * sin_p; v_re_ = theta_horiz_re * sin_p + phi_verti_re * cos_p; v_im_ = theta_horiz_im * sin_p + phi_verti_im * cos_p; } /* Store the surface data in Ludwig-3 format. */ ((double*)p_theta)[n] = t; ((double*)p_phi)[n] = p; ((double*)p_h_re)[n] = h_re_; ((double*)p_h_im)[n] = h_im_; ((double*)p_v_re)[n] = v_re_; ((double*)p_v_im)[n] = v_im_; ((double*)p_weight)[n] = 1.0; /* Increment array pointer. */ n++; } /* Free the line buffer and close the file. */ free(line); fclose(file); /* Fit splines to the surface data. */ fit_splines(log, data_h_re, n, theta, phi, h_re, weight, closeness, closeness_inc, "H [real]", status); fit_splines(log, data_h_im, n, theta, phi, h_im, weight, closeness, closeness_inc, "H [imag]", status); fit_splines(log, data_v_re, n, theta, phi, v_re, weight, closeness, closeness_inc, "V [real]", status); fit_splines(log, data_v_im, n, theta, phi, v_im, weight, closeness, closeness_inc, "V [imag]", status); /* Store the filename. */ if (port == 0) { oskar_mem_append_raw(data->filename_x[i], filename, OSKAR_CHAR, OSKAR_CPU, fname_len, status); oskar_mem_append_raw(data->filename_y[i], filename, OSKAR_CHAR, OSKAR_CPU, fname_len, status); } else if (port == 1) { oskar_mem_append_raw(data->filename_x[i], filename, OSKAR_CHAR, OSKAR_CPU, fname_len, status); } else if (port == 2) { oskar_mem_append_raw(data->filename_y[i], filename, OSKAR_CHAR, OSKAR_CPU, fname_len, status); } /* Copy X to Y if both ports are the same. */ if (port == 0) { oskar_splines_copy(data->y_h_re[i], data->x_h_re[i], status); oskar_splines_copy(data->y_h_im[i], data->x_h_im[i], status); oskar_splines_copy(data->y_v_re[i], data->x_v_re[i], status); oskar_splines_copy(data->y_v_im[i], data->x_v_im[i], status); } /* Free local arrays. */ oskar_mem_free(theta, status); oskar_mem_free(phi, status); oskar_mem_free(h_re, status); oskar_mem_free(h_im, status); oskar_mem_free(v_re, status); oskar_mem_free(v_im, status); oskar_mem_free(weight, status); } static void fit_splines(oskar_Log* log, oskar_Splines* splines, int n, oskar_Mem* theta, oskar_Mem* phi, oskar_Mem* data, oskar_Mem* weight, double closeness, double closeness_inc, const char* name, int* status) { double avg_frac_error; if (*status) return; avg_frac_error = closeness; /* Copy the fitting parameter. */ oskar_log_line(log, 'M', ' '); oskar_log_message(log, 'M', 0, "Fitting surface %s...", name); oskar_splines_fit(splines, n, oskar_mem_double(theta, status), oskar_mem_double(phi, status), oskar_mem_double_const(data, status), oskar_mem_double_const(weight, status), OSKAR_SPLINES_SPHERICAL, 1, &avg_frac_error, closeness_inc, 1, 1e-14, status); oskar_log_message(log, 'M', 1, "Surface fitted to %.4f average " "frac. error (s=%.2e).", avg_frac_error, oskar_splines_smoothing_factor(splines)); oskar_log_message(log, 'M', 1, "Number of knots (theta, phi) = (%d, %d).", oskar_splines_num_knots_x_theta(splines), oskar_splines_num_knots_y_phi(splines)); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/src/oskar_evaluate_station_beam_aperture_array.c
<filename>oskar/telescope/station/src/oskar_evaluate_station_beam_aperture_array.c /* * Copyright (c) 2012-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/oskar_evaluate_station_beam_aperture_array.h" #include "telescope/station/oskar_evaluate_beam_horizon_direction.h" #include "telescope/station/oskar_evaluate_element_weights.h" #include "telescope/station/element/oskar_element_evaluate.h" #include "telescope/station/oskar_blank_below_horizon.h" #include "telescope/station/private_station_work.h" #include "math/oskar_cmath.h" #include "math/oskar_dftw.h" #ifdef __cplusplus extern "C" { #endif #define MAX_CHUNK_SIZE 49152 /* Private function, used for recursive calls. */ static void oskar_evaluate_station_beam_aperture_array_private(oskar_Mem* beam, const oskar_Station* s, int num_points, const oskar_Mem* x, const oskar_Mem* y, const oskar_Mem* z, double gast, double frequency_hz, oskar_StationWork* work, int time_index, int depth, int* status); void oskar_evaluate_station_beam_aperture_array(oskar_Mem* beam, const oskar_Station* station, int num_points, const oskar_Mem* x, const oskar_Mem* y, const oskar_Mem* z, double gast, double frequency_hz, oskar_StationWork* work, int time_index, int* status) { int start; /* Check if safe to proceed. */ if (*status) return; /* Evaluate beam immediately, without chunking, if there are no * child stations. */ if (!oskar_station_has_child(station)) { oskar_evaluate_station_beam_aperture_array_private(beam, station, num_points, x, y, z, gast, frequency_hz, work, time_index, 0, status); } else { oskar_Mem *c_beam, *c_x, *c_y, *c_z; c_beam = oskar_mem_create_alias(0, 0, 0, status); c_x = oskar_mem_create_alias(0, 0, 0, status); c_y = oskar_mem_create_alias(0, 0, 0, status); c_z = oskar_mem_create_alias(0, 0, 0, status); /* Split up list of input points into manageable chunks. */ for (start = 0; start < num_points; start += MAX_CHUNK_SIZE) { int chunk_size; /* Get size of current chunk. */ chunk_size = num_points - start; if (chunk_size > MAX_CHUNK_SIZE) chunk_size = MAX_CHUNK_SIZE; /* Get pointers to start of chunk input data. */ oskar_mem_set_alias(c_beam, beam, start, chunk_size, status); oskar_mem_set_alias(c_x, x, start, chunk_size, status); oskar_mem_set_alias(c_y, y, start, chunk_size, status); oskar_mem_set_alias(c_z, z, start, chunk_size, status); /* Start recursive call at depth 1 (depth 0 is element level). */ oskar_evaluate_station_beam_aperture_array_private(c_beam, station, chunk_size, c_x, c_y, c_z, gast, frequency_hz, work, time_index, 1, status); } /* Release handles for chunk memory. */ oskar_mem_free(c_beam, status); oskar_mem_free(c_x, status); oskar_mem_free(c_y, status); oskar_mem_free(c_z, status); } } static void oskar_evaluate_station_beam_aperture_array_private(oskar_Mem* beam, const oskar_Station* s, int num_points, const oskar_Mem* x, const oskar_Mem* y, const oskar_Mem* z, double gast, double frequency_hz, oskar_StationWork* work, int time_index, int depth, int* status) { double beam_x, beam_y, beam_z, wavenumber; oskar_Mem *weights, *weights_error, *theta, *phi, *array; int num_elements, is_3d; num_elements = oskar_station_num_elements(s); is_3d = oskar_station_array_is_3d(s); weights = work->weights; weights_error = work->weights_error; theta = work->theta_modified; phi = work->phi_modified; array = work->array_pattern; wavenumber = 2.0 * M_PI * frequency_hz / 299792458.0; /* Check if safe to proceed. */ if (*status) return; /* Compute direction cosines for the beam for this station. */ oskar_evaluate_beam_horizon_direction(&beam_x, &beam_y, &beam_z, s, gast, status); /* Evaluate beam if there are no child stations. */ if (!oskar_station_has_child(s)) { /* First optimisation: A single element model type, and either a common * orientation for all elements within the station, or isotropic * elements. */ /* Array pattern and element pattern are separable. */ if (oskar_station_num_element_types(s) == 1 && (oskar_station_common_element_orientation(s) || oskar_element_type(oskar_station_element_const(s, 0)) == OSKAR_ELEMENT_TYPE_ISOTROPIC) ) { /* (Always) evaluate element pattern into the output beam array. */ oskar_element_evaluate(oskar_station_element_const(s, 0), beam, oskar_station_element_x_alpha_rad(s, 0) + M_PI/2.0, /* FIXME Will change: This matches the old convention. */ oskar_station_element_y_alpha_rad(s, 0), num_points, x, y, z, frequency_hz, theta, phi, status); /* Check if array pattern is enabled. */ if (oskar_station_enable_array_pattern(s)) { /* Generate beamforming weights and evaluate array pattern. */ oskar_evaluate_element_weights(weights, weights_error, wavenumber, s, beam_x, beam_y, beam_z, time_index, status); oskar_dftw(num_elements, wavenumber, oskar_station_element_true_x_enu_metres_const(s), oskar_station_element_true_y_enu_metres_const(s), oskar_station_element_true_z_enu_metres_const(s), weights, num_points, x, y, (is_3d ? z : 0), 0, array, status); /* Normalise array response if required. */ if (oskar_station_normalise_array_pattern(s)) oskar_mem_scale_real(array, 1.0 / num_elements, status); /* Element-wise multiply to join array and element pattern. */ oskar_mem_multiply(beam, beam, array, num_points, status); } } #if 0 /* Second optimisation: Common orientation for all elements within the * station, but more than one element type. */ else if (oskar_station_common_element_orientation(s)) { /* Must evaluate array pattern, so check that this is enabled. */ if (!oskar_station_enable_array_pattern(s)) { *status = OSKAR_ERR_SETTINGS_TELESCOPE; return; } /* Call a DFT using indexed input. */ /* TODO Not yet implemented. */ *status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE; } #endif /* No optimisation: No common element orientation. */ /* Can't separate array and element evaluation. */ else { int i, num_element_types; oskar_Mem *element_block = 0, *element = 0; const int* element_type_array = 0; /* Must evaluate array pattern, so check that this is enabled. */ if (!oskar_station_enable_array_pattern(s)) { *status = OSKAR_ERR_SETTINGS_TELESCOPE; return; } /* Get sized element pattern block (at depth 0). */ element_block = oskar_station_work_beam(work, beam, num_elements * num_points, 0, status); /* Create alias into element block. */ element = oskar_mem_create_alias(element_block, 0, 0, status); /* Loop over elements and evaluate response for each. */ element_type_array = oskar_station_element_types_cpu_const(s); num_element_types = oskar_station_num_element_types(s); for (i = 0; i < num_elements; ++i) { int element_type_idx; element_type_idx = element_type_array[i]; if (element_type_idx >= num_element_types) { *status = OSKAR_ERR_OUT_OF_RANGE; break; } oskar_mem_set_alias(element, element_block, i * num_points, num_points, status); oskar_element_evaluate( oskar_station_element_const(s, element_type_idx), element, oskar_station_element_x_alpha_rad(s, i) + M_PI/2.0, /* FIXME Will change: This matches the old convention. */ oskar_station_element_y_alpha_rad(s, i), num_points, x, y, z, frequency_hz, theta, phi, status); } /* Generate beamforming weights. */ oskar_evaluate_element_weights(weights, weights_error, wavenumber, s, beam_x, beam_y, beam_z, time_index, status); /* Use DFT to evaluate array response. */ oskar_dftw(num_elements, wavenumber, oskar_station_element_true_x_enu_metres_const(s), oskar_station_element_true_y_enu_metres_const(s), oskar_station_element_true_z_enu_metres_const(s), weights, num_points, x, y, (is_3d ? z : 0), element_block, beam, status); /* Free element alias. */ oskar_mem_free(element, status); /* Normalise array response if required. */ if (oskar_station_normalise_array_pattern(s)) oskar_mem_scale_real(beam, 1.0 / num_elements, status); } /* Blank (set to zero) points below the horizon. */ oskar_blank_below_horizon(num_points, z, beam, status); } /* If there are child stations, must first evaluate the beam for each. */ else { int i; oskar_Mem* signal; /* Must evaluate array pattern, so check that this is enabled. */ if (!oskar_station_enable_array_pattern(s)) { *status = OSKAR_ERR_SETTINGS_TELESCOPE; return; } /* Get sized work array for this depth, with the correct type. */ signal = oskar_station_work_beam(work, beam, num_elements * num_points, depth, status); /* Check if child stations are identical. */ if (oskar_station_identical_children(s)) { /* Set up the output buffer for the first station. */ oskar_Mem* output0; output0 = oskar_mem_create_alias(signal, 0, num_points, status); /* Recursive call. */ oskar_evaluate_station_beam_aperture_array_private(output0, oskar_station_child_const(s, 0), num_points, x, y, z, gast, frequency_hz, work, time_index, depth + 1, status); /* Copy beam for child station 0 into memory for other stations. */ for (i = 1; i < num_elements; ++i) { oskar_mem_copy_contents(signal, output0, i * num_points, 0, oskar_mem_length(output0), status); } oskar_mem_free(output0, status); } else { /* Loop over child stations. */ for (i = 0; i < num_elements; ++i) { /* Set up the output buffer for this station. */ oskar_Mem* output; output = oskar_mem_create_alias(signal, i * num_points, num_points, status); /* Recursive call. */ oskar_evaluate_station_beam_aperture_array_private(output, oskar_station_child_const(s, i), num_points, x, y, z, gast, frequency_hz, work, time_index, depth + 1, status); oskar_mem_free(output, status); } } /* Generate beamforming weights and form beam from child stations. */ oskar_evaluate_element_weights(weights, weights_error, wavenumber, s, beam_x, beam_y, beam_z, time_index, status); oskar_dftw(num_elements, wavenumber, oskar_station_element_true_x_enu_metres_const(s), oskar_station_element_true_y_enu_metres_const(s), oskar_station_element_true_z_enu_metres_const(s), weights, num_points, x, y, (is_3d ? z : 0), signal, beam, status); /* Normalise array response if required. */ if (oskar_station_normalise_array_pattern(s)) oskar_mem_scale_real(beam, 1.0 / num_elements, status); } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/src/oskar_station_set_element_coords.c
/* * Copyright (c) 2011-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include "telescope/station/private_station.h" #include "telescope/station/oskar_station.h" #ifdef __cplusplus extern "C" { #endif void oskar_station_set_element_coords(oskar_Station* dst, int index, const double measured_enu[3], const double true_enu[3], int* status) { /* Check if safe to proceed. */ if (*status) return; /* Check range. */ if (index >= dst->num_elements) { *status = OSKAR_ERR_OUT_OF_RANGE; return; } /* Check if any z component is nonzero, and set 3D flag if so. */ if (measured_enu[2] != 0.0 || true_enu[2] != 0.0) dst->array_is_3d = OSKAR_TRUE; if (oskar_station_mem_location(dst) == OSKAR_CPU) { int type; void *xw, *yw, *zw, *xs, *ys, *zs; /* Get raw pointers. */ xw = oskar_mem_void(dst->element_measured_x_enu_metres); yw = oskar_mem_void(dst->element_measured_y_enu_metres); zw = oskar_mem_void(dst->element_measured_z_enu_metres); xs = oskar_mem_void(dst->element_true_x_enu_metres); ys = oskar_mem_void(dst->element_true_y_enu_metres); zs = oskar_mem_void(dst->element_true_z_enu_metres); type = oskar_station_precision(dst); if (type == OSKAR_DOUBLE) { ((double*)xw)[index] = measured_enu[0]; ((double*)yw)[index] = measured_enu[1]; ((double*)zw)[index] = measured_enu[2]; ((double*)xs)[index] = true_enu[0]; ((double*)ys)[index] = true_enu[1]; ((double*)zs)[index] = true_enu[2]; } else if (type == OSKAR_SINGLE) { ((float*)xw)[index] = (float)measured_enu[0]; ((float*)yw)[index] = (float)measured_enu[1]; ((float*)zw)[index] = (float)measured_enu[2]; ((float*)xs)[index] = (float)true_enu[0]; ((float*)ys)[index] = (float)true_enu[1]; ((float*)zs)[index] = (float)true_enu[2]; } else *status = OSKAR_ERR_BAD_DATA_TYPE; } else { oskar_mem_set_element_real(dst->element_measured_x_enu_metres, index, measured_enu[0], status); oskar_mem_set_element_real(dst->element_measured_y_enu_metres, index, measured_enu[1], status); oskar_mem_set_element_real(dst->element_measured_z_enu_metres, index, measured_enu[2], status); oskar_mem_set_element_real(dst->element_true_x_enu_metres, index, true_enu[0], status); oskar_mem_set_element_real(dst->element_true_y_enu_metres, index, true_enu[1], status); oskar_mem_set_element_real(dst->element_true_z_enu_metres, index, true_enu[2], status); } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/convert/oskar_convert_ecef_to_geodetic_spherical.h
<filename>oskar/convert/oskar_convert_ecef_to_geodetic_spherical.h /* * Copyright (c) 2013-2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_CONVERT_ECEF_TO_GEODETIC_SPHERICAL_H_ #define OSKAR_CONVERT_ECEF_TO_GEODETIC_SPHERICAL_H_ /** * @file oskar_convert_ecef_to_geodetic_spherical.h */ #include <oskar_global.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Convert coordinates from a geocentric cartesian (ECEF) to geodetic spherical * system (single precision). * * @details * This function converts positions from the geocentric cartesian * (Earth-Centred-Earth-Fixed, or ECEF) to the geodetic spherical (longitude, * latitude, altitude above ellipsoid) system. * * WARNING: This function uses reduced floating-point precision! * Use the double-precision version of this function in preference. * * The function uses WGS84 ellipsoid parameters: * Equatorial radius: 6378137 metres. * Polar radius: 6356752.314 metres. * * The input coordinates are with respect to the origin at the centre of the * Earth, and have the x-axis pointing towards the meridian of zero longitude, * the y-axis to +90 degrees East, and the z-axis to the North Celestial Pole. * * The algorithm is from <NAME> (2002): Journal of Geodesy, 76, 451. * DOI 10.1007/s00190-002-0273-6 * * @param[in] num_points Number of points. * @param[in] x Vector of ECEF x-positions, in metres. * @param[in] y Vector of ECEF y-positions, in metres. * @param[in] z Vector of ECEF z-positions, in metres. * @param[out] lon_rad Vector of longitudes, in radians. * @param[out] lat_rad Vector of latitudes, in radians. * @param[out] alt_m Vector of altitudes above ellipsoid, in metres. */ OSKAR_EXPORT void oskar_convert_ecef_to_geodetic_spherical_f(int num_points, const float* x, const float* y, const float* z, float* lon_rad, float* lat_rad, float* alt_m); /** * @brief * Convert coordinates from a geocentric cartesian (ECEF) to geodetic spherical * system (double precision). * * @details * This function converts positions from the geocentric cartesian * (Earth-Centred-Earth-Fixed, or ECEF) to the geodetic spherical (longitude, * latitude, altitude above ellipsoid) system. * * The function uses WGS84 ellipsoid parameters: * Equatorial radius: 6378137 metres. * Polar radius: 6356752.314 metres. * * The input coordinates are with respect to the origin at the centre of the * Earth, and have the x-axis pointing towards the meridian of zero longitude, * the y-axis to +90 degrees East, and the z-axis to the North Celestial Pole. * * The algorithm is from <NAME> (2002): Journal of Geodesy, 76, 451. * DOI 10.1007/s00190-002-0273-6 * * @param[in] num_points Number of points. * @param[in] x Vector of ECEF x-positions, in metres. * @param[in] y Vector of ECEF y-positions, in metres. * @param[in] z Vector of ECEF z-positions, in metres. * @param[out] lon_rad Vector of longitudes, in radians. * @param[out] lat_rad Vector of latitudes, in radians. * @param[out] alt_m Vector of altitudes above ellipsoid, in metres. */ OSKAR_EXPORT void oskar_convert_ecef_to_geodetic_spherical(int num_points, const double* x, const double* y, const double* z, double* lon_rad, double* lat_rad, double* alt_m); #ifdef __cplusplus } #endif #endif /* OSKAR_CONVERT_ECEF_TO_GEODETIC_SPHERICAL_H_ */
davepallot/OSKAR
oskar/telescope/station/src/oskar_evaluate_element_weights_errors.c
/* * Copyright (c) 2012-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/oskar_evaluate_element_weights_errors.h" #include "telescope/station/oskar_evaluate_element_weights_errors_cuda.h" #include "utility/oskar_cl_utils.h" #include "utility/oskar_device_utils.h" #include <math.h> #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_evaluate_element_weights_errors_f(int num_elements, const float* amp_gain, const float* amp_error, const float* phase_offset, const float* phase_error, float2* errors) { int i; for (i = 0; i < num_elements; ++i) { float2 r, t; /* Get two random numbers from a normalised Gaussian distribution. */ r = errors[i]; /* Evaluate the real and imaginary components of the error weight * for the antenna. */ r.x *= amp_error[i]; r.x += amp_gain[i]; /* Amplitude. */ r.y *= phase_error[i]; r.y += phase_offset[i]; /* Phase. */ t.x = cosf(r.y); t.y = sinf(r.y); t.x *= r.x; /* Real. */ t.y *= r.x; /* Imaginary. */ errors[i] = t; /* Store. */ } } /* Double precision. */ void oskar_evaluate_element_weights_errors_d(int num_elements, const double* amp_gain, const double* amp_error, const double* phase_offset, const double* phase_error, double2* errors) { int i; for (i = 0; i < num_elements; ++i) { double2 r, t; /* Get two random numbers from a normalised Gaussian distribution. */ r = errors[i]; /* Evaluate the real and imaginary components of the error weight * for the antenna. */ r.x *= amp_error[i]; r.x += amp_gain[i]; /* Amplitude. */ r.y *= phase_error[i]; r.y += phase_offset[i]; /* Phase. */ t.x = cos(r.y); t.y = sin(r.y); t.x *= r.x; /* Real. */ t.y *= r.x; /* Imaginary. */ errors[i] = t; /* Store. */ } } /* Wrapper. */ void oskar_evaluate_element_weights_errors(int num_elements, const oskar_Mem* gain, const oskar_Mem* gain_error, const oskar_Mem* phase, const oskar_Mem* phase_error, unsigned int random_seed, int time_index, int station_id, oskar_Mem* errors, int* status) { int type, location; /* Check if safe to proceed. */ if (*status) return; /* Check array dimensions are OK. */ if ((int)oskar_mem_length(errors) < num_elements || (int)oskar_mem_length(gain) < num_elements || (int)oskar_mem_length(gain_error) < num_elements || (int)oskar_mem_length(phase) < num_elements || (int)oskar_mem_length(phase_error) < num_elements) { *status = OSKAR_ERR_DIMENSION_MISMATCH; return; } /* Check for location mismatch. */ location = oskar_mem_location(errors); if (oskar_mem_location(gain) != location || oskar_mem_location(gain_error) != location || oskar_mem_location(phase) != location || oskar_mem_location(phase_error) != location) { *status = OSKAR_ERR_LOCATION_MISMATCH; return; } /* Check types. */ type = oskar_mem_precision(errors); if (!oskar_mem_is_complex(errors) || oskar_mem_is_matrix(errors)) { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } if (oskar_mem_type(gain) != type || oskar_mem_type(phase) != type || oskar_mem_type(gain_error) != type || oskar_mem_type(phase_error) != type) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } /* Generate Gaussian-distributed random numbers in output array. */ oskar_mem_random_gaussian(errors, random_seed, time_index, station_id, 0x12345678, 1.0, status); /* Generate weights errors. */ if (location == OSKAR_CPU) { if (type == OSKAR_DOUBLE) oskar_evaluate_element_weights_errors_d(num_elements, oskar_mem_double_const(gain, status), oskar_mem_double_const(gain_error, status), oskar_mem_double_const(phase, status), oskar_mem_double_const(phase_error, status), oskar_mem_double2(errors, status)); else if (type == OSKAR_SINGLE) oskar_evaluate_element_weights_errors_f(num_elements, oskar_mem_float_const(gain, status), oskar_mem_float_const(gain_error, status), oskar_mem_float_const(phase, status), oskar_mem_float_const(phase_error, status), oskar_mem_float2(errors, status)); else *status = OSKAR_ERR_BAD_DATA_TYPE; } else if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA if (type == OSKAR_DOUBLE) oskar_evaluate_element_weights_errors_cuda_d(num_elements, oskar_mem_double_const(gain, status), oskar_mem_double_const(gain_error, status), oskar_mem_double_const(phase, status), oskar_mem_double_const(phase_error, status), oskar_mem_double2(errors, status)); else if (type == OSKAR_SINGLE) oskar_evaluate_element_weights_errors_cuda_f(num_elements, oskar_mem_float_const(gain, status), oskar_mem_float_const(gain_error, status), oskar_mem_float_const(phase, status), oskar_mem_float_const(phase_error, status), oskar_mem_float2(errors, status)); else *status = OSKAR_ERR_BAD_DATA_TYPE; oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location & OSKAR_CL) { #ifdef OSKAR_HAVE_OPENCL cl_device_type dev_type; cl_event event; cl_kernel k = 0; cl_int is_gpu, error, num; cl_uint arg = 0; size_t global_size, local_size; clGetDeviceInfo(oskar_cl_device_id(), CL_DEVICE_TYPE, sizeof(cl_device_type), &dev_type, NULL); is_gpu = dev_type & CL_DEVICE_TYPE_GPU; if (type == OSKAR_DOUBLE) k = oskar_cl_kernel("evaluate_element_weights_errors_double"); else if (type == OSKAR_SINGLE) k = oskar_cl_kernel("evaluate_element_weights_errors_float"); else { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } if (!k) { *status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE; return; } /* Set kernel arguments. */ num = (cl_int) num_elements; error = clSetKernelArg(k, arg++, sizeof(cl_int), &num); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer_const(gain, status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer_const(gain_error, status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer_const(phase, status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer_const(phase_error, status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer(errors, status)); if (error != CL_SUCCESS) { *status = OSKAR_ERR_INVALID_ARGUMENT; return; } /* Launch kernel on current command queue. */ local_size = is_gpu ? 256 : 128; global_size = ((num + local_size - 1) / local_size) * local_size; error = clEnqueueNDRangeKernel(oskar_cl_command_queue(), k, 1, NULL, &global_size, &local_size, 0, NULL, &event); if (error != CL_SUCCESS) *status = OSKAR_ERR_KERNEL_LAUNCH_FAILURE; #else *status = OSKAR_ERR_OPENCL_NOT_AVAILABLE; #endif } else *status = OSKAR_ERR_BAD_LOCATION; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/settings/types/oskar_DateTime.h
/* * Copyright (c) 2015-2017, The University of Oxford * All rights reserved. * * This file is part of the OSKAR package. * Contact: oskar at oerc.ox.ac.uk * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_SETTINGS_TYPE_DATETIME_H_ #define OSKAR_SETTINGS_TYPE_DATETIME_H_ /** * @file oskar_DateTime.h */ #include "settings/types/oskar_AbstractSettingsType.h" namespace oskar { /** * @class DateTime * * @brief * * @details * TODO check leading zero behaviour in OSKAR ... * oskar_settings_load_observation.cpp * * TODO also ready MJD * * d-M-yyyy h:m:s[.z] - British style * yyyy/M/d/h:m:s[.z] - CASA style * yyyy-M-d h:m:s[.z] - International style * yyyy-M-dTh:m:s[.z] - ISO date style */ class DateTime : public AbstractSettingsType { public: enum Format { UNDEF = -1, BRITISH, CASA, INTERNATIONAL, ISO, MJD }; struct OSKAR_SETTINGS_EXPORT Value { DateTime::Format style; int year, month, day, hours, minutes; double seconds; Value() : style(DateTime::UNDEF), year(0), month(0), day(0), hours(0), minutes(0), seconds(0.0) {} void clear() { style = DateTime::UNDEF; year = 0; month = 0; day = 0; hours = 0; minutes = 0; seconds = 0.0; } }; public: OSKAR_SETTINGS_EXPORT DateTime(); OSKAR_SETTINGS_EXPORT virtual ~DateTime(); OSKAR_SETTINGS_EXPORT bool init(const char* s); OSKAR_SETTINGS_EXPORT bool set_default(const char* value); OSKAR_SETTINGS_EXPORT bool set_value(const char* value); OSKAR_SETTINGS_EXPORT bool is_default() const; OSKAR_SETTINGS_EXPORT Value value() const; OSKAR_SETTINGS_EXPORT Value default_value() const; OSKAR_SETTINGS_EXPORT double to_mjd() const; OSKAR_SETTINGS_EXPORT double to_mjd_2() const; OSKAR_SETTINGS_EXPORT void from_mjd(double mjd); OSKAR_SETTINGS_EXPORT DateTime::Format format() const; OSKAR_SETTINGS_EXPORT void set_format(DateTime::Format format); OSKAR_SETTINGS_EXPORT bool operator==(const DateTime& other) const; OSKAR_SETTINGS_EXPORT bool operator>(const DateTime& other) const; private: Value default_, value_; }; } /* namespace oskar */ #endif /* OSKAR_SETTINGS_TYPE_DATETIME_H_ */
davepallot/OSKAR
oskar/mem/src/oskar_mem_create.c
<reponame>davepallot/OSKAR /* * Copyright (c) 2013-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifdef OSKAR_HAVE_CUDA #include <cuda_runtime_api.h> #endif #include "mem/oskar_mem.h" #include "mem/private_mem.h" #include "utility/oskar_cl_utils.h" #include "utility/oskar_device_utils.h" #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif oskar_Mem* oskar_mem_create(int type, int location, size_t num_elements, int* status) { oskar_Mem* mem = 0; size_t element_size, bytes; /* Create the structure. */ mem = (oskar_Mem*) calloc(1, sizeof(oskar_Mem)); if (!mem) { *status = OSKAR_ERR_MEMORY_ALLOC_FAILURE; return 0; } /* Initialise meta-data. * (This must happen regardless of the status code.) */ mem->type = type; mem->location = location; mem->num_elements = 0; mem->owner = 1; mem->data = NULL; /* Check if allocation should happen or not. */ if (!status || *status || num_elements == 0) return mem; /* Get the memory size. */ element_size = oskar_mem_element_size(type); if (element_size == 0) { *status = OSKAR_ERR_BAD_DATA_TYPE; return mem; } bytes = num_elements * element_size; /* Check whether the memory should be on the host or the device. */ mem->num_elements = num_elements; if (location == OSKAR_CPU) { /* Allocate host memory. */ mem->data = calloc(bytes, 1); if (mem->data == NULL) *status = OSKAR_ERR_MEMORY_ALLOC_FAILURE; } else if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA /* Allocate GPU memory. For efficiency, don't clear it. */ cudaMalloc(&mem->data, bytes); if (mem->data == NULL) *status = OSKAR_ERR_MEMORY_ALLOC_FAILURE; oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location & OSKAR_CL) { #ifdef OSKAR_HAVE_OPENCL /* Allocate OpenCL memory buffer using the current context. */ cl_int error = 0; mem->buffer = clCreateBuffer(oskar_cl_context(), CL_MEM_READ_WRITE, bytes, NULL, &error); if (error != CL_SUCCESS) *status = OSKAR_ERR_MEMORY_ALLOC_FAILURE; #else *status = OSKAR_ERR_OPENCL_NOT_AVAILABLE; #endif } else { *status = OSKAR_ERR_BAD_LOCATION; } /* Return a handle to the structure .*/ return mem; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/element/oskar_evaluate_dipole_pattern_cuda.h
<gh_stars>1-10 /* * Copyright (c) 2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_EVALUATE_DIPOLE_PATTERN_CUDA_H_ #define OSKAR_EVALUATE_DIPOLE_PATTERN_CUDA_H_ /** * @file oskar_evaluate_dipole_pattern_cuda.h */ #include <oskar_global.h> #include <utility/oskar_vector_types.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Evaluates pattern of a perfect dipole at source positions using CUDA * (single precision). * * @details * This function evaluates the pattern of a perfect dipole antenna * at the supplied source positions using CUDA. * * The magnitude of the dipole response is given by * * \f[ * E_{\theta^{'}} = * \frac{\cos(\frac{kL}{2}\cos\phi\sin\theta) - \cos(\frac{kL}{2})} * {\sqrt{1 - \cos^2\phi \sin^2\theta}}; * \f] * * where phi and theta are the angles measured from x to y and from z to xy, * respectively. * * The supplied theta and phi positions of the sources are the <b>modified</b> * source positions. They must be adjusted relative to a dipole with its axis * oriented along the x-direction. * * Note that all pointers refer to device memory. * * @param[in] num_points Number of points. * @param[in] d_theta Point position (modified) theta values in rad. * @param[in] d_phi Point position (modified) phi values in rad. * @param[in] freq_hz Observing frequency in Hz. * @param[in] dipole_length_m Length of dipole in metres. * @param[in] stride Stride into output arrays. * @param[out] d_E_theta Response per point in E_theta. * @param[out] d_E_phi Response per point in E_phi. */ OSKAR_EXPORT void oskar_evaluate_dipole_pattern_cuda_f(int num_points, const float* d_theta, const float* d_phi, float freq_hz, float dipole_length_m, int stride, float2* d_E_theta, float2* d_E_phi); /** * @brief * Evaluates pattern of a perfect dipole at source positions using CUDA * (scalar version, single precision). * * @details * This function evaluates the scalar pattern of a perfect dipole antenna * at the supplied source positions using CUDA. * * The supplied theta and phi positions of the sources are the <b>modified</b> * source positions. They must be adjusted relative to a dipole with its axis * oriented along the x-direction. * * Note that all pointers refer to device memory. * * @param[in] num_points Number of points. * @param[in] d_theta Point position (modified) theta values in rad. * @param[in] d_phi Point position (modified) phi values in rad. * @param[in] freq_hz Observing frequency in Hz. * @param[in] dipole_length_m Length of dipole in metres. * @param[in] stride Stride into output array (normally 1). * @param[out] d_pattern Response per point. */ OSKAR_EXPORT void oskar_evaluate_dipole_pattern_scalar_cuda_f(int num_points, const float* d_theta, const float* d_phi, float freq_hz, float dipole_length_m, int stride, float2* d_pattern); /** * @brief * Evaluates pattern of a perfect dipole at source positions using CUDA * (double precision). * * @details * This function evaluates the pattern of a perfect dipole antenna * at the supplied source positions using CUDA. * * The magnitude of the dipole response is given by * * \f[ * E_{\theta^{'}} = * \frac{\cos(\frac{kL}{2}\cos\phi\sin\theta) - \cos(\frac{kL}{2})} * {\sqrt{1 - \cos^2\phi \sin^2\theta}}; * \f] * * where phi and theta are the angles measured from x to y and from z to xy, * respectively. * * The supplied theta and phi positions of the sources are the <b>modified</b> * source positions. They must be adjusted relative to a dipole with its axis * oriented along the x-direction. * * Note that all pointers refer to device memory. * * @param[in] num_points Number of points. * @param[in] d_theta Point position (modified) theta values in rad. * @param[in] d_phi Point position (modified) phi values in rad. * @param[in] freq_hz Observing frequency in Hz. * @param[in] dipole_length_m Length of dipole in metres. * @param[in] stride Stride into output arrays. * @param[out] d_E_theta Response per point in E_theta. * @param[out] d_E_phi Response per point in E_phi. */ OSKAR_EXPORT void oskar_evaluate_dipole_pattern_cuda_d(int num_points, const double* d_theta, const double* d_phi, double freq_hz, double dipole_length_m, int stride, double2* d_E_theta, double2* d_E_phi); /** * @brief * Evaluates pattern of a perfect dipole at source positions using CUDA * (scalar version, double precision). * * @details * This function evaluates the scalar pattern of a perfect dipole antenna * at the supplied source positions using CUDA. * * The supplied theta and phi positions of the sources are the <b>modified</b> * source positions. They must be adjusted relative to a dipole with its axis * oriented along the x-direction. * * Note that all pointers refer to device memory. * * @param[in] num_points Number of points. * @param[in] d_theta Point position (modified) theta values in rad. * @param[in] d_phi Point position (modified) phi values in rad. * @param[in] freq_hz Observing frequency in Hz. * @param[in] dipole_length_m Length of dipole in metres. * @param[in] stride Stride into output array (normally 1). * @param[out] d_pattern Response per point. */ OSKAR_EXPORT void oskar_evaluate_dipole_pattern_scalar_cuda_d(int num_points, const double* d_theta, const double* d_phi, double freq_hz, double dipole_length_m, int stride, double2* d_pattern); #ifdef __CUDACC__ /* Kernels. */ __global__ void oskar_evaluate_dipole_pattern_cudak_f(const int num_points, const float* restrict theta, const float* restrict phi, const float kL, const float cos_kL, const int stride, float2* E_theta, float2* E_phi); __global__ void oskar_evaluate_dipole_pattern_scalar_cudak_f(const int num_points, const float* restrict theta, const float* restrict phi, const float kL, const float cos_kL, const int stride, float2* restrict pattern); __global__ void oskar_evaluate_dipole_pattern_cudak_d(const int num_points, const double* restrict theta, const double* restrict phi, const double kL, const double cos_kL, const int stride, double2* E_theta, double2* E_phi); __global__ void oskar_evaluate_dipole_pattern_scalar_cudak_d(const int num_points, const double* restrict theta, const double* restrict phi, const double kL, const double cos_kL, const int stride, double2* restrict pattern); #endif /* __CUDACC__ */ #ifdef __cplusplus } #endif #endif /* OSKAR_EVALUATE_DIPOLE_PATTERN_CUDA_H_ */
davepallot/OSKAR
oskar/mem/oskar_mem_multiply.h
<reponame>davepallot/OSKAR /* * Copyright (c) 2012-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_MEM_MULTIPLY_H_ #define OSKAR_MEM_MULTIPLY_H_ /** * @file oskar_mem_multiply.h */ #include <oskar_global.h> #include <utility/oskar_vector_types.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Multiplies (element-wise) the contents of two arrays. * * @details * This function multiplies each element of one array by each element in * another array. * * The arrays can be in either CPU or GPU memory, but will be copied to the * output memory location if necessary before performing the multiplication. * * If c is NULL on input then the operation becomes a = a .* b. * * @param[out] c Output array. * @param[in,out] a Input and/or output array. * @param[in] b Second input array. * @param[in] num If >0, use only this number of elements from A and B. * @param[in,out] status Status return code. */ OSKAR_EXPORT void oskar_mem_multiply(oskar_Mem* c, oskar_Mem* a, const oskar_Mem* b, size_t num, int* status); OSKAR_EXPORT void oskar_mem_multiply_rr_r_f(size_t num, float* c, const float* a, const float* b); OSKAR_EXPORT void oskar_mem_multiply_cc_c_f(size_t num, float2* c, const float2* a, const float2* b); OSKAR_EXPORT void oskar_mem_multiply_cc_m_f(size_t num, float4c* c, const float2* a, const float2* b); OSKAR_EXPORT void oskar_mem_multiply_cm_m_f(size_t num, float4c* c, const float2* a, const float4c* b); OSKAR_EXPORT void oskar_mem_multiply_mm_m_f(size_t num, float4c* c, const float4c* a, const float4c* b); OSKAR_EXPORT void oskar_mem_multiply_rr_r_d(size_t num, double* c, const double* a, const double* b); OSKAR_EXPORT void oskar_mem_multiply_cc_c_d(size_t num, double2* c, const double2* a, const double2* b); OSKAR_EXPORT void oskar_mem_multiply_cc_m_d(size_t num, double4c* c, const double2* a, const double2* b); OSKAR_EXPORT void oskar_mem_multiply_cm_m_d(size_t num, double4c* c, const double2* a, const double4c* b); OSKAR_EXPORT void oskar_mem_multiply_mm_m_d(size_t num, double4c* c, const double4c* a, const double4c* b); #ifdef __cplusplus } #endif #endif /* OSKAR_MEM_MULTIPLY_H_ */
davepallot/OSKAR
oskar/beam_pattern/private_beam_pattern.h
<gh_stars>1-10 /* * Copyright (c) 2016-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <mem/oskar_mem.h> #include <telescope/oskar_telescope.h> #include <utility/oskar_timer.h> #include <utility/oskar_thread.h> #include <fitsio.h> #include <stdio.h> #include <stddef.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /* Memory allocated per device. */ struct DeviceData { /* Host memory. */ /* Chunks have dimension max_chunk_size * num_active_stations. */ /* Cross power beams have dimension max_chunk_size. */ oskar_Mem* jones_data_cpu[2]; /* On host, for copy back & write. */ /* Per Stokes parameter. */ oskar_Mem* auto_power_cpu[4][2]; /* On host, for copy back & write. */ oskar_Mem* auto_power_time_avg[4]; oskar_Mem* auto_power_channel_avg[4]; oskar_Mem* auto_power_channel_and_time_avg[4]; oskar_Mem* cross_power_cpu[4][2]; /* On host, for copy back & write. */ oskar_Mem* cross_power_time_avg[4]; oskar_Mem* cross_power_channel_avg[4]; oskar_Mem* cross_power_channel_and_time_avg[4]; /* Device memory. */ int previous_chunk_index; oskar_Telescope* tel; oskar_StationWork* work; oskar_Mem *x, *y, *z, *jones_data; oskar_Mem *auto_power[4], *cross_power[4]; /* Timers. */ oskar_Timer* tmr_compute; /* Total time spent calculating pixels. */ }; typedef struct DeviceData DeviceData; struct DataProduct { int type; int stokes_in; /* Source polarisation type. */ int stokes_out; /* Image polarisation type. */ int i_station; int time_average; int channel_average; fitsfile* fits_file; FILE* text_file; }; typedef struct DataProduct DataProduct; struct oskar_BeamPattern { /* Settings. */ int prec, num_devices, num_gpus, *gpu_ids; int coord_type, max_chunk_size; int num_time_steps, num_channels, num_chunks; int pol_mode, width, height, num_pixels, nside; int num_active_stations, *station_ids; int voltage_amp_txt, voltage_phase_txt, voltage_raw_txt, auto_power_txt; int voltage_amp_fits, voltage_phase_fits, auto_power_fits; int cross_power_amp_txt, cross_power_phase_txt, cross_power_raw_txt; int cross_power_amp_fits, cross_power_phase_fits, ixr_txt, ixr_fits; int average_time_and_channel, separate_time_and_channel, stokes[4]; double lon0, lat0, phase_centre_deg[2], fov_deg[2]; double time_start_mjd_utc, time_inc_sec, length_sec; double freq_start_hz, freq_inc_hz; char average_single_axis, coord_frame_type, coord_grid_type; char *root_path, *sky_model_file; /* State. */ oskar_Mutex* mutex; oskar_Barrier* barrier; int i_global, status; /* Input data. */ oskar_Mem *x, *y, *z; oskar_Telescope* tel; /* Temporary arrays. */ oskar_Mem* pix; /* Real-valued pixel array to write to file. */ oskar_Mem* ctemp; /* Complex-valued array used for reordering. */ /* Settings log data. */ oskar_Log* log; char* settings_log; size_t settings_log_length; /* Data product list. */ int num_data_products; DataProduct* data_products; /* Timers. */ oskar_Timer *tmr_sim, *tmr_write; /* Array of DeviceData structures, one per compute device. */ DeviceData* d; }; #ifndef OSKAR_BEAM_PATTERN_TYPEDEF_ #define OSKAR_BEAM_PATTERN_TYPEDEF_ typedef struct oskar_BeamPattern oskar_BeamPattern; #endif enum OSKAR_BEAM_PATTERN_DATA_PRODUCT_TYPE { RAW_COMPLEX, AMP, PHASE, AUTO_POWER, CROSS_POWER_RAW_COMPLEX, CROSS_POWER_AMP, CROSS_POWER_PHASE, IXR }; enum OSKAR_BEAM_DATA_TYPE { JONES_DATA, AUTO_POWER_DATA, CROSS_POWER_DATA }; enum OSKAR_STOKES { /* IQUV must be 0 to 3. */ I = 0, Q = 1, U = 2, V = 3, XX = 4, XY = 5, YX = 6, YY = 7 }; #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/vis/src/oskar_vis_header_write_ms.c
/* * Copyright (c) 2015-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "vis/oskar_vis_header.h" #include "math/oskar_cmath.h" #include "utility/oskar_dir.h" #include "ms/oskar_measurement_set.h" #include "oskar_version.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif oskar_MeasurementSet* oskar_vis_header_write_ms(const oskar_VisHeader* hdr, const char* ms_path, int overwrite, int force_polarised, int* status) { const oskar_Mem *x_metres, *y_metres, *z_metres; double freq_start_hz, freq_inc_hz, ra_rad, dec_rad; int amp_type, autocorr, crosscorr, dir_exists, len; unsigned int num_stations, num_pols, num_channels; char *output_path = 0; oskar_MeasurementSet* ms = 0; /* Check if safe to proceed. */ if (*status) return 0; /* Pull data from visibility structure. */ amp_type = oskar_vis_header_amp_type(hdr); num_stations = oskar_vis_header_num_stations(hdr); num_channels = oskar_vis_header_num_channels_total(hdr); ra_rad = oskar_vis_header_phase_centre_ra_deg(hdr) * M_PI / 180.0; dec_rad = oskar_vis_header_phase_centre_dec_deg(hdr) * M_PI / 180.0; freq_start_hz = oskar_vis_header_freq_start_hz(hdr); freq_inc_hz = oskar_vis_header_freq_inc_hz(hdr); x_metres = oskar_vis_header_station_x_offset_ecef_metres_const(hdr); y_metres = oskar_vis_header_station_y_offset_ecef_metres_const(hdr); z_metres = oskar_vis_header_station_z_offset_ecef_metres_const(hdr); autocorr = oskar_vis_header_write_auto_correlations(hdr); crosscorr = oskar_vis_header_write_cross_correlations(hdr); num_pols = oskar_type_is_matrix(amp_type) ? 4 : 1; /* Force creation of polarised output data if flag is set. */ if (force_polarised) num_pols = 4; /* Set channel width to be greater than 0, if it isn't already. * This is required for the Measurement Set to be valid. */ if (! (freq_inc_hz > 0.0)) freq_inc_hz = 1.0; /* Check and add '.MS' file extension if necessary. */ len = (int) strlen(ms_path); output_path = (char*) calloc(6 + len, 1); if ((len >= 3) && ( !strcmp(&(ms_path[len-3]), ".MS") || !strcmp(&(ms_path[len-3]), ".ms") )) strcpy(output_path, ms_path); else sprintf(output_path, "%s.MS", ms_path); /* If directory doesn't exist, or if overwrite flag is set, * create a new one. */ dir_exists = oskar_dir_exists(output_path); if (!dir_exists || overwrite) { /* Remove any existing directory. */ if (dir_exists && overwrite) oskar_dir_remove(output_path); /* Create the Measurement Set. */ ms = oskar_ms_create(output_path, "OSKAR " OSKAR_VERSION_STR, num_stations, num_channels, num_pols, freq_start_hz, freq_inc_hz, NULL, autocorr, crosscorr); free(output_path); if (!ms) { *status = OSKAR_ERR_FILE_IO; return 0; } /* Set the phase centre. */ oskar_ms_set_phase_centre(ms, 0, ra_rad, dec_rad); /* Set the station positions. */ if (oskar_mem_type(x_metres) == OSKAR_DOUBLE) { oskar_ms_set_station_coords_d(ms, num_stations, oskar_mem_double_const(x_metres, status), oskar_mem_double_const(y_metres, status), oskar_mem_double_const(z_metres, status)); } else { oskar_ms_set_station_coords_f(ms, num_stations, oskar_mem_float_const(x_metres, status), oskar_mem_float_const(y_metres, status), oskar_mem_float_const(z_metres, status)); } /* Add the settings. */ oskar_ms_add_history(ms, "OSKAR_SETTINGS", oskar_mem_char_const(oskar_vis_header_settings_const(hdr)), oskar_mem_length(oskar_vis_header_settings_const(hdr))); } /* If directory already exists and we're not overwriting, open it. */ else { /* Open the Measurement Set. */ ms = oskar_ms_open(output_path); free(output_path); if (!ms) { *status = OSKAR_ERR_FILE_IO; return 0; } /* Check the dimensions match. */ if (oskar_ms_num_channels(ms) != num_channels || oskar_ms_num_pols(ms) != num_pols || oskar_ms_num_stations(ms) != num_stations) { *status = OSKAR_ERR_DIMENSION_MISMATCH; oskar_ms_close(ms); return 0; } /* Check the reference frequencies match. */ if (fabs(oskar_ms_freq_start_hz(ms) - freq_start_hz) > 1e-10) { *status = OSKAR_ERR_VALUE_MISMATCH; oskar_ms_close(ms); return 0; } /* Check the phase centres are the same. */ if (fabs(oskar_ms_phase_centre_ra_rad(ms) - ra_rad) > 1e-10 || fabs(oskar_ms_phase_centre_dec_rad(ms) - dec_rad) > 1e-10) { *status = OSKAR_ERR_VALUE_MISMATCH; oskar_ms_close(ms); return 0; } } return ms; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/element/src/oskar_element_free.c
/* * Copyright (c) 2012-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/element/private_element.h" #include "telescope/station/element/oskar_element.h" #ifdef __cplusplus extern "C" { #endif void oskar_element_free(oskar_Element* data, int* status) { int i; if (!data) return; /* Free the memory contents. */ for (i = 0; i < data->num_freq; ++i) { oskar_mem_free(data->filename_x[i], status); oskar_mem_free(data->filename_y[i], status); oskar_mem_free(data->filename_scalar[i], status); oskar_splines_free(data->x_v_re[i], status); oskar_splines_free(data->x_v_im[i], status); oskar_splines_free(data->x_h_re[i], status); oskar_splines_free(data->x_h_im[i], status); oskar_splines_free(data->y_v_re[i], status); oskar_splines_free(data->y_v_im[i], status); oskar_splines_free(data->y_h_re[i], status); oskar_splines_free(data->y_h_im[i], status); oskar_splines_free(data->scalar_re[i], status); oskar_splines_free(data->scalar_im[i], status); } free(data->freqs_hz); free(data->filename_x); free(data->filename_y); free(data->filename_scalar); free(data->x_h_re); free(data->x_h_im); free(data->x_v_re); free(data->x_v_im); free(data->y_h_re); free(data->y_h_im); free(data->y_v_re); free(data->y_v_im); free(data->scalar_re); free(data->scalar_im); /* Free the structure itself. */ free(data); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/element/src/oskar_apply_element_taper_gaussian.c
/* * Copyright (c) 2012-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/element/oskar_apply_element_taper_gaussian.h" #include "telescope/station/element/oskar_apply_element_taper_gaussian_cuda.h" #include "utility/oskar_cl_utils.h" #include "utility/oskar_device_utils.h" #include <math.h> #define M_4LN2 2.77258872223978123767 #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_apply_element_taper_gaussian_scalar_f(const int num_sources, const float inv_2sigma_sq, const float* theta, float2* jones) { int i; for (i = 0; i < num_sources; ++i) { float f, theta_sq; theta_sq = theta[i]; theta_sq *= theta_sq; f = expf(-theta_sq * inv_2sigma_sq); jones[i].x *= f; jones[i].y *= f; } } void oskar_apply_element_taper_gaussian_matrix_f(const int num_sources, const float inv_2sigma_sq, const float* theta, float4c* jones) { int i; for (i = 0; i < num_sources; ++i) { float f, theta_sq; theta_sq = theta[i]; theta_sq *= theta_sq; f = expf(-theta_sq * inv_2sigma_sq); jones[i].a.x *= f; jones[i].a.y *= f; jones[i].b.x *= f; jones[i].b.y *= f; jones[i].c.x *= f; jones[i].c.y *= f; jones[i].d.x *= f; jones[i].d.y *= f; } } /* Double precision. */ void oskar_apply_element_taper_gaussian_scalar_d(const int num_sources, const double inv_2sigma_sq, const double* theta, double2* jones) { int i; for (i = 0; i < num_sources; ++i) { double f, theta_sq; theta_sq = theta[i]; theta_sq *= theta_sq; f = exp(-theta_sq * inv_2sigma_sq); jones[i].x *= f; jones[i].y *= f; } } void oskar_apply_element_taper_gaussian_matrix_d(const int num_sources, const double inv_2sigma_sq, const double* theta, double4c* jones) { int i; for (i = 0; i < num_sources; ++i) { double f, theta_sq; theta_sq = theta[i]; theta_sq *= theta_sq; f = exp(-theta_sq * inv_2sigma_sq); jones[i].a.x *= f; jones[i].a.y *= f; jones[i].b.x *= f; jones[i].b.y *= f; jones[i].c.x *= f; jones[i].c.y *= f; jones[i].d.x *= f; jones[i].d.y *= f; } } /* Wrapper. */ void oskar_apply_element_taper_gaussian(oskar_Mem* jones, int num_sources, double fwhm, const oskar_Mem* theta, int* status) { if (*status) return; /* Check arrays are co-located. */ const int location = oskar_mem_location(jones); if (oskar_mem_location(theta) != location) { *status = OSKAR_ERR_LOCATION_MISMATCH; return; } /* Check types for consistency. */ if (oskar_mem_type(theta) != oskar_mem_precision(jones)) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } /* Apply taper. */ const double inv_2sigma_sq = M_4LN2 / (fwhm * fwhm); if (location == OSKAR_CPU) { switch (oskar_mem_type(jones)) { case OSKAR_SINGLE_COMPLEX: oskar_apply_element_taper_gaussian_scalar_f(num_sources, (float)inv_2sigma_sq, oskar_mem_float_const(theta, status), oskar_mem_float2(jones, status)); break; case OSKAR_DOUBLE_COMPLEX: oskar_apply_element_taper_gaussian_scalar_d(num_sources, inv_2sigma_sq, oskar_mem_double_const(theta, status), oskar_mem_double2(jones, status)); break; case OSKAR_SINGLE_COMPLEX_MATRIX: oskar_apply_element_taper_gaussian_matrix_f(num_sources, (float)inv_2sigma_sq, oskar_mem_float_const(theta, status), oskar_mem_float4c(jones, status)); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: oskar_apply_element_taper_gaussian_matrix_d(num_sources, inv_2sigma_sq, oskar_mem_double_const(theta, status), oskar_mem_double4c(jones, status)); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; break; } } else if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA switch (oskar_mem_type(jones)) { case OSKAR_SINGLE_COMPLEX: oskar_apply_element_taper_gaussian_scalar_cuda_f(num_sources, (float)inv_2sigma_sq, oskar_mem_float_const(theta, status), oskar_mem_float2(jones, status)); break; case OSKAR_DOUBLE_COMPLEX: oskar_apply_element_taper_gaussian_scalar_cuda_d(num_sources, inv_2sigma_sq, oskar_mem_double_const(theta, status), oskar_mem_double2(jones, status)); break; case OSKAR_SINGLE_COMPLEX_MATRIX: oskar_apply_element_taper_gaussian_matrix_cuda_f(num_sources, (float)inv_2sigma_sq, oskar_mem_float_const(theta, status), oskar_mem_float4c(jones, status)); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: oskar_apply_element_taper_gaussian_matrix_cuda_d(num_sources, inv_2sigma_sq, oskar_mem_double_const(theta, status), oskar_mem_double4c(jones, status)); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; break; } oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location & OSKAR_CL) { #ifdef OSKAR_HAVE_OPENCL cl_device_type dev_type; cl_event event; cl_kernel k = 0; cl_int is_gpu, error, num; cl_uint arg = 0; size_t global_size, local_size; clGetDeviceInfo(oskar_cl_device_id(), CL_DEVICE_TYPE, sizeof(cl_device_type), &dev_type, NULL); is_gpu = dev_type & CL_DEVICE_TYPE_GPU; switch (oskar_mem_type(jones)) { case OSKAR_SINGLE_COMPLEX: k = oskar_cl_kernel("apply_element_taper_gaussian_scalar_float"); break; case OSKAR_DOUBLE_COMPLEX: k = oskar_cl_kernel("apply_element_taper_gaussian_scalar_double"); break; case OSKAR_SINGLE_COMPLEX_MATRIX: k = oskar_cl_kernel("apply_element_taper_gaussian_matrix_float"); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: k = oskar_cl_kernel("apply_element_taper_gaussian_matrix_double"); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; return; } if (!k) { *status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE; return; } /* Set kernel arguments. */ num = (cl_int) num_sources; error = clSetKernelArg(k, arg++, sizeof(cl_int), &num); if (oskar_mem_precision(jones) == OSKAR_SINGLE) { cl_float w = (cl_float) inv_2sigma_sq; error = clSetKernelArg(k, arg++, sizeof(cl_float), &w); } else { cl_double w = (cl_double) inv_2sigma_sq; error = clSetKernelArg(k, arg++, sizeof(cl_double), &w); } error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer_const(theta, status)); error |= clSetKernelArg(k, arg++, sizeof(cl_mem), oskar_mem_cl_buffer(jones, status)); if (error != CL_SUCCESS) { *status = OSKAR_ERR_INVALID_ARGUMENT; return; } /* Launch kernel on current command queue. */ local_size = is_gpu ? 256 : 128; global_size = ((num + local_size - 1) / local_size) * local_size; error = clEnqueueNDRangeKernel(oskar_cl_command_queue(), k, 1, NULL, &global_size, &local_size, 0, NULL, &event); if (error != CL_SUCCESS) *status = OSKAR_ERR_KERNEL_LAUNCH_FAILURE; #else *status = OSKAR_ERR_OPENCL_NOT_AVAILABLE; #endif } else *status = OSKAR_ERR_BAD_LOCATION; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/src/oskar_station_resize.c
<reponame>davepallot/OSKAR<gh_stars>1-10 /* * Copyright (c) 2011-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/private_station.h" #include "telescope/station/oskar_station.h" #include "math/oskar_cmath.h" #include <string.h> #ifdef __cplusplus extern "C" { #endif void oskar_station_resize(oskar_Station* station, int num_elements, int* status) { /* Check if safe to proceed. */ if (*status) return; /* Resize arrays in the model. */ oskar_mem_realloc(station->element_true_x_enu_metres, num_elements, status); oskar_mem_realloc(station->element_true_y_enu_metres, num_elements, status); oskar_mem_realloc(station->element_true_z_enu_metres, num_elements, status); oskar_mem_realloc(station->element_measured_x_enu_metres, num_elements, status); oskar_mem_realloc(station->element_measured_y_enu_metres, num_elements, status); oskar_mem_realloc(station->element_measured_z_enu_metres, num_elements, status); oskar_mem_realloc(station->element_weight, num_elements, status); oskar_mem_realloc(station->element_gain, num_elements, status); oskar_mem_realloc(station->element_gain_error, num_elements, status); oskar_mem_realloc(station->element_phase_offset_rad, num_elements, status); oskar_mem_realloc(station->element_phase_error_rad, num_elements, status); oskar_mem_realloc(station->element_x_alpha_cpu, num_elements, status); oskar_mem_realloc(station->element_x_beta_cpu, num_elements, status); oskar_mem_realloc(station->element_x_gamma_cpu, num_elements, status); oskar_mem_realloc(station->element_y_alpha_cpu, num_elements, status); oskar_mem_realloc(station->element_y_beta_cpu, num_elements, status); oskar_mem_realloc(station->element_y_gamma_cpu, num_elements, status); oskar_mem_realloc(station->element_types, num_elements, status); oskar_mem_realloc(station->element_types_cpu, num_elements, status); oskar_mem_realloc(station->element_mount_types_cpu, num_elements, status); /* Initialise any new elements with default values. */ if (num_elements > station->num_elements) { int offset, num_new; offset = station->num_elements; num_new = num_elements - offset; /* Must set default element weight, gain and orientation. */ oskar_mem_set_value_real(station->element_gain, 1.0, offset, num_new, status); oskar_mem_set_value_real(station->element_weight, 1.0, offset, num_new, status); memset(oskar_mem_char(station->element_mount_types_cpu) + offset, 'F', num_new); } /* Set the new number of elements. */ station->num_elements = num_elements; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/settings/old/oskar_Settings_old.h
<reponame>davepallot/OSKAR /* * Copyright (c) 2011-2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_SETTINGS_OLD_H_ #define OSKAR_SETTINGS_OLD_H_ #ifdef __cplusplus #include <cstring> #include <cstdlib> #endif struct oskar_SettingsSimulator { int double_precision, keep_log_file; }; typedef struct oskar_SettingsSimulator oskar_SettingsSimulator; struct oskar_SettingsObservation { int num_time_steps; double start_mjd_utc, length_sec, length_days, dt_dump_days; }; typedef struct oskar_SettingsObservation oskar_SettingsObservation; struct oskar_SettingsTIDscreen { double height_km; /* Height of the TID screen, km */ int num_components; /* Number of TID components in the screen */ double* amp; /* Relative amplitude compared to TEC0 */ double* wavelength; /* km */ double* speed; /* km/h */ double* theta; /* deg. */ }; typedef struct oskar_SettingsTIDscreen oskar_SettingsTIDscreen; struct oskar_SettingsTECImage { int stationID; /* Index of the station for which to evaluate the TEC image */ int beam_centred; /* Bool, centre the TEC image on the beam direction */ double fov_rad; /* Image field of view, in radians */ int size; /* Image size along one dimension */ char* fits_file; /* File name for TEC image in FITS format */ }; typedef struct oskar_SettingsTECImage oskar_SettingsTECImage; struct oskar_SettingsPiercePoints { char* filename; }; typedef struct oskar_SettingsPiercePoints oskar_SettingsPiercePoints; struct oskar_SettingsIonosphere { int enable; /* Flag to enable/disable MIM evaluation. */ double min_elevation; /* Minimum elevation for MIM evaluation, in radians. */ double TEC0; /* Zero offset TEC value. */ int num_TID_screens; /* Number of TID TEC screens evaluated. */ char** TID_files; /* TID settings files (one for each screen height). */ oskar_SettingsTIDscreen* TID; /* Array of TID screen structures. */ oskar_SettingsTECImage TECImage; oskar_SettingsPiercePoints pierce_points; }; typedef struct oskar_SettingsIonosphere oskar_SettingsIonosphere; struct oskar_Settings_old { oskar_SettingsSimulator sim; oskar_SettingsObservation obs; oskar_SettingsIonosphere ionosphere; #ifdef __cplusplus oskar_Settings_old() { std::memset((void*) this, 0, sizeof(oskar_Settings_old)); } ~oskar_Settings_old() { for (int i = 0; i < this->ionosphere.num_TID_screens; ++i) { free(this->ionosphere.TID_files[i]); free(this->ionosphere.TID[i].amp); free(this->ionosphere.TID[i].speed); free(this->ionosphere.TID[i].theta); free(this->ionosphere.TID[i].wavelength); } free(this->ionosphere.TID); free(this->ionosphere.TID_files); free(this->ionosphere.TECImage.fits_file); free(this->ionosphere.pierce_points.filename); } #endif }; typedef struct oskar_Settings_old oskar_Settings_old; #endif /* OSKAR_SETTINGS_OLD_H_ */
davepallot/OSKAR
oskar/telescope/station/src/oskar_evaluate_beam_horizon_direction.c
<reponame>davepallot/OSKAR /* * Copyright (c) 2011-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/oskar_evaluate_beam_horizon_direction.h" #include "convert/oskar_convert_apparent_ra_dec_to_enu_directions.h" #include "math/oskar_angular_distance.h" #include <stdlib.h> #include <math.h> #include <float.h> #ifdef __cplusplus extern "C" { #endif void oskar_evaluate_beam_horizon_direction(double* x, double* y, double* z, const oskar_Station* station, const double gast, int* status) { int beam_coord_type; double beam_lon, beam_lat; /* Check if safe to proceed. */ if (*status) return; /* Get direction cosines in horizontal coordinates. */ beam_coord_type = oskar_station_beam_coord_type(station); beam_lon = oskar_station_beam_lon_rad(station); beam_lat = oskar_station_beam_lat_rad(station); if (beam_coord_type == OSKAR_SPHERICAL_TYPE_EQUATORIAL) { double lon, lat, last; lon = oskar_station_lon_rad(station); lat = oskar_station_lat_rad(station); last = gast + lon; /* Local Apparent Sidereal Time, in radians. */ oskar_convert_apparent_ra_dec_to_enu_directions_d(1, &beam_lon, &beam_lat, last, lat, x, y, z); } else if (beam_coord_type == OSKAR_SPHERICAL_TYPE_AZEL) { /* Convert AZEL to direction cosines. */ double cos_lat; cos_lat = cos(beam_lat); *x = cos_lat * sin(beam_lon); *y = cos_lat * cos(beam_lon); *z = sin(beam_lat); } else { *status = OSKAR_ERR_INVALID_ARGUMENT; } /* Check if the beam direction needs to be one of a set of * allowed (az,el) directions. */ if (oskar_station_num_permitted_beams(station) > 0) { int i, n, min_index = 0; double az, el, cos_el, min_dist = DBL_MAX; const double *p_az, *p_el; /* Convert current direction cosines to azimuth, elevation. */ az = atan2(*x, *y); el = atan2(*z, sqrt(*x * *x + *y * *y)); /* Get pointers to permitted beam data. */ n = oskar_station_num_permitted_beams(station); p_az = oskar_mem_double_const( oskar_station_permitted_beam_az_rad_const(station), status); p_el = oskar_mem_double_const( oskar_station_permitted_beam_el_rad_const(station), status); /* Loop over permitted beams. */ for (i = 0; i < n; ++i) { double dist; dist = oskar_angular_distance(p_az[i], az, p_el[i], el); if (dist < min_dist) { min_dist = dist; min_index = i; } } /* Select beam azimuth and elevation based on minimum distance. */ az = p_az[min_index]; el = p_el[min_index]; /* Set new direction cosines. */ cos_el = cos(el); *x = cos_el * sin(az); *y = cos_el * cos(az); *z = sin(el); } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/src/oskar_station_different.c
<reponame>davepallot/OSKAR<gh_stars>1-10 /* * Copyright (c) 2013-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/private_station.h" #include "telescope/station/oskar_station.h" #include "mem/oskar_mem.h" #include <stdio.h> #ifdef __cplusplus extern "C" { #endif int oskar_station_different(const oskar_Station* a, const oskar_Station* b, int* status) { int i, j, n, num_element_types; /* Check if safe to proceed. */ if (*status) return 1; /* Don't check the unique ID, for obvious reasons! */ /* Check if the meta-data are different. */ n = a->num_elements; if (a->station_type != b->station_type || a->normalise_final_beam != b->normalise_final_beam || a->beam_coord_type != b->beam_coord_type || a->beam_lon_rad != b->beam_lon_rad || a->beam_lat_rad != b->beam_lat_rad || a->pm_x_rad != b->pm_x_rad || a->pm_y_rad != b->pm_y_rad || a->identical_children != b->identical_children || a->num_elements != b->num_elements || a->num_element_types != b->num_element_types || a->normalise_array_pattern != b->normalise_array_pattern || a->enable_array_pattern != b->enable_array_pattern || a->common_element_orientation != b->common_element_orientation || a->array_is_3d != b->array_is_3d || a->apply_element_errors != b->apply_element_errors || a->apply_element_weight != b->apply_element_weight || a->gaussian_beam_fwhm_rad != b->gaussian_beam_fwhm_rad || a->gaussian_beam_reference_freq_hz != b->gaussian_beam_reference_freq_hz || a->num_permitted_beams != b->num_permitted_beams) { return 1; } /* Check if child stations exist. */ if ((oskar_station_has_child(a) && !oskar_station_has_child(b)) || (!oskar_station_has_child(a) && oskar_station_has_child(b))) return 1; /* Check if element patterns exist. */ if ( (oskar_station_has_element(a) && !oskar_station_has_element(b)) || (!oskar_station_has_element(a) && oskar_station_has_element(b)) ) return 1; /* Check if element pattern filenames are different, * for each element type. */ num_element_types = oskar_station_num_element_types(a); for (j = 0; j < num_element_types; ++j) { const oskar_Element *e_a, *e_b; int num_freq_a, num_freq_b; e_a = oskar_station_element_const(a, j); e_b = oskar_station_element_const(b, j); /* Check if number of frequencies in element models are different. */ num_freq_a = oskar_element_num_freq(e_a); num_freq_b = oskar_element_num_freq(e_b); if (num_freq_a != num_freq_b) return 1; for (i = 0; i < num_freq_a; ++i) { const oskar_Mem *fname_a_x = 0, *fname_a_y = 0; const oskar_Mem *fname_b_x = 0, *fname_b_y = 0; fname_a_x = oskar_element_x_filename_const(e_a, i); fname_a_y = oskar_element_y_filename_const(e_a, i); fname_b_x = oskar_element_x_filename_const(e_b, i); fname_b_y = oskar_element_y_filename_const(e_b, i); if (oskar_mem_different(fname_a_x, fname_b_x, 0, status)) return 1; if (oskar_mem_different(fname_a_y, fname_b_y, 0, status)) return 1; } } /* Check if the memory contents are different. */ if (oskar_mem_different(a->noise_freq_hz, b->noise_freq_hz, 0, status)) return 1; if (oskar_mem_different(a->noise_rms_jy, b->noise_rms_jy, 0, status)) return 1; if (oskar_mem_different(a->element_measured_x_enu_metres, b->element_measured_x_enu_metres, n, status)) return 1; if (oskar_mem_different(a->element_measured_y_enu_metres, b->element_measured_y_enu_metres, n, status)) return 1; if (oskar_mem_different(a->element_measured_z_enu_metres, b->element_measured_z_enu_metres, n, status)) return 1; if (oskar_mem_different(a->element_true_x_enu_metres, b->element_true_x_enu_metres, n, status)) return 1; if (oskar_mem_different(a->element_true_y_enu_metres, b->element_true_y_enu_metres, n, status)) return 1; if (oskar_mem_different(a->element_true_z_enu_metres, b->element_true_z_enu_metres, n, status)) return 1; if (oskar_mem_different(a->element_gain, b->element_gain, n, status)) return 1; if (oskar_mem_different(a->element_phase_offset_rad, b->element_phase_offset_rad, n, status)) return 1; if (oskar_mem_different(a->element_weight, b->element_weight, n, status)) return 1; if (oskar_mem_different(a->element_x_alpha_cpu, b->element_x_alpha_cpu, n, status)) return 1; if (oskar_mem_different(a->element_x_beta_cpu, b->element_x_beta_cpu, n, status)) return 1; if (oskar_mem_different(a->element_x_gamma_cpu, b->element_x_gamma_cpu, n, status)) return 1; if (oskar_mem_different(a->element_y_alpha_cpu, b->element_y_alpha_cpu, n, status)) return 1; if (oskar_mem_different(a->element_y_beta_cpu, b->element_y_beta_cpu, n, status)) return 1; if (oskar_mem_different(a->element_y_gamma_cpu, b->element_y_gamma_cpu, n, status)) return 1; if (oskar_mem_different(a->element_types, b->element_types, n, status)) return 1; if (oskar_mem_different(a->element_types_cpu, b->element_types_cpu, n, status)) return 1; if (oskar_mem_different(a->element_mount_types_cpu, b->element_mount_types_cpu, n, status)) return 1; if (oskar_mem_different(a->permitted_beam_az_rad, b->permitted_beam_az_rad, n, status)) return 1; if (oskar_mem_different(a->permitted_beam_el_rad, b->permitted_beam_el_rad, n, status)) return 1; /* Recursively check child stations. */ if (oskar_station_has_child(a) && oskar_station_has_child(b)) { for (i = 0; i < n; ++i) { if (oskar_station_different(oskar_station_child_const(a, i), oskar_station_child_const(b, i), status)) return 1; } } /* Stations must be the same! */ return 0; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/vis/oskar_vis_block_accessors.h
/* * Copyright (c) 2015-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_VIS_BLOCK_ACCESSORS_H_ #define OSKAR_VIS_BLOCK_ACCESSORS_H_ /** * @file oskar_vis_block_accessors.h */ #include <oskar_global.h> #include <mem/oskar_mem.h> #ifdef __cplusplus extern "C" { #endif OSKAR_EXPORT int oskar_vis_block_location(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_num_baselines(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_num_channels(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_num_stations(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_num_times(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_num_pols(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_start_channel_index(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_start_time_index(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_has_auto_correlations(const oskar_VisBlock* vis); OSKAR_EXPORT int oskar_vis_block_has_cross_correlations(const oskar_VisBlock* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_block_baseline_uu_metres(oskar_VisBlock* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_block_baseline_uu_metres_const( const oskar_VisBlock* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_block_baseline_vv_metres(oskar_VisBlock* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_block_baseline_vv_metres_const( const oskar_VisBlock* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_block_baseline_ww_metres(oskar_VisBlock* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_block_baseline_ww_metres_const( const oskar_VisBlock* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_block_auto_correlations(oskar_VisBlock* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_block_auto_correlations_const( const oskar_VisBlock* vis); OSKAR_EXPORT oskar_Mem* oskar_vis_block_cross_correlations(oskar_VisBlock* vis); OSKAR_EXPORT const oskar_Mem* oskar_vis_block_cross_correlations_const( const oskar_VisBlock* vis); OSKAR_EXPORT void oskar_vis_block_set_num_channels(oskar_VisBlock* vis, int value, int* status); OSKAR_EXPORT void oskar_vis_block_set_num_times(oskar_VisBlock* vis, int value, int* status); OSKAR_EXPORT void oskar_vis_block_set_start_channel_index(oskar_VisBlock* vis, int global_index); OSKAR_EXPORT void oskar_vis_block_set_start_time_index(oskar_VisBlock* vis, int global_index); #ifdef __cplusplus } #endif #endif /* OSKAR_VIS_BLOCK_ACCESSORS_H_ */
davepallot/OSKAR
oskar/correlate/src/oskar_cross_correlate.c
<filename>oskar/correlate/src/oskar_cross_correlate.c /* * Copyright (c) 2011-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "correlate/oskar_cross_correlate.h" #include "correlate/oskar_cross_correlate_cuda.h" #include "correlate/oskar_cross_correlate_omp.h" #include "correlate/oskar_cross_correlate_scalar_cuda.h" #include "correlate/oskar_cross_correlate_scalar_omp.h" #include "utility/oskar_device_utils.h" #include <float.h> #include <math.h> #ifdef __cplusplus extern "C" { #endif void oskar_cross_correlate(oskar_Mem* vis, int n_sources, const oskar_Jones* jones, const oskar_Sky* sky, const oskar_Telescope* tel, const oskar_Mem* u, const oskar_Mem* v, const oskar_Mem* w, double gast, double frequency_hz, int* status) { int jones_type, base_type, location, n_stations, use_extended; double inv_wavelength, frac_bandwidth, time_avg, gha0, dec0; double uv_filter_max, uv_filter_min; const oskar_Mem *J, *a, *b, *c, *l, *m, *n, *I, *Q, *U, *V, *x, *y; /* Check if safe to proceed. */ if (*status) return; /* Get the data dimensions. */ n_stations = oskar_telescope_num_stations(tel); use_extended = oskar_sky_use_extended(sky); /* Get bandwidth-smearing terms. */ frequency_hz = fabs(frequency_hz); inv_wavelength = frequency_hz / 299792458.0; frac_bandwidth = oskar_telescope_channel_bandwidth_hz(tel) / frequency_hz; /* Get time-average smearing term and Greenwich hour angle. */ time_avg = oskar_telescope_time_average_sec(tel); gha0 = gast - oskar_telescope_phase_centre_ra_rad(tel); dec0 = oskar_telescope_phase_centre_dec_rad(tel); /* Get UV filter parameters in wavelengths. */ uv_filter_min = oskar_telescope_uv_filter_min(tel); uv_filter_max = oskar_telescope_uv_filter_max(tel); if (oskar_telescope_uv_filter_units(tel) == OSKAR_METRES) { uv_filter_min *= inv_wavelength; uv_filter_max *= inv_wavelength; } if (uv_filter_max < 0.0 || uv_filter_max > FLT_MAX) uv_filter_max = FLT_MAX; /* Check data locations. */ location = oskar_sky_mem_location(sky); if (oskar_telescope_mem_location(tel) != location || oskar_jones_mem_location(jones) != location || oskar_mem_location(vis) != location || oskar_mem_location(u) != location || oskar_mem_location(v) != location || oskar_mem_location(w) != location) { *status = OSKAR_ERR_LOCATION_MISMATCH; return; } /* Check for consistent data types. */ jones_type = oskar_jones_type(jones); base_type = oskar_sky_precision(sky); if (oskar_mem_precision(vis) != base_type || oskar_type_precision(jones_type) != base_type || oskar_mem_type(u) != base_type || oskar_mem_type(v) != base_type || oskar_mem_type(w) != base_type) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } if (oskar_mem_type(vis) != jones_type) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } /* If neither single or double precision, return error. */ if (base_type != OSKAR_SINGLE && base_type != OSKAR_DOUBLE) { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } /* Check the input dimensions. */ if (oskar_jones_num_sources(jones) < n_sources || (int)oskar_mem_length(u) != n_stations || (int)oskar_mem_length(v) != n_stations || (int)oskar_mem_length(w) != n_stations) { *status = OSKAR_ERR_DIMENSION_MISMATCH; return; } /* Check there is enough space for the result. */ if ((int)oskar_mem_length(vis) < oskar_telescope_num_baselines(tel)) { *status = OSKAR_ERR_DIMENSION_MISMATCH; return; } /* Get handles to arrays. */ J = oskar_jones_mem_const(jones); I = oskar_sky_I_const(sky); Q = oskar_sky_Q_const(sky); U = oskar_sky_U_const(sky); V = oskar_sky_V_const(sky); l = oskar_sky_l_const(sky); m = oskar_sky_m_const(sky); n = oskar_sky_n_const(sky); a = oskar_sky_gaussian_a_const(sky); b = oskar_sky_gaussian_b_const(sky); c = oskar_sky_gaussian_c_const(sky); x = oskar_telescope_station_true_x_offset_ecef_metres_const(tel); y = oskar_telescope_station_true_y_offset_ecef_metres_const(tel); /* Select kernel. */ if (location == OSKAR_CPU) { if (use_extended) { switch (oskar_mem_type(vis)) { case OSKAR_SINGLE_COMPLEX_MATRIX: oskar_cross_correlate_gaussian_omp_f( n_sources, n_stations, oskar_mem_float4c_const(J, status), oskar_mem_float_const(I, status), oskar_mem_float_const(Q, status), oskar_mem_float_const(U, status), oskar_mem_float_const(V, status), oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), oskar_mem_float_const(a, status), oskar_mem_float_const(b, status), oskar_mem_float_const(c, status), oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), oskar_mem_float_const(x, status), oskar_mem_float_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_float4c(vis, status)); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: oskar_cross_correlate_gaussian_omp_d( n_sources, n_stations, oskar_mem_double4c_const(J, status), oskar_mem_double_const(I, status), oskar_mem_double_const(Q, status), oskar_mem_double_const(U, status), oskar_mem_double_const(V, status), oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), oskar_mem_double_const(a, status), oskar_mem_double_const(b, status), oskar_mem_double_const(c, status), oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), oskar_mem_double_const(x, status), oskar_mem_double_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_double4c(vis, status)); break; case OSKAR_SINGLE_COMPLEX: oskar_cross_correlate_scalar_gaussian_omp_f( n_sources, n_stations, oskar_mem_float2_const(J, status), oskar_mem_float_const(I, status), oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), oskar_mem_float_const(a, status), oskar_mem_float_const(b, status), oskar_mem_float_const(c, status), oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), oskar_mem_float_const(x, status), oskar_mem_float_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_float2(vis, status)); break; case OSKAR_DOUBLE_COMPLEX: oskar_cross_correlate_scalar_gaussian_omp_d( n_sources, n_stations, oskar_mem_double2_const(J, status), oskar_mem_double_const(I, status), oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), oskar_mem_double_const(a, status), oskar_mem_double_const(b, status), oskar_mem_double_const(c, status), oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), oskar_mem_double_const(x, status), oskar_mem_double_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_double2(vis, status)); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; return; } } else { switch (oskar_mem_type(vis)) { case OSKAR_SINGLE_COMPLEX_MATRIX: oskar_cross_correlate_point_omp_f( n_sources, n_stations, oskar_mem_float4c_const(J, status), oskar_mem_float_const(I, status), oskar_mem_float_const(Q, status), oskar_mem_float_const(U, status), oskar_mem_float_const(V, status), oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), oskar_mem_float_const(x, status), oskar_mem_float_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_float4c(vis, status)); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: oskar_cross_correlate_point_omp_d( n_sources, n_stations, oskar_mem_double4c_const(J, status), oskar_mem_double_const(I, status), oskar_mem_double_const(Q, status), oskar_mem_double_const(U, status), oskar_mem_double_const(V, status), oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), oskar_mem_double_const(x, status), oskar_mem_double_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_double4c(vis, status)); break; case OSKAR_SINGLE_COMPLEX: oskar_cross_correlate_scalar_point_omp_f( n_sources, n_stations, oskar_mem_float2_const(J, status), oskar_mem_float_const(I, status), oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), oskar_mem_float_const(x, status), oskar_mem_float_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_float2(vis, status)); break; case OSKAR_DOUBLE_COMPLEX: oskar_cross_correlate_scalar_point_omp_d( n_sources, n_stations, oskar_mem_double2_const(J, status), oskar_mem_double_const(I, status), oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), oskar_mem_double_const(x, status), oskar_mem_double_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_double2(vis, status)); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; return; } } } else if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA if (use_extended) { switch (oskar_mem_type(vis)) { case OSKAR_SINGLE_COMPLEX_MATRIX: oskar_cross_correlate_gaussian_cuda_f( n_sources, n_stations, oskar_mem_float4c_const(J, status), oskar_mem_float_const(I, status), oskar_mem_float_const(Q, status), oskar_mem_float_const(U, status), oskar_mem_float_const(V, status), oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), oskar_mem_float_const(a, status), oskar_mem_float_const(b, status), oskar_mem_float_const(c, status), oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), oskar_mem_float_const(x, status), oskar_mem_float_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_float4c(vis, status)); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: oskar_cross_correlate_gaussian_cuda_d( n_sources, n_stations, oskar_mem_double4c_const(J, status), oskar_mem_double_const(I, status), oskar_mem_double_const(Q, status), oskar_mem_double_const(U, status), oskar_mem_double_const(V, status), oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), oskar_mem_double_const(a, status), oskar_mem_double_const(b, status), oskar_mem_double_const(c, status), oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), oskar_mem_double_const(x, status), oskar_mem_double_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_double4c(vis, status)); break; case OSKAR_SINGLE_COMPLEX: oskar_cross_correlate_scalar_gaussian_cuda_f( n_sources, n_stations, oskar_mem_float2_const(J, status), oskar_mem_float_const(I, status), oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), oskar_mem_float_const(a, status), oskar_mem_float_const(b, status), oskar_mem_float_const(c, status), oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), oskar_mem_float_const(x, status), oskar_mem_float_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_float2(vis, status)); break; case OSKAR_DOUBLE_COMPLEX: oskar_cross_correlate_scalar_gaussian_cuda_d( n_sources, n_stations, oskar_mem_double2_const(J, status), oskar_mem_double_const(I, status), oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), oskar_mem_double_const(a, status), oskar_mem_double_const(b, status), oskar_mem_double_const(c, status), oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), oskar_mem_double_const(x, status), oskar_mem_double_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_double2(vis, status)); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; return; } } else { switch (oskar_mem_type(vis)) { case OSKAR_SINGLE_COMPLEX_MATRIX: oskar_cross_correlate_point_cuda_f( n_sources, n_stations, oskar_mem_float4c_const(J, status), oskar_mem_float_const(I, status), oskar_mem_float_const(Q, status), oskar_mem_float_const(U, status), oskar_mem_float_const(V, status), oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), oskar_mem_float_const(x, status), oskar_mem_float_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_float4c(vis, status)); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: oskar_cross_correlate_point_cuda_d( n_sources, n_stations, oskar_mem_double4c_const(J, status), oskar_mem_double_const(I, status), oskar_mem_double_const(Q, status), oskar_mem_double_const(U, status), oskar_mem_double_const(V, status), oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), oskar_mem_double_const(x, status), oskar_mem_double_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_double4c(vis, status)); break; case OSKAR_SINGLE_COMPLEX: oskar_cross_correlate_scalar_point_cuda_f( n_sources, n_stations, oskar_mem_float2_const(J, status), oskar_mem_float_const(I, status), oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), oskar_mem_float_const(x, status), oskar_mem_float_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_float2(vis, status)); break; case OSKAR_DOUBLE_COMPLEX: oskar_cross_correlate_scalar_point_cuda_d( n_sources, n_stations, oskar_mem_double2_const(J, status), oskar_mem_double_const(I, status), oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), oskar_mem_double_const(x, status), oskar_mem_double_const(y, status), uv_filter_min, uv_filter_max, inv_wavelength, frac_bandwidth, time_avg, gha0, dec0, oskar_mem_double2(vis, status)); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; return; } } oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else *status = OSKAR_ERR_BAD_LOCATION; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/convert/oskar_convert_ecef_to_station_uvw.h
/* * Copyright (c) 2013-2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_CONVERT_ECEF_TO_STATION_UVW_H_ #define OSKAR_CONVERT_ECEF_TO_STATION_UVW_H_ /** * @file oskar_convert_ecef_to_station_uvw.h */ #include <oskar_global.h> #include <mem/oskar_mem.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Transforms station (x,y,z) coordinates to (u,v,w) coordinates * (single precision). * * @details * Given the hour angle and declination of the phase tracking centre, this * function transforms the station (x,y,z) coordinates to (u,v,w) coordinates. * * @param[in] num_stations The size of the station coordinate arrays. * @param[in] x Input station x coordinates (ECEF or related frame). * @param[in] y Input station y coordinates (ECEF or related frame). * @param[in] z Input station z coordinates (ECEF or related frame). * @param[in] ha0_rad The Hour Angle of the phase centre, in radians. * @param[in] dec0_rad The Declination of the phase centre, in radians. * @param[out] u Output station u coordinates. * @param[out] v Output station v coordinates. * @param[out] w Output station w coordinates. */ OSKAR_EXPORT void oskar_convert_ecef_to_station_uvw_f(int num_stations, const float* x, const float* y, const float* z, double ha0_rad, double dec0_rad, float* u, float* v, float* w); /** * @brief * Transforms station (x,y,z) coordinates to (u,v,w) coordinates * (double precision). * * @details * Given the hour angle and declination of the phase tracking centre, this * function transforms the station (x,y,z) coordinates to (u,v,w) coordinates. * * @param[in] num_stations The size of the station coordinate arrays. * @param[in] x Input station x coordinates (ECEF or related frame). * @param[in] y Input station y coordinates (ECEF or related frame). * @param[in] z Input station z coordinates (ECEF or related frame). * @param[in] ha0_rad The Hour Angle of the phase centre, in radians. * @param[in] dec0_rad The Declination of the phase centre, in radians. * @param[out] u Output station u coordinates. * @param[out] v Output station v coordinates. * @param[out] w Output station w coordinates. */ OSKAR_EXPORT void oskar_convert_ecef_to_station_uvw_d(int num_stations, const double* x, const double* y, const double* z, double ha0_rad, double dec0_rad, double* u, double* v, double* w); /** * @brief * Evaluates the station (u,v,w) coordinates. * * @details * This function evaluates the station (u,v,w) coordinates using the * station (x,y,z) coordinates, the supplied phase tracking centre, and * the Greenwich Apparent Sidereal Time. * * @param[in] num_stations The size of the station coordinate arrays. * @param[in] x Input station x coordinates (ECEF or related frame). * @param[in] y Input station y coordinates (ECEF or related frame). * @param[in] z Input station z coordinates (ECEF or related frame). * @param[in] ra0_rad The Right Ascension of the phase centre, in radians. * @param[in] dec0_rad The Declination of the phase centre, in radians. * @param[in] gast The Greenwich Apparent Sidereal Time, in radians. * @param[out] u Output station u coordinates. * @param[out] v Output station v coordinates. * @param[out] w Output station w coordinates. * @param[in,out] status Status return code. */ OSKAR_EXPORT void oskar_convert_ecef_to_station_uvw(int num_stations, const oskar_Mem* x, const oskar_Mem* y, const oskar_Mem* z, double ra0_rad, double dec0_rad, double gast, oskar_Mem* u, oskar_Mem* v, oskar_Mem* w, int* status); #ifdef __cplusplus } #endif #endif /* OSKAR_CONVERT_ECEF_TO_STATION_UVW_H_ */
davepallot/OSKAR
oskar/beam_pattern/src/private_beam_pattern_generate_coordinates.c
<gh_stars>1-10 /* * Copyright (c) 2013-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "beam_pattern/private_beam_pattern.h" #include "beam_pattern/private_beam_pattern_generate_coordinates.h" #include "convert/oskar_convert_healpix_ring_to_theta_phi.h" #include "convert/oskar_convert_theta_phi_to_enu_directions.h" #include "convert/oskar_convert_lon_lat_to_relative_directions.h" #include "math/oskar_evaluate_image_lmn_grid.h" #include "utility/oskar_getline.h" #include "utility/oskar_string_to_array.h" #include "math/oskar_cmath.h" #include <stdio.h> #include <stddef.h> static void load_coords(oskar_Mem* lon, oskar_Mem* lat, const char* filename, int* status); #ifdef __cplusplus extern "C" { #endif void oskar_beam_pattern_generate_coordinates(oskar_BeamPattern* h, int beam_coord_type, int* status) { size_t num_pixels = 0; int nside = 0; /* Check if safe to proceed. */ if (*status) return; /* If memory is already allocated, do nothing. */ if (h->x) return; /* Calculate number of pixels if possible. */ if (h->coord_grid_type == 'B') /* Beam image */ { num_pixels = h->width * h->height; } else if (h->coord_grid_type == 'H') /* Healpix */ { nside = h->nside; num_pixels = 12 * nside * nside; } else if (h->coord_grid_type == 'S') /* Sky model */ num_pixels = 0; else { *status = OSKAR_ERR_INVALID_ARGUMENT; return; } /* Create output arrays. */ h->x = oskar_mem_create(h->prec, OSKAR_CPU, num_pixels, status); h->y = oskar_mem_create(h->prec, OSKAR_CPU, num_pixels, status); h->z = oskar_mem_create(h->prec, OSKAR_CPU, num_pixels, status); /* Get equatorial or horizon coordinates. */ if (h->coord_frame_type == 'E') { /* * Equatorial coordinates. */ switch (h->coord_grid_type) { case 'B': /* Beam image */ { oskar_evaluate_image_lmn_grid(h->width, h->height, h->fov_deg[0]*(M_PI/180.0), h->fov_deg[1]*(M_PI/180.0), 1, h->x, h->y, h->z, status); break; } case 'H': /* Healpix */ { int num_points, type, i; double ra0 = 0.0, dec0 = 0.0; oskar_Mem *theta, *phi; /* Generate theta and phi from nside. */ num_points = 12 * nside * nside; type = oskar_mem_type(h->x); theta = oskar_mem_create(type, OSKAR_CPU, num_points, status); phi = oskar_mem_create(type, OSKAR_CPU, num_points, status); oskar_convert_healpix_ring_to_theta_phi(nside, theta, phi, status); /* Convert theta from polar angle to elevation. */ if (type == OSKAR_DOUBLE) { double* theta_ = oskar_mem_double(theta, status); for (i = 0; i < num_points; ++i) theta_[i] = 90.0 - theta_[i]; } else if (type == OSKAR_SINGLE) { float* theta_ = oskar_mem_float(theta, status); for (i = 0; i < num_points; ++i) theta_[i] = 90.0f - theta_[i]; } else { *status = OSKAR_ERR_BAD_DATA_TYPE; } /* Evaluate beam phase centre coordinates in equatorial frame. */ if (beam_coord_type == OSKAR_SPHERICAL_TYPE_EQUATORIAL) { ra0 = oskar_telescope_phase_centre_ra_rad(h->tel); dec0 = oskar_telescope_phase_centre_dec_rad(h->tel); } else if (beam_coord_type == OSKAR_SPHERICAL_TYPE_AZEL) { /* TODO convert from az0, el0 to ra0, dec0 */ *status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE; } else { *status = OSKAR_ERR_INVALID_ARGUMENT; } /* Convert equatorial angles to direction cosines in the frame * of the beam phase centre. */ oskar_convert_lon_lat_to_relative_directions(num_points, phi, theta, ra0, dec0, h->x, h->y, h->z, status); /* Free memory. */ oskar_mem_free(theta, status); oskar_mem_free(phi, status); break; } case 'S': /* Sky model */ { oskar_Mem *ra, *dec; int type = 0, num_points = 0; type = oskar_mem_type(h->x); ra = oskar_mem_create(type, OSKAR_CPU, 0, status); dec = oskar_mem_create(type, OSKAR_CPU, 0, status); load_coords(ra, dec, h->sky_model_file, status); num_points = (int) oskar_mem_length(ra); oskar_mem_realloc(h->x, num_points, status); oskar_mem_realloc(h->y, num_points, status); oskar_mem_realloc(h->z, num_points, status); oskar_convert_lon_lat_to_relative_directions( num_points, ra, dec, oskar_telescope_phase_centre_ra_rad(h->tel), oskar_telescope_phase_centre_dec_rad(h->tel), h->x, h->y, h->z, status); oskar_mem_free(ra, status); oskar_mem_free(dec, status); break; } default: *status = OSKAR_ERR_INVALID_ARGUMENT; break; }; /* Set the return values. */ h->coord_type = OSKAR_RELATIVE_DIRECTIONS; h->lon0 = oskar_telescope_phase_centre_ra_rad(h->tel); h->lat0 = oskar_telescope_phase_centre_dec_rad(h->tel); } else if (h->coord_frame_type == 'H') { /* * Horizon coordinates. */ switch (h->coord_grid_type) { case 'B': /* Beam image */ { /* NOTE: This is for an all-sky image centred on the zenith. */ oskar_evaluate_image_lmn_grid(h->width, h->height, M_PI, M_PI, 1, h->x, h->y, h->z, status); break; } case 'H': /* Healpix */ { int num_points, type; oskar_Mem *theta, *phi; num_points = 12 * nside * nside; type = oskar_mem_type(h->x); theta = oskar_mem_create(type, OSKAR_CPU, num_points, status); phi = oskar_mem_create(type, OSKAR_CPU, num_points, status); oskar_convert_healpix_ring_to_theta_phi(nside, theta, phi, status); oskar_convert_theta_phi_to_enu_directions(num_points, theta, phi, h->x, h->y, h->z, status); oskar_mem_free(theta, status); oskar_mem_free(phi, status); break; } default: *status = OSKAR_ERR_INVALID_ARGUMENT; break; }; /* Set the return values. */ h->coord_type = OSKAR_ENU_DIRECTIONS; h->lon0 = 0.0; h->lat0 = M_PI / 2.0; } else { *status = OSKAR_ERR_INVALID_ARGUMENT; } /* Set the number of pixels. */ h->num_pixels = (int) oskar_mem_length(h->x); } static void load_coords(oskar_Mem* lon, oskar_Mem* lat, const char* filename, int* status) { int type = 0; FILE* file; char* line = 0; size_t n = 0, bufsize = 0; if (*status) return; /* Set initial size of coordinate arrays. */ type = oskar_mem_precision(lon); oskar_mem_realloc(lon, 100, status); oskar_mem_realloc(lat, 100, status); /* Open the file. */ file = fopen(filename, "r"); if (!file) { *status = OSKAR_ERR_FILE_IO; return; } /* Loop over lines in file. */ while (oskar_getline(&line, &bufsize, file) != OSKAR_ERR_EOF) { /* Set defaults. */ /* Longitude, latitude. */ double par[] = {0., 0.}; size_t num_param = sizeof(par) / sizeof(double); size_t num_required = 2, num_read = 0; /* Load coordinates. */ num_read = oskar_string_to_array_d(line, num_param, par); if (num_read < num_required) continue; /* Ensure enough space in arrays. */ if (oskar_mem_length(lon) <= n) { oskar_mem_realloc(lon, n + 100, status); oskar_mem_realloc(lat, n + 100, status); if (*status) break; } /* Store the coordinates. */ if (type == OSKAR_DOUBLE) { oskar_mem_double(lon, status)[n] = par[0] * M_PI/180.0; oskar_mem_double(lat, status)[n] = par[1] * M_PI/180.0; } else { oskar_mem_float(lon, status)[n] = par[0] * M_PI/180.0; oskar_mem_float(lat, status)[n] = par[1] * M_PI/180.0; } ++n; } /* Resize output arrays to final size. */ oskar_mem_realloc(lon, n, status); oskar_mem_realloc(lat, n, status); fclose(file); free(line); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/imager/src/private_imager_update_plane_fft.c
<filename>oskar/imager/src/private_imager_update_plane_fft.c /* * Copyright (c) 2016-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "imager/private_imager.h" #include "imager/oskar_imager.h" #include "imager/private_imager_update_plane_fft.h" #include "imager/oskar_grid_simple.h" #ifdef __cplusplus extern "C" { #endif void oskar_imager_update_plane_fft(oskar_Imager* h, size_t num_vis, const oskar_Mem* uu, const oskar_Mem* vv, const oskar_Mem* amps, const oskar_Mem* weight, oskar_Mem* plane, double* plane_norm, size_t* num_skipped, int* status) { int grid_size; size_t num_cells; if (*status) return; grid_size = oskar_imager_plane_size(h); num_cells = grid_size * grid_size; if (oskar_mem_precision(plane) != h->imager_prec) *status = OSKAR_ERR_TYPE_MISMATCH; if (oskar_mem_length(plane) < num_cells) oskar_mem_realloc(plane, num_cells, status); if (*status) return; if (h->imager_prec == OSKAR_DOUBLE) oskar_grid_simple_d(h->support, h->oversample, oskar_mem_double_const(h->conv_func, status), num_vis, oskar_mem_double_const(uu, status), oskar_mem_double_const(vv, status), oskar_mem_double_const(amps, status), oskar_mem_double_const(weight, status), h->cellsize_rad, grid_size, num_skipped, plane_norm, oskar_mem_double(plane, status)); else oskar_grid_simple_f(h->support, h->oversample, oskar_mem_float_const(h->conv_func, status), num_vis, oskar_mem_float_const(uu, status), oskar_mem_float_const(vv, status), oskar_mem_float_const(amps, status), oskar_mem_float_const(weight, status), (float) (h->cellsize_rad), grid_size, num_skipped, plane_norm, oskar_mem_float(plane, status)); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/mem/src/oskar_mem_read_healpix_fits.c
/* * Copyright (c) 2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "mem/oskar_mem.h" #include <fitsio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif oskar_Mem* oskar_mem_read_healpix_fits(const char* filename, int healpix_hdu_index, int* nside, char* ordering, char* coordsys, char** brightness_units, int* status) { int col_index = 1; /* Read the first column. */ int i_healpix = 0, i_hdu = 0, len, num_cols = 0, num_hdu = 0; int type_fits = 0, type_oskar = 0, status1 = 0; long repeat = 0, width = 0, num_rows = 0, num_pixels = 0; char card1[FLEN_CARD], card2[FLEN_CARD]; fitsfile* fptr = 0; oskar_Mem* data = 0; /* Check if safe to proceed. */ if (*status) return 0; /* Open the FITS file. */ fits_open_file(&fptr, filename, READONLY, status); if (*status || !fptr) { *status = OSKAR_ERR_FILE_IO; return 0; } /* Get number of HDUs in file. */ fits_get_num_hdus(fptr, &num_hdu, status); /* Loop over extensions until the right HEALPix binary table is found. */ for (i_hdu = 2; i_hdu <= num_hdu; ++i_hdu) { int hdutype = 0; fits_movabs_hdu(fptr, i_hdu, &hdutype, status); if (hdutype != BINARY_TBL) continue; /* Look for PIXTYPE keyword. */ fits_read_key(fptr, TSTRING, "XTENSION", card1, NULL, status); fits_read_key(fptr, TSTRING, "PIXTYPE", card2, NULL, status); if (!strcmp(card1, "BINTABLE") && !strcmp(card2, "HEALPIX")) { if (i_healpix == healpix_hdu_index) break; else i_healpix++; } } /* Check if we exhausted the HDU list without finding anything. */ if (i_hdu > num_hdu) { fits_close_file(fptr, status); *status = OSKAR_ERR_FILE_IO; return 0; } /* Get number of rows and columns in binary table. */ fits_get_num_rows(fptr, &num_rows, status); fits_get_num_cols(fptr, &num_cols, status); /* Read type of the first column. */ fits_get_coltype(fptr, col_index, &type_fits, &repeat, &width, status); type_oskar = (type_fits == TDOUBLE) ? OSKAR_DOUBLE : OSKAR_SINGLE; /* Number of pixels = number of rows x number of pixels in each row */ num_pixels = num_rows * repeat; /* Get HEALPix NSIDE parameter. */ fits_read_key(fptr, TINT, "NSIDE", nside, NULL, status); if (num_pixels != 12 * (*nside) * (*nside)) { fits_close_file(fptr, status); *status = OSKAR_ERR_DIMENSION_MISMATCH; return 0; } /* Get HEALPix ordering scheme. */ card1[0] = 0; fits_read_key(fptr, TSTRING, "ORDERING", card1, NULL, status); *ordering = card1[0]; /* Get coordinate system. */ card1[0] = 0; fits_read_key(fptr, TSTRING, "COORDSYS", card1, NULL, status); *coordsys = card1[0]; /* Get brightness units if present. */ card1[0] = 0; status1 = 0; fits_read_key(fptr, TSTRING, "TUNIT1", card1, NULL, &status1); len = (int) strlen(card1); if (!status1 && len > 0) { *brightness_units = (char*) realloc (*brightness_units, len + 1); strcpy(*brightness_units, card1); } /* Read the FITS binary table into memory, and close the file. */ data = oskar_mem_create(type_oskar, OSKAR_CPU, num_pixels, status); fits_read_col(fptr, type_fits, col_index, 1, 1, num_pixels, 0, oskar_mem_void(data), 0, status); fits_close_file(fptr, status); return data; } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/vis/src/oskar_vis_block_write_ms.c
<gh_stars>1-10 /* * Copyright (c) 2015-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ms/oskar_measurement_set.h" #include "vis/oskar_vis_block.h" #include "vis/oskar_vis_header.h" #include "math/oskar_cmath.h" #ifdef __cplusplus extern "C" { #endif #define D2R (M_PI / 180.0) void oskar_vis_block_write_ms(const oskar_VisBlock* blk, const oskar_VisHeader* header, oskar_MeasurementSet* ms, int* status) { const oskar_Mem *in_acorr, *in_xcorr, *in_uu, *in_vv, *in_ww; oskar_Mem *temp_vis = 0, *temp_uu = 0, *temp_vv = 0, *temp_ww = 0; double exposure_sec, interval_sec, t_start_mjd, t_start_sec; double ra_rad, dec_rad, freq_start_hz; unsigned int a1, a2, num_baseln_in, num_baseln_out, num_channels; unsigned int num_pols_in, num_pols_out, num_stations, num_times, b, c, t; unsigned int i, i_out, prec, start_time_index, start_chan_index; unsigned int have_autocorr, have_crosscorr; const void *xcorr, *acorr; void* out; /* Check if safe to proceed. */ if (*status) return; /* Pull data from visibility structures. */ num_pols_out = oskar_ms_num_pols(ms); num_pols_in = oskar_vis_block_num_pols(blk); num_stations = oskar_vis_block_num_stations(blk); num_baseln_in = oskar_vis_block_num_baselines(blk); num_channels = oskar_vis_block_num_channels(blk); num_times = oskar_vis_block_num_times(blk); in_acorr = oskar_vis_block_auto_correlations_const(blk); in_xcorr = oskar_vis_block_cross_correlations_const(blk); in_uu = oskar_vis_block_baseline_uu_metres_const(blk); in_vv = oskar_vis_block_baseline_vv_metres_const(blk); in_ww = oskar_vis_block_baseline_ww_metres_const(blk); have_autocorr = oskar_vis_block_has_auto_correlations(blk); have_crosscorr = oskar_vis_block_has_cross_correlations(blk); start_time_index = oskar_vis_block_start_time_index(blk); start_chan_index = oskar_vis_block_start_channel_index(blk); ra_rad = oskar_vis_header_phase_centre_ra_deg(header) * D2R; dec_rad = oskar_vis_header_phase_centre_dec_deg(header) * D2R; exposure_sec = oskar_vis_header_time_average_sec(header); interval_sec = oskar_vis_header_time_inc_sec(header); t_start_mjd = oskar_vis_header_time_start_mjd_utc(header); freq_start_hz = oskar_vis_header_freq_start_hz(header); prec = oskar_mem_precision(in_xcorr); t_start_sec = t_start_mjd * 86400.0; /* Check that there is something to write. */ if (!have_autocorr && !have_crosscorr) return; /* Get number of output baselines. */ num_baseln_out = num_baseln_in; if (have_autocorr) num_baseln_out += num_stations; /* Check polarisation dimension consistency: * num_pols_in can be less than num_pols_out, but not vice-versa. */ if (num_pols_in > num_pols_out) { *status = OSKAR_ERR_DIMENSION_MISMATCH; return; } /* Check the dimensions match. */ if (oskar_ms_num_pols(ms) != num_pols_out || oskar_ms_num_stations(ms) != num_stations) { *status = OSKAR_ERR_DIMENSION_MISMATCH; return; } /* Check the reference frequencies match. */ if (fabs(oskar_ms_freq_start_hz(ms) - freq_start_hz) > 1e-10) { *status = OSKAR_ERR_VALUE_MISMATCH; return; } /* Check the phase centres are the same. */ if (fabs(oskar_ms_phase_centre_ra_rad(ms) - ra_rad) > 1e-10 || fabs(oskar_ms_phase_centre_dec_rad(ms) - dec_rad) > 1e-10) { *status = OSKAR_ERR_VALUE_MISMATCH; return; } /* Add visibilities and u,v,w coordinates. */ temp_vis = oskar_mem_create(prec | OSKAR_COMPLEX, OSKAR_CPU, num_baseln_out * num_channels * num_pols_out, status); temp_uu = oskar_mem_create(prec, OSKAR_CPU, num_baseln_out, status); temp_vv = oskar_mem_create(prec, OSKAR_CPU, num_baseln_out, status); temp_ww = oskar_mem_create(prec, OSKAR_CPU, num_baseln_out, status); xcorr = oskar_mem_void_const(in_xcorr); acorr = oskar_mem_void_const(in_acorr); out = oskar_mem_void(temp_vis); if (prec == OSKAR_DOUBLE) { const double *uu_in, *vv_in, *ww_in; double *uu_out, *vv_out, *ww_out; uu_in = oskar_mem_double_const(in_uu, status); vv_in = oskar_mem_double_const(in_vv, status); ww_in = oskar_mem_double_const(in_ww, status); uu_out = oskar_mem_double(temp_uu, status); vv_out = oskar_mem_double(temp_vv, status); ww_out = oskar_mem_double(temp_ww, status); for (t = 0; t < num_times; ++t) { /* Construct the baseline coordinates for the given time. */ unsigned int start_row = (start_time_index + t) * num_baseln_out; for (a1 = 0, b = 0, i_out = 0; a1 < num_stations; ++a1) { if (have_autocorr) { uu_out[i_out] = 0.0; vv_out[i_out] = 0.0; ww_out[i_out] = 0.0; ++i_out; } if (have_crosscorr) { for (a2 = a1 + 1; a2 < num_stations; ++a2, ++b, ++i_out) { i = num_baseln_in * t + b; uu_out[i_out] = uu_in[i]; vv_out[i_out] = vv_in[i]; ww_out[i_out] = ww_in[i]; } } } for (c = 0, i_out = 0; c < num_channels; ++c) { /* Construct amplitude data for the given time and channel. */ if (num_pols_in == 4) { for (a1 = 0, b = 0; a1 < num_stations; ++a1) { if (have_autocorr) { i = num_stations * (t * num_channels + c) + a1; ((double4c*)out)[i_out++] = ((const double4c*)acorr)[i]; } if (have_crosscorr) { for (a2 = a1 + 1; a2 < num_stations; ++b, ++a2) { i = num_baseln_in * (t * num_channels + c) + b; ((double4c*)out)[i_out++] = ((const double4c*)xcorr)[i]; } } } } else if (num_pols_in == 1 && num_pols_out == 1) { for (a1 = 0, b = 0; a1 < num_stations; ++a1) { if (have_autocorr) { i = num_stations * (t * num_channels + c) + a1; ((double2*)out)[i_out++] = ((const double2*)acorr)[i]; } if (have_crosscorr) { for (a2 = a1 + 1; a2 < num_stations; ++b, ++a2) { i = num_baseln_in * (t * num_channels + c) + b; ((double2*)out)[i_out++] = ((const double2*)xcorr)[i]; } } } } else { double2 vis_amp, *out_; out_ = (double2*)out; for (a1 = 0, b = 0; a1 < num_stations; ++a1) { if (have_autocorr) { i = num_stations * (t * num_channels + c) + a1; vis_amp = ((const double2*)acorr)[i]; out_[i_out + 0] = vis_amp; /* XX */ out_[i_out + 1].x = 0.0; /* XY */ out_[i_out + 1].y = 0.0; /* XY */ out_[i_out + 2].x = 0.0; /* YX */ out_[i_out + 2].y = 0.0; /* YX */ out_[i_out + 3] = vis_amp; /* YY */ i_out += 4; } if (have_crosscorr) { for (a2 = a1 + 1; a2 < num_stations; ++b, ++a2) { i = num_baseln_in * (t * num_channels + c) + b; vis_amp = ((const double2*)xcorr)[i]; out_[i_out + 0] = vis_amp; /* XX */ out_[i_out + 1].x = 0.0; /* XY */ out_[i_out + 1].y = 0.0; /* XY */ out_[i_out + 2].x = 0.0; /* YX */ out_[i_out + 2].y = 0.0; /* YX */ out_[i_out + 3] = vis_amp; /* YY */ i_out += 4; } } } } } oskar_ms_write_coords_d(ms, start_row, num_baseln_out, uu_out, vv_out, ww_out, exposure_sec, interval_sec, (start_time_index + t + 0.5) * interval_sec + t_start_sec); oskar_ms_write_vis_d(ms, start_row, start_chan_index, num_channels, num_baseln_out, (const double*)out); } } else if (prec == OSKAR_SINGLE) { const float *uu_in, *vv_in, *ww_in; float *uu_out, *vv_out, *ww_out; uu_in = oskar_mem_float_const(in_uu, status); vv_in = oskar_mem_float_const(in_vv, status); ww_in = oskar_mem_float_const(in_ww, status); uu_out = oskar_mem_float(temp_uu, status); vv_out = oskar_mem_float(temp_vv, status); ww_out = oskar_mem_float(temp_ww, status); for (t = 0; t < num_times; ++t) { /* Construct the baseline coordinates for the given time. */ unsigned int start_row = (start_time_index + t) * num_baseln_out; for (a1 = 0, b = 0, i_out = 0; a1 < num_stations; ++a1) { if (have_autocorr) { uu_out[i_out] = 0.0; vv_out[i_out] = 0.0; ww_out[i_out] = 0.0; ++i_out; } if (have_crosscorr) { for (a2 = a1 + 1; a2 < num_stations; ++a2, ++b, ++i_out) { i = num_baseln_in * t + b; uu_out[i_out] = uu_in[i]; vv_out[i_out] = vv_in[i]; ww_out[i_out] = ww_in[i]; } } } for (c = 0, i_out = 0; c < num_channels; ++c) { /* Construct amplitude data for the given time and channel. */ if (num_pols_in == 4) { for (a1 = 0, b = 0; a1 < num_stations; ++a1) { if (have_autocorr) { i = num_stations * (t * num_channels + c) + a1; ((float4c*)out)[i_out++] = ((const float4c*)acorr)[i]; } if (have_crosscorr) { for (a2 = a1 + 1; a2 < num_stations; ++b, ++a2) { i = num_baseln_in * (t * num_channels + c) + b; ((float4c*)out)[i_out++] = ((const float4c*)xcorr)[i]; } } } } else if (num_pols_in == 1 && num_pols_out == 1) { for (a1 = 0, b = 0; a1 < num_stations; ++a1) { if (have_autocorr) { i = num_stations * (t * num_channels + c) + a1; ((float2*)out)[i_out++] = ((const float2*)acorr)[i]; } if (have_crosscorr) { for (a2 = a1 + 1; a2 < num_stations; ++b, ++a2) { i = num_baseln_in * (t * num_channels + c) + b; ((float2*)out)[i_out++] = ((const float2*)xcorr)[i]; } } } } else { float2 vis_amp, *out_; out_ = (float2*)out; for (a1 = 0, b = 0; a1 < num_stations; ++a1) { if (have_autocorr) { i = num_stations * (t * num_channels + c) + a1; vis_amp = ((const float2*)acorr)[i]; out_[i_out + 0] = vis_amp; /* XX */ out_[i_out + 1].x = 0.0; /* XY */ out_[i_out + 1].y = 0.0; /* XY */ out_[i_out + 2].x = 0.0; /* YX */ out_[i_out + 2].y = 0.0; /* YX */ out_[i_out + 3] = vis_amp; /* YY */ i_out += 4; } if (have_crosscorr) { for (a2 = a1 + 1; a2 < num_stations; ++b, ++a2) { i = num_baseln_in * (t * num_channels + c) + b; vis_amp = ((const float2*)xcorr)[i]; out_[i_out + 0] = vis_amp; /* XX */ out_[i_out + 1].x = 0.0; /* XY */ out_[i_out + 1].y = 0.0; /* XY */ out_[i_out + 2].x = 0.0; /* YX */ out_[i_out + 2].y = 0.0; /* YX */ out_[i_out + 3] = vis_amp; /* YY */ i_out += 4; } } } } } oskar_ms_write_coords_f(ms, start_row, num_baseln_out, uu_out, vv_out, ww_out, exposure_sec, interval_sec, (start_time_index + t + 0.5) * interval_sec + t_start_sec); oskar_ms_write_vis_f(ms, start_row, start_chan_index, num_channels, num_baseln_out, (const float*)out); } } else { *status = OSKAR_ERR_BAD_DATA_TYPE; } /* Cleanup. */ oskar_mem_free(temp_vis, status); oskar_mem_free(temp_uu, status); oskar_mem_free(temp_vv, status); oskar_mem_free(temp_ww, status); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/correlate/src/oskar_evaluate_cross_power.c
<filename>oskar/correlate/src/oskar_evaluate_cross_power.c<gh_stars>1-10 /* * Copyright (c) 2014-2018, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "correlate/oskar_evaluate_cross_power.h" #include "correlate/oskar_evaluate_cross_power_cuda.h" #include "correlate/oskar_evaluate_cross_power_omp.h" #include "utility/oskar_device_utils.h" #ifdef __cplusplus extern "C" { #endif /* Wrapper. */ void oskar_evaluate_cross_power(int num_sources, int num_stations, const oskar_Mem* jones, oskar_Mem* out, int *status) { int type, location; /* Check if safe to proceed. */ if (*status) return; /* Check type and location. */ type = oskar_mem_type(jones); location = oskar_mem_location(jones); if (type != oskar_mem_type(out)) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } if (location != oskar_mem_location(out)) { *status = OSKAR_ERR_LOCATION_MISMATCH; return; } /* Switch on type and location combination. */ if (location == OSKAR_CPU) { switch (type) { case OSKAR_SINGLE_COMPLEX_MATRIX: oskar_evaluate_cross_power_omp_f(num_sources, num_stations, oskar_mem_float4c_const(jones, status), oskar_mem_float4c(out, status)); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: oskar_evaluate_cross_power_omp_d(num_sources, num_stations, oskar_mem_double4c_const(jones, status), oskar_mem_double4c(out, status)); break; case OSKAR_SINGLE_COMPLEX: oskar_evaluate_cross_power_scalar_omp_f(num_sources, num_stations, oskar_mem_float2_const(jones, status), oskar_mem_float2(out, status)); break; case OSKAR_DOUBLE_COMPLEX: oskar_evaluate_cross_power_scalar_omp_d(num_sources, num_stations, oskar_mem_double2_const(jones, status), oskar_mem_double2(out, status)); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; return; } } else if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA switch (type) { case OSKAR_SINGLE_COMPLEX_MATRIX: oskar_evaluate_cross_power_cuda_f(num_sources, num_stations, oskar_mem_float4c_const(jones, status), oskar_mem_float4c(out, status)); break; case OSKAR_DOUBLE_COMPLEX_MATRIX: oskar_evaluate_cross_power_cuda_d(num_sources, num_stations, oskar_mem_double4c_const(jones, status), oskar_mem_double4c(out, status)); break; case OSKAR_SINGLE_COMPLEX: oskar_evaluate_cross_power_scalar_cuda_f(num_sources, num_stations, oskar_mem_float2_const(jones, status), oskar_mem_float2(out, status)); break; case OSKAR_DOUBLE_COMPLEX: oskar_evaluate_cross_power_scalar_cuda_d(num_sources, num_stations, oskar_mem_double2_const(jones, status), oskar_mem_double2(out, status)); break; default: *status = OSKAR_ERR_BAD_DATA_TYPE; return; } oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/interferometer/src/oskar_evaluate_jones_K.c
/* * Copyright (c) 2011-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "interferometer/oskar_evaluate_jones_K.h" #include "interferometer/oskar_evaluate_jones_K_cuda.h" #include "utility/oskar_device_utils.h" #include "math/oskar_cmath.h" #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_evaluate_jones_K_f(float2* jones, int num_sources, const float* l, const float* m, const float* n, int num_stations, const float* u, const float* v, const float* w, float wavenumber, const float* source_filter, float source_filter_min, float source_filter_max) { int a, s; /* Loop over stations. */ for (a = 0; a < num_stations; ++a) { float us, vs, ws; float2* station_ptr; /* Get the station data. */ station_ptr = &jones[a * num_sources]; us = wavenumber * u[a]; vs = wavenumber * v[a]; ws = wavenumber * w[a]; /* Loop over sources. */ for (s = 0; s < num_sources; ++s) { float phase; float2 weight; /* Calculate the source phase. */ if (source_filter[s] > source_filter_min && source_filter[s] <= source_filter_max) { phase = us * l[s] + vs * m[s] + ws * (n[s] - 1.0f); /* Double precision versions are converted to sincos() by the * compiler, so they're faster and more accurate * than sinf(), cosf(). */ weight.x = cos(phase); weight.y = sin(phase); } else { weight.x = 0.0f; weight.y = 0.0f; } /* Store the result. */ station_ptr[s] = weight; } } } /* Double precision. */ void oskar_evaluate_jones_K_d(double2* jones, int num_sources, const double* l, const double* m, const double* n, int num_stations, const double* u, const double* v, const double* w, double wavenumber, const double* source_filter, double source_filter_min, double source_filter_max) { int a, s; /* Loop over stations. */ for (a = 0; a < num_stations; ++a) { double us, vs, ws; double2* station_ptr; /* Get the station data. */ station_ptr = &jones[a * num_sources]; us = wavenumber * u[a]; vs = wavenumber * v[a]; ws = wavenumber * w[a]; /* Loop over sources. */ for (s = 0; s < num_sources; ++s) { double phase; double2 weight; /* Calculate the source phase. */ if (source_filter[s] > source_filter_min && source_filter[s] <= source_filter_max) { phase = us * l[s] + vs * m[s] + ws * (n[s] - 1.0); weight.x = cos(phase); weight.y = sin(phase); } else { weight.x = 0.0; weight.y = 0.0; } /* Store the result. */ station_ptr[s] = weight; } } } /* Wrapper. */ void oskar_evaluate_jones_K(oskar_Jones* K, int num_sources, const oskar_Mem* l, const oskar_Mem* m, const oskar_Mem* n, const oskar_Mem* u, const oskar_Mem* v, const oskar_Mem* w, double frequency_hz, const oskar_Mem* source_filter, double source_filter_min, double source_filter_max, int* status) { int num_stations, jones_type, base_type, location; double wavenumber; /* Check if safe to proceed. */ if (*status) return; /* Get the Jones matrix block meta-data. */ jones_type = oskar_jones_type(K); base_type = oskar_type_precision(jones_type); location = oskar_jones_mem_location(K); num_stations = oskar_jones_num_stations(K); wavenumber = 2.0 * M_PI * frequency_hz / 299792458.0; /* Check that the data is in the right location. */ if (oskar_mem_location(l) != location || oskar_mem_location(m) != location || oskar_mem_location(n) != location || oskar_mem_location(source_filter) != location || oskar_mem_location(u) != location || oskar_mem_location(v) != location || oskar_mem_location(w) != location) { *status = OSKAR_ERR_LOCATION_MISMATCH; return; } /* Check that the data are of the right type. */ if (!oskar_type_is_complex(jones_type) || oskar_type_is_matrix(jones_type)) { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } if (base_type != oskar_mem_type(l) || base_type != oskar_mem_type(m) || base_type != oskar_mem_type(n) || base_type != oskar_mem_type(u) || base_type != oskar_mem_type(v) || base_type != oskar_mem_type(w) || base_type != oskar_mem_type(source_filter)) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } /* Evaluate Jones matrices. */ if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA if (jones_type == OSKAR_SINGLE_COMPLEX) { oskar_evaluate_jones_K_cuda_f(oskar_jones_float2(K, status), num_sources, oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), num_stations, oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), wavenumber, oskar_mem_float_const(source_filter, status), source_filter_min, source_filter_max); } else if (jones_type == OSKAR_DOUBLE_COMPLEX) { oskar_evaluate_jones_K_cuda_d(oskar_jones_double2(K, status), num_sources, oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), num_stations, oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), wavenumber, oskar_mem_double_const(source_filter, status), source_filter_min, source_filter_max); } oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location == OSKAR_CPU) { if (jones_type == OSKAR_SINGLE_COMPLEX) { oskar_evaluate_jones_K_f(oskar_jones_float2(K, status), num_sources, oskar_mem_float_const(l, status), oskar_mem_float_const(m, status), oskar_mem_float_const(n, status), num_stations, oskar_mem_float_const(u, status), oskar_mem_float_const(v, status), oskar_mem_float_const(w, status), wavenumber, oskar_mem_float_const(source_filter, status), source_filter_min, source_filter_max); } else if (jones_type == OSKAR_DOUBLE_COMPLEX) { oskar_evaluate_jones_K_d(oskar_jones_double2(K, status), num_sources, oskar_mem_double_const(l, status), oskar_mem_double_const(m, status), oskar_mem_double_const(n, status), num_stations, oskar_mem_double_const(u, status), oskar_mem_double_const(v, status), oskar_mem_double_const(w, status), wavenumber, oskar_mem_double_const(source_filter, status), source_filter_min, source_filter_max); } } } #ifdef __cplusplus } #endif
davepallot/OSKAR
apps/oskar_option_parser.h
/* * Copyright (c) 2012-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_OPTION_PARSER_H_ #define OSKAR_OPTION_PARSER_H_ /** * @file oskar_option_parser.h */ #include "extern/ezOptionParser/ezOptionParser.hpp" #include <vector> #include <string> #include <cstdio> #include <cstdarg> namespace oskar { /** * @brief * Provides a command line parser for OSKAR applications. * * @details * Provides a command line parser for OSKAR applications. * * Note on the use symbols in option syntax: (the following are advised * in order to maintain consistency) * * [] = optional (e.g. $ foo [settings file] ) * <> = required (e.g. $ foo <file name> ) * ... = repeating elements, "and so on" * | = mutually exclusive * * TODO better handling of unexpected options. It would be useful if a warning * could be printed. */ class OptionParser : public ez::ezOptionParser { public: OptionParser(const char* title, const char* ver, const char* settings = "") { this->footer = "\n" "" + std::string(79, '-') + "\n" "OSKAR (version " + ver + ")\n" "Copyright (c) 2017, The University of Oxford.\n" "This program is free and without warranty.\n" "" + std::string(79, '-') + "\n"; set_version(ver, false); set_title(title); set_settings(settings); } virtual ~OptionParser() {} void add_example(const char* text) { this->example += " " + std::string(text) + "\n"; } // Wrapper to define flags with no arguments void add_flag(const char* flag1, const char* help, bool required = false, const char* flag2 = 0) { const char* defaults = ""; int expectedArgs = 0; char delim = 0; if (flag2) add(defaults, required, expectedArgs, delim, help, flag1, flag2); else add(defaults, required, expectedArgs, delim, help, flag1); } // Wrapper to define flags with arguments with default values. void add_flag(const char* flag1, const char* help, int expectedArgs, const char* defaults = "", bool required = false, const char* flag2 = 0) { char delim = 0; std::string strHelp = help; if (strlen(defaults) > 0 && expectedArgs == 1 && required == false) strHelp += " (default = " + std::string(defaults) + ")"; if (flag2) add(defaults, required, expectedArgs, delim, strHelp.c_str(), flag1, flag2); else add(defaults, required, expectedArgs, delim, strHelp.c_str(), flag1); } void add_optional(const char* name, const char* help = "") { // TODO Do something with the help field optional_.push_back(std::string(name)); optionalHelp_.push_back(std::string(help)); } void add_required(const char* name, const char* help = "") { // TODO Do something with the help field required_.push_back(std::string(name)); requiredHelp_.push_back(std::string(help)); } void add_settings_options() { add_required("settings file"); add_optional("key"); add_optional("value"); add_flag("--get", "Print key value in settings file."); add_flag("--set", "Set key value in settings file."); } bool check_options(int argc, char** argv) { add_flag("--help", "Display usage instructions and exit.", false); add_flag("--version", "Display the program name/version banner and exit.", false); add_flag("--settings", "Display settings and exit.", false); this->parse(argc, argv); if (is_set("--help")) { print_usage(); return false; } if (is_set("--version")) { std::cout << version_ << std::endl; return false; } if (is_set("--settings")) { std::cout << std::string(settings_) << std::endl; return false; } std::vector<std::string> badOpts; if (!gotRequired(badOpts)) { for (int i = 0; i < (int)badOpts.size(); ++i) { error("Missing required option: %s", badOpts[i].c_str()); return false; } } if (!gotExpected(badOpts)) { for (int i = 0; i < (int)badOpts.size(); ++i) { error("Got unexpected number of arguments for option: %s", badOpts[i].c_str()); return false; } } int minReqArgs = (int)required_.size(); if (num_args() < minReqArgs) { error("Expected >= %i input argument(s), %i given", minReqArgs, num_args()); return false; } return true; } void error(const char* format, ...) { std::cerr << "ERROR:\n"; std::cerr << " "; std::va_list args; va_start(args, format); std::vprintf(format, args); va_end(args); std::cerr << "\n\n"; this->print_usage(); } std::vector<std::string> get_args() const { std::vector<std::string> args; for (int i = 1; i < (int)firstArgs.size(); ++i) args.push_back(*this->firstArgs[i]); for (int i = 0; i < (int)lastArgs.size(); ++i) args.push_back(*this->lastArgs[i]); return args; } const char* get_arg(int i = 0) const { if ((int)firstArgs.size()-1 > i) return (*this->firstArgs[i+1]).c_str(); // Requested index is in the last argument set. else if (((int)firstArgs.size()-1 + (int)lastArgs.size()) > i) return (*this->lastArgs[i-((int)firstArgs.size()-1)]).c_str(); return 0; } std::vector<std::string> get_input_files(int minRequired = 2) const { std::vector<std::string> files; // Note: minRequired+1 because firstArg[0] == binary name bool filesFirst = ((int)this->firstArgs.size() >= minRequired+1) && ((int)this->lastArgs.size() == 0); if (filesFirst) { // Note: starts at 1 as index 0 == the binary name. for (int i = 1; i < (int)this->firstArgs.size(); ++i) files.push_back(*this->firstArgs[i]); } else { for (int i = 0; i < (int)this->lastArgs.size(); ++i) files.push_back(*this->lastArgs[i]); } return files; } void get_usage(std::string& usage) { this->syntax = this->title + " [OPTIONS]"; for (int i = 0; i < (int)required_.size(); ++i) this->syntax += " <" + required_[i] + ">"; for (int i = 0; i < (int)optional_.size(); ++i) this->syntax += " [" + optional_[i] + "]"; // TODO overload here rather than editing the library header...! ez::ezOptionParser::getUsage(usage); } int is_set(const char* option) { return isSet(option); } void print_usage() { std::string usage; this->get_usage(usage); std::cout << usage; } int num_args() const { return (((int)firstArgs.size()-1) + (int)lastArgs.size()); } void set_description(const char* description) { this->overview = description; } void set_settings(const char* text) { this->settings_ = text; } void set_title(const char* text) { this->title = text; } void set_version(const char* version, bool show = true) { if (show) this->version = version; version_ = version; } private: std::string title, version; std::vector<std::string> optional_; std::vector<std::string> optionalHelp_; std::vector<std::string> required_; std::vector<std::string> requiredHelp_; const char* settings_; const char* version_; }; } /* namespace oskar */ #endif /* OSKAR_OPTION_PARSER_H_ */
davepallot/OSKAR
oskar/sky/oskar_update_horizon_mask.h
/* * Copyright (c) 2013-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_UPDATE_HORIZON_MASK_H_ #define OSKAR_UPDATE_HORIZON_MASK_H_ /** * @file oskar_update_horizon_mask.h */ #include <oskar_global.h> #include <mem/oskar_mem.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Ensures source mask value is 1 if the source is visible. * * @details * This function sets the horizon mask to 1 if a source is * visible from a particular station. * * @param[in] num_sources The number of source positions. * @param[in] l Source l-direction cosines relative to phase centre. * @param[in] m Source m-direction cosines relative to phase centre. * @param[in] n Source n-direction cosines relative to phase centre. * @param[in] ha0_rad Local apparent hour angle of phase centre, in radians. * @param[in] dec0_rad Local apparent declination of phase centre, in radians. * @param[in] lat_rad The observer's geodetic latitude, in radians. * @param[in,out] mask The input and output mask vector. * @param[in,out] status Status return code. */ OSKAR_EXPORT void oskar_update_horizon_mask(int num_sources, const oskar_Mem* l, const oskar_Mem* m, const oskar_Mem* n, const double ha0_rad, const double dec0_rad, const double lat_rad, oskar_Mem* mask, int* status); #ifdef __cplusplus } #endif #endif /* OSKAR_UPDATE_HORIZON_MASK_H_ */
davepallot/OSKAR
oskar/interferometer/src/oskar_evaluate_jones_R.c
/* * Copyright (c) 2011-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include "interferometer/oskar_jones.h" #include "interferometer/oskar_evaluate_jones_R.h" #include "interferometer/oskar_evaluate_jones_R_cuda.h" #include "sky/oskar_parallactic_angle.h" #include "utility/oskar_device_utils.h" #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_evaluate_jones_R_f(float4c* jones, int num_sources, const float* ra_rad, const float* dec_rad, float latitude_rad, float lst_rad) { int i; float cos_lat, sin_lat; cos_lat = cos(latitude_rad); sin_lat = sin(latitude_rad); /* Loop over sources. */ for (i = 0; i < num_sources; ++i) { float ha, q, cos_q, sin_q; float4c J; /* Compute the source hour angle and parallactic angle. */ ha = lst_rad - ra_rad[i]; /* HA = LST - RA. */ q = oskar_parallactic_angle_f(ha, dec_rad[i], cos_lat, sin_lat); cos_q = cosf(q); sin_q = sinf(q); /* Construct the Jones matrix for the source. */ J.a.x = cos_q; J.b.x = -sin_q; J.c.x = sin_q; J.d.x = cos_q; J.a.y = 0.0f; J.b.y = 0.0f; J.c.y = 0.0f; J.d.y = 0.0f; /* Store the Jones matrix. */ jones[i] = J; } } /* Double precision. */ void oskar_evaluate_jones_R_d(double4c* jones, int num_sources, const double* ra_rad, const double* dec_rad, double latitude_rad, double lst_rad) { int i; double cos_lat, sin_lat; cos_lat = cos(latitude_rad); sin_lat = sin(latitude_rad); /* Loop over sources. */ for (i = 0; i < num_sources; ++i) { double ha, q, cos_q, sin_q; double4c J; /* Compute the source hour angle and parallactic angle. */ ha = lst_rad - ra_rad[i]; /* HA = LST - RA. */ q = oskar_parallactic_angle_d(ha, dec_rad[i], cos_lat, sin_lat); cos_q = cos(q); sin_q = sin(q); /* Construct the Jones matrix for the source. */ J.a.x = cos_q; J.b.x = -sin_q; J.c.x = sin_q; J.d.x = cos_q; J.a.y = 0.0; J.b.y = 0.0; J.c.y = 0.0; J.d.y = 0.0; /* Store the Jones matrix. */ jones[i] = J; } } /* Wrapper. */ void oskar_evaluate_jones_R(oskar_Jones* R, int num_sources, const oskar_Mem* ra_rad, const oskar_Mem* dec_rad, const oskar_Telescope* telescope, double gast, int* status) { int i, n, num_stations, jones_type, base_type, location; double latitude, lst; oskar_Mem *R_station; /* Check if safe to proceed. */ if (*status) return; /* Get the Jones matrix block meta-data. */ jones_type = oskar_jones_type(R); base_type = oskar_type_precision(jones_type); location = oskar_jones_mem_location(R); num_stations = oskar_jones_num_stations(R); n = (oskar_telescope_allow_station_beam_duplication(telescope) ? 1 : num_stations); /* Check that the data dimensions are OK. */ if (num_sources > (int)oskar_mem_length(ra_rad) || num_sources > (int)oskar_mem_length(dec_rad) || num_sources > oskar_jones_num_sources(R) || num_stations != oskar_telescope_num_stations(telescope)) { *status = OSKAR_ERR_DIMENSION_MISMATCH; return; } /* Check that the data is in the right location. */ if (location != oskar_mem_location(ra_rad) || location != oskar_mem_location(dec_rad)) { *status = OSKAR_ERR_LOCATION_MISMATCH; return; } /* Check that the data is of the right type. */ if (!oskar_type_is_matrix(jones_type)) { *status = OSKAR_ERR_BAD_DATA_TYPE; return; } if (base_type != oskar_mem_precision(ra_rad) || base_type != oskar_mem_precision(dec_rad)) { *status = OSKAR_ERR_TYPE_MISMATCH; return; } /* Evaluate Jones matrix for each source for appropriate stations. */ R_station = oskar_mem_create_alias(0, 0, 0, status); if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA for (i = 0; i < n; ++i) { const oskar_Station* station; /* Get station data. */ station = oskar_telescope_station_const(telescope, i); latitude = oskar_station_lat_rad(station); lst = gast + oskar_station_lon_rad(station); oskar_jones_get_station_pointer(R_station, R, i, status); /* Evaluate source parallactic angles. */ if (base_type == OSKAR_SINGLE) { oskar_evaluate_jones_R_cuda_f( oskar_mem_float4c(R_station, status), num_sources, oskar_mem_float_const(ra_rad, status), oskar_mem_float_const(dec_rad, status), (float)latitude, (float)lst); } else if (base_type == OSKAR_DOUBLE) { oskar_evaluate_jones_R_cuda_d( oskar_mem_double4c(R_station, status), num_sources, oskar_mem_double_const(ra_rad, status), oskar_mem_double_const(dec_rad, status), latitude, lst); } } oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location == OSKAR_CPU) { for (i = 0; i < n; ++i) { const oskar_Station* station; /* Get station data. */ station = oskar_telescope_station_const(telescope, i); latitude = oskar_station_lat_rad(station); lst = gast + oskar_station_lon_rad(station); oskar_jones_get_station_pointer(R_station, R, i, status); /* Evaluate source parallactic angles. */ if (base_type == OSKAR_SINGLE) { oskar_evaluate_jones_R_f( oskar_mem_float4c(R_station, status), num_sources, oskar_mem_float_const(ra_rad, status), oskar_mem_float_const(dec_rad, status), (float)latitude, (float)lst); } else if (base_type == OSKAR_DOUBLE) { oskar_evaluate_jones_R_d( oskar_mem_double4c(R_station, status), num_sources, oskar_mem_double_const(ra_rad, status), oskar_mem_double_const(dec_rad, status), latitude, lst); } } } /* Copy data for station 0 to stations 1 to n, if using a common sky. */ if (oskar_telescope_allow_station_beam_duplication(telescope)) { oskar_Mem* R0; R0 = oskar_mem_create_alias(0, 0, 0, status); oskar_jones_get_station_pointer(R0, R, 0, status); for (i = 1; i < num_stations; ++i) { oskar_jones_get_station_pointer(R_station, R, i, status); oskar_mem_copy_contents(R_station, R0, 0, 0, oskar_mem_length(R0), status); } oskar_mem_free(R0, status); } oskar_mem_free(R_station, status); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/element/oskar_evaluate_geometric_dipole_pattern_cuda.h
/* * Copyright (c) 2012-2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_EVALUATE_GEOMETRIC_DIPOLE_PATTERN_CUDA_H_ #define OSKAR_EVALUATE_GEOMETRIC_DIPOLE_PATTERN_CUDA_H_ /** * @file oskar_evaluate_geometric_dipole_pattern_cuda.h */ #include <oskar_global.h> #include <utility/oskar_vector_types.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Evaluates pattern of a perfect dipole at source positions using CUDA * (single precision). * * @details * This function evaluates the pattern of a perfect dipole antenna * at the supplied source positions using CUDA. * * The supplied theta and phi positions of the sources are the <b>modified</b> * source positions. They must be adjusted relative to a dipole with its axis * oriented along the x-direction. * * Note that all pointers refer to device memory. * * @param[in] num_points Number of points. * @param[in] d_theta Point position (modified) theta values in rad. * @param[in] d_phi Point position (modified) phi values in rad. * @param[in] stride Stride into output arrays. * @param[out] d_E_theta Response per point in E_theta. * @param[out] d_E_phi Response per point in E_phi. */ OSKAR_EXPORT void oskar_evaluate_geometric_dipole_pattern_cuda_f(int num_points, const float* d_theta, const float* d_phi, int stride, float2* d_E_theta, float2* d_E_phi); /** * @brief * Evaluates pattern of a perfect dipole at source positions using CUDA * (scalar version, single precision). * * @details * This function evaluates the scalar pattern of a perfect dipole antenna * at the supplied source positions using CUDA. * * The supplied theta and phi positions of the sources are the <b>modified</b> * source positions. They must be adjusted relative to a dipole with its axis * oriented along the x-direction. * * Note that all pointers refer to device memory. * * @param[in] num_points Number of points. * @param[in] d_theta Point position (modified) theta values in rad. * @param[in] d_phi Point position (modified) phi values in rad. * @param[in] stride Stride into output array (normally 1). * @param[out] d_pattern Response per point. */ OSKAR_EXPORT void oskar_evaluate_geometric_dipole_pattern_scalar_cuda_f(int num_points, const float* d_theta, const float* d_phi, int stride, float2* d_pattern); /** * @brief * Evaluates pattern of a perfect dipole at source positions using CUDA * (double precision). * * @details * This function evaluates the pattern of a perfect dipole antenna * at the supplied source positions using CUDA. * * The supplied theta and phi positions of the sources are the <b>modified</b> * source positions. They must be adjusted relative to a dipole with its axis * oriented along the x-direction. * * Note that all pointers refer to device memory. * * @param[in] num_points Number of points. * @param[in] d_theta Point position (modified) theta values in rad. * @param[in] d_phi Point position (modified) phi values in rad. * @param[in] stride Stride into output arrays. * @param[out] d_E_theta Response per point in E_theta. * @param[out] d_E_phi Response per point in E_phi. */ OSKAR_EXPORT void oskar_evaluate_geometric_dipole_pattern_cuda_d(int num_points, const double* d_theta, const double* d_phi, int stride, double2* d_E_theta, double2* d_E_phi); /** * @brief * Evaluates pattern of a perfect dipole at source positions using CUDA * (scalar version, double precision). * * @details * This function evaluates the scalar pattern of a perfect dipole antenna * at the supplied source positions using CUDA. * * The supplied theta and phi positions of the sources are the <b>modified</b> * source positions. They must be adjusted relative to a dipole with its axis * oriented along the x-direction. * * Note that all pointers refer to device memory. * * @param[in] num_points Number of points. * @param[in] d_theta Point position (modified) theta values in rad. * @param[in] d_phi Point position (modified) phi values in rad. * @param[in] stride Stride into output array (normally 1). * @param[out] d_pattern Response per point. */ OSKAR_EXPORT void oskar_evaluate_geometric_dipole_pattern_scalar_cuda_d(int num_points, const double* d_theta, const double* d_phi, int stride, double2* d_pattern); #ifdef __CUDACC__ /* Kernels. */ __global__ void oskar_evaluate_geometric_dipole_pattern_scalar_cudak_f( const int num_points, const float* restrict theta, const float* restrict phi, const int stride, float2* restrict pattern); __global__ void oskar_evaluate_geometric_dipole_pattern_cudak_f(const int num_points, const float* restrict theta, const float* restrict phi, const int stride, float2* E_theta, float2* E_phi); __global__ void oskar_evaluate_geometric_dipole_pattern_cudak_d(const int num_points, const double* restrict theta, const double* restrict phi, const int stride, double2* E_theta, double2* E_phi); __global__ void oskar_evaluate_geometric_dipole_pattern_scalar_cudak_d( const int num_points, const double* restrict theta, const double* restrict phi, const int stride, double2* restrict pattern); #endif /* __CUDACC__ */ #ifdef __cplusplus } #endif #endif /* OSKAR_EVALUATE_GEOMETRIC_DIPOLE_PATTERN_CUDA_H_ */
davepallot/OSKAR
oskar/sky/oskar_parallactic_angle.h
<gh_stars>1-10 /* * Copyright (c) 2013, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_PARALLACTIC_ANGLE_H_ #define OSKAR_PARALLACTIC_ANGLE_H_ /** * @file oskar_parallactic_angle.h */ #include <oskar_global.h> #ifdef __cplusplus extern "C" { #endif /** * @brief * Function to compute the parallactic angle at a position (single precision). * * @details * This function computes the parallactic angle at a position on the sky, * at a given latitude. * * @param[in] ha The hour angle. * @param[in] dec The declination. * @param[in] cos_lat Cosine of the observer's latitude. * @param[in] sin_lat Sine of the observer's latitude. */ OSKAR_INLINE float oskar_parallactic_angle_f(const float ha, const float dec, const float cos_lat, const float sin_lat) { float sin_dec, cos_dec, sin_ha, cos_ha, x, y; #ifdef __CUDACC__ sincosf(ha, &sin_ha, &cos_ha); sincosf(dec, &sin_dec, &cos_dec); #else sin_ha = sinf(ha); cos_ha = cosf(ha); sin_dec = sinf(dec); cos_dec = cosf(dec); #endif y = cos_lat * sin_ha; x = sin_lat * cos_dec - cos_lat * sin_dec * cos_ha; return atan2f(y, x); } /** * @brief * Function to compute the parallactic angle at a position (double precision). * * @details * This function computes the parallactic angle at a position on the sky, * at a given latitude. * * @param[in] ha The hour angle. * @param[in] dec The declination. * @param[in] cos_lat Cosine of the observer's latitude. * @param[in] sin_lat Sine of the observer's latitude. */ OSKAR_INLINE double oskar_parallactic_angle_d(const double ha, const double dec, const double cos_lat, const double sin_lat) { double sin_dec, cos_dec, sin_ha, cos_ha, x, y; #ifdef __CUDACC__ sincos(ha, &sin_ha, &cos_ha); sincos(dec, &sin_dec, &cos_dec); #else sin_ha = sin(ha); cos_ha = cos(ha); sin_dec = sin(dec); cos_dec = cos(dec); #endif y = cos_lat * sin_ha; x = sin_lat * cos_dec - cos_lat * sin_dec * cos_ha; return atan2(y, x); } #ifdef __cplusplus } #endif #endif /* OSKAR_PARALLACTIC_ANGLE_H_ */
davepallot/OSKAR
oskar/telescope/station/element/src/oskar_element_copy.c
/* * Copyright (c) 2012-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/element/private_element.h" #include "telescope/station/element/oskar_element.h" #ifdef __cplusplus extern "C" { #endif void oskar_element_copy(oskar_Element* dst, const oskar_Element* src, int* status) { int i; /* Check if safe to proceed. */ if (*status) return; dst->precision = src->precision; dst->element_type = src->element_type; dst->taper_type = src->taper_type; dst->cosine_power = src->cosine_power; dst->gaussian_fwhm_rad = src->gaussian_fwhm_rad; dst->dipole_length = src->dipole_length; dst->dipole_length_units = src->dipole_length_units; /* Resize the arrays. */ oskar_element_resize_freq_data(dst, src->num_freq, status); /* Copy the new data across. */ for (i = 0; i < src->num_freq; ++i) { dst->freqs_hz[i] = src->freqs_hz[i]; oskar_mem_copy(dst->filename_x[i], src->filename_x[i], status); oskar_mem_copy(dst->filename_y[i], src->filename_y[i], status); oskar_mem_copy(dst->filename_scalar[i], src->filename_scalar[i], status); oskar_splines_copy(dst->x_v_re[i], src->x_v_re[i], status); oskar_splines_copy(dst->x_v_im[i], src->x_v_im[i], status); oskar_splines_copy(dst->x_h_re[i], src->x_h_re[i], status); oskar_splines_copy(dst->x_h_im[i], src->x_h_im[i], status); oskar_splines_copy(dst->y_v_re[i], src->y_v_re[i], status); oskar_splines_copy(dst->y_v_im[i], src->y_v_im[i], status); oskar_splines_copy(dst->y_h_re[i], src->y_h_re[i], status); oskar_splines_copy(dst->y_h_im[i], src->y_h_im[i], status); oskar_splines_copy(dst->scalar_re[i], src->scalar_re[i], status); oskar_splines_copy(dst->scalar_im[i], src->scalar_im[i], status); } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/station/src/oskar_station_analyse.c
/* * Copyright (c) 2012-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/station/private_station.h" #include "telescope/station/oskar_station.h" #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif void oskar_station_analyse(oskar_Station* station, int* finished_identical_station_check, int* status) { int i, type; double *x_alpha, *x_beta, *x_gamma, *y_alpha, *y_beta, *y_gamma; char* mount_type; /* Check if safe to proceed. */ if (*status) return; /* Check station model is in CPU-accessible memory. */ if (oskar_station_mem_location(station) != OSKAR_CPU) { *status = OSKAR_ERR_BAD_LOCATION; return; } /* Get type. */ type = oskar_station_precision(station); /* Set default station flags. */ station->array_is_3d = 0; station->apply_element_errors = 0; station->apply_element_weight = 0; station->common_element_orientation = 1; /* Analyse orientations separately (always double precision). */ mount_type = oskar_mem_char(station->element_mount_types_cpu); x_alpha = oskar_mem_double(station->element_x_alpha_cpu, status); x_beta = oskar_mem_double(station->element_x_beta_cpu, status); x_gamma = oskar_mem_double(station->element_x_gamma_cpu, status); y_alpha = oskar_mem_double(station->element_y_alpha_cpu, status); y_beta = oskar_mem_double(station->element_y_beta_cpu, status); y_gamma = oskar_mem_double(station->element_y_gamma_cpu, status); for (i = 1; i < station->num_elements; ++i) { if (mount_type[i] != mount_type[0] || x_alpha[i] != x_alpha[0] || x_beta[i] != x_beta[0] || x_gamma[i] != x_gamma[0] || y_alpha[i] != y_alpha[0] || y_beta[i] != y_beta[0] || y_gamma[i] != y_gamma[0]) { station->common_element_orientation = 0; break; } } if (type == OSKAR_DOUBLE) { double *z_true, *z_meas, *amp, *amp_err, *phase, *phase_err; double2 *weights; z_true = oskar_mem_double(station->element_true_z_enu_metres, status); z_meas = oskar_mem_double(station->element_measured_z_enu_metres, status); amp = oskar_mem_double(station->element_gain, status); amp_err = oskar_mem_double(station->element_gain_error, status); phase = oskar_mem_double(station->element_phase_offset_rad, status); phase_err = oskar_mem_double(station->element_phase_error_rad, status); weights = oskar_mem_double2(station->element_weight, status); for (i = 0; i < station->num_elements; ++i) { if (z_true[i] != 0.0 || z_meas[i] != 0.0) { station->array_is_3d = 1; } if (amp[i] != 1.0 || phase[i] != 0.0) { station->apply_element_errors = 1; } if (amp_err[i] != 0.0 || phase_err[i] != 0.0) { station->apply_element_errors = 1; *finished_identical_station_check = 1; } if (weights[i].x != 1.0 || weights[i].y != 0.0) { station->apply_element_weight = 1; } } } else if (type == OSKAR_SINGLE) { float *z_true, *z_meas, *amp, *amp_err, *phase, *phase_err; float2 *weights; z_true = oskar_mem_float(station->element_true_z_enu_metres, status); z_meas = oskar_mem_float(station->element_measured_z_enu_metres, status); amp = oskar_mem_float(station->element_gain, status); amp_err = oskar_mem_float(station->element_gain_error, status); phase = oskar_mem_float(station->element_phase_offset_rad, status); phase_err = oskar_mem_float(station->element_phase_error_rad, status); weights = oskar_mem_float2(station->element_weight, status); for (i = 0; i < station->num_elements; ++i) { if (z_true[i] != 0.0 || z_meas[i] != 0.0) { station->array_is_3d = 1; } if (amp[i] != 1.0f || phase[i] != 0.0) { station->apply_element_errors = 1; } if (amp_err[i] != 0.0 || phase_err[i] != 0.0) { station->apply_element_errors = 1; *finished_identical_station_check = 1; } if (weights[i].x != 1.0f || weights[i].y != 0.0) { station->apply_element_weight = 1; } } } /* Check if station has child stations. */ if (oskar_station_has_child(station)) { /* Recursively analyse all child stations. */ for (i = 0; i < station->num_elements; ++i) { oskar_station_analyse(oskar_station_child(station, i), finished_identical_station_check, status); } /* Check if we need to examine every station. */ if (*finished_identical_station_check) { station->identical_children = 0; } else { /* Check if child stations are identical. */ station->identical_children = 1; for (i = 1; i < station->num_elements; ++i) { if (oskar_station_different( oskar_station_child_const(station, 0), oskar_station_child_const(station, i), status)) { station->identical_children = 0; } } } } } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/telescope/oskar_telescope.h
<reponame>davepallot/OSKAR /* * Copyright (c) 2013-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_TELESCOPE_H_ #define OSKAR_TELESCOPE_H_ /** * @file oskar_telescope.h */ /* Public interface. */ #ifdef __cplusplus extern "C" { #endif struct oskar_Telescope; #ifndef OSKAR_TELESCOPE_TYPEDEF_ #define OSKAR_TELESCOPE_TYPEDEF_ typedef struct oskar_Telescope oskar_Telescope; #endif /* OSKAR_TELESCOPE_TYPEDEF_ */ enum OSKAR_POL_MODE_TYPE { OSKAR_POL_MODE_FULL, OSKAR_POL_MODE_SCALAR }; #ifdef __cplusplus } #endif #include <telescope/station/oskar_station.h> #include <telescope/oskar_telescope_accessors.h> #include <telescope/oskar_telescope_analyse.h> #include <telescope/oskar_telescope_create.h> #include <telescope/oskar_telescope_create_copy.h> #include <telescope/oskar_telescope_duplicate_first_station.h> #include <telescope/oskar_telescope_free.h> #include <telescope/oskar_telescope_load.h> #include <telescope/oskar_telescope_load_pointing_file.h> #include <telescope/oskar_telescope_load_position.h> #include <telescope/oskar_telescope_load_station_coords_ecef.h> #include <telescope/oskar_telescope_load_station_coords_enu.h> #include <telescope/oskar_telescope_load_station_coords_wgs84.h> #include <telescope/oskar_telescope_log_summary.h> #include <telescope/oskar_telescope_resize.h> #include <telescope/oskar_telescope_save.h> #include <telescope/oskar_telescope_save_layout.h> #include <telescope/oskar_telescope_set_station_coords.h> #include <telescope/oskar_telescope_set_station_coords_ecef.h> #include <telescope/oskar_telescope_set_station_coords_enu.h> #include <telescope/oskar_telescope_set_station_coords_wgs84.h> #endif /* OSKAR_TELESCOPE_H_ */
davepallot/OSKAR
gui/oskar_DoubleSpinBox.h
<gh_stars>1-10 /* * Copyright (c) 2012-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_DOUBLE_SPIN_BOX_H_ #define OSKAR_DOUBLE_SPIN_BOX_H_ #include <QtWidgets/QAbstractSpinBox> class QDoubleValidator; namespace oskar { class DoubleSpinBox : public QAbstractSpinBox { Q_OBJECT public: DoubleSpinBox(QWidget* parent = 0); QString cleanText() const; int decimals() const; void setDecimals(int prec); void setRange(double minimum, double maximum); double rangeMin() const; void setSingleStep(double val); double singleStep() const; virtual void stepBy(int steps); virtual QString textFromValue(double value) const; virtual QValidator::State validate(QString& text, int& pos) const; double value() const; virtual double valueFromText(const QString& text) const; void setMinText(const QString& text); QString minText() const; public Q_SLOTS: void setValue(double val); void setValue(const QString& text); Q_SIGNALS: void valueChanged(double d); void valueChanged(const QString& text); protected: virtual void focusInEvent(QFocusEvent* event); virtual void keyPressEvent(QKeyEvent* event); virtual StepEnabled stepEnabled() const; private Q_SLOTS: void setValue(); private: double value_; double max_; double min_; QString minText_; double singleStep_; int decimals_; QDoubleValidator* v_; }; } /* namespace oskar */ #endif /* OSKAR_DOUBLE_SPIN_BOX_H_ */
davepallot/OSKAR
oskar/telescope/src/oskar_telescope_set_station_coords.c
/* * Copyright (c) 2011-2015, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "telescope/private_telescope.h" #include "telescope/oskar_telescope.h" #ifdef __cplusplus extern "C" { #endif void oskar_telescope_set_station_coords(oskar_Telescope* dst, int index, const double measured_offset_ecef[3], const double true_offset_ecef[3], const double measured_enu[3], const double true_enu[3], int* status) { oskar_mem_set_element_real(dst->station_measured_x_offset_ecef_metres, index, measured_offset_ecef[0], status); oskar_mem_set_element_real(dst->station_measured_y_offset_ecef_metres, index, measured_offset_ecef[1], status); oskar_mem_set_element_real(dst->station_measured_z_offset_ecef_metres, index, measured_offset_ecef[2], status); oskar_mem_set_element_real(dst->station_true_x_offset_ecef_metres, index, true_offset_ecef[0], status); oskar_mem_set_element_real(dst->station_true_y_offset_ecef_metres, index, true_offset_ecef[1], status); oskar_mem_set_element_real(dst->station_true_z_offset_ecef_metres, index, true_offset_ecef[2], status); oskar_mem_set_element_real(dst->station_measured_x_enu_metres, index, measured_enu[0], status); oskar_mem_set_element_real(dst->station_measured_y_enu_metres, index, measured_enu[1], status); oskar_mem_set_element_real(dst->station_measured_z_enu_metres, index, measured_enu[2], status); oskar_mem_set_element_real(dst->station_true_x_enu_metres, index, true_enu[0], status); oskar_mem_set_element_real(dst->station_true_y_enu_metres, index, true_enu[1], status); oskar_mem_set_element_real(dst->station_true_z_enu_metres, index, true_enu[2], status); } #ifdef __cplusplus } #endif
davepallot/OSKAR
oskar/utility/oskar_dir.h
/* * Copyright (c) 2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_DIR_H_ #define OSKAR_DIR_H_ /** * @file oskar_dir.h */ #include <oskar_global.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Checks if the specified directory exists. * * @details * This function returns true if the specified directory exists, false if not. * * @param[in] dir_path Path of the directory to check. * * @return Returns true if the specified directory exists, false if not. */ OSKAR_EXPORT int oskar_dir_exists(const char* dir_path); /** * @brief Checks if the specified file exists in the specified directory. * * @details * This function returns true if the specified file exists in the * specified directory, false if not. * * @param[in] dir_path Path of the directory to check. * @param[in] file_name Name of the file in the directory. * * @return Returns true if the file exists in the directory, false if not. */ OSKAR_EXPORT int oskar_dir_file_exists(const char* dir_path, const char* file_name); /** * @brief Returns the path name of an item in the directory. * * @details * Returns the path name of a file in the directory. * Does not check if the file actually exists in the current directory. * * The name must be freed using free() when no longer needed. * * @param[in] dir_path Path of the directory. * @param[in] item_name Name of the item in the directory. */ OSKAR_EXPORT char* oskar_dir_get_path(const char* dir_path, const char* item_name); /** * @brief Returns names of all items in the specified directory. * * @details * This function returns the names of all items in the specified directory, * sorted by name. * * The list of names and the names themselves must be freed using free() * when no longer needed. * * An optional wildcard pattern can be supplied if required. * If not NULL, this is used to select item names matching only this pattern * (e.g. "*.txt" or "element_pattern*"). * * @param[in] dir_path Path of the directory. * @param[in] wildcard Optional wildcard string for name match (or NULL). * @param[in] match_files If true, match files. * @param[in] match_dirs If true, match directories. * @param[in,out] num_items Number of items in the list of names. * @param[in,out] items Pointer to list of item names. */ OSKAR_EXPORT void oskar_dir_items(const char* dir_path, const char* wildcard, int match_files, int match_dirs, int* num_items, char*** items); /** * @brief Creates a directory. * * @details * This function creates a directory with the given name. * It does nothing and returns true if the directory already exists. * * @param[in] dir_path Path of the directory to create. * * @return Returns true if the directory was created successfully, false if not. */ OSKAR_EXPORT int oskar_dir_mkdir(const char* dir_path); /** * @brief Creates a directory tree. * * @details * This function creates a directory tree with the given path. * It does nothing and returns true if the directory tree already exists. * * @param[in] dir_path Path of the directory tree to create. * * @return Returns true if the directory was created successfully, false if not. */ OSKAR_EXPORT int oskar_dir_mkpath(const char* dir_path); /** * @brief Removes a directory and its contents. * * @details * This function recursively removes the named directory and its contents. * Use with caution! * * @param[in] dir_path Path of the directory to remove. * * @return Returns true if the directory was removed successfully, false if not. */ OSKAR_EXPORT int oskar_dir_remove(const char* dir_path); /** * @brief Returns the character denoting the directory separator. * * @details * This function returns the character used to separate directories in a * pathname: '/' on POSIX-compliant systems, '\' on Windows. */ OSKAR_EXPORT char oskar_dir_separator(void); #ifdef __cplusplus } #endif #endif /* OSKAR_DIR_H_ */
davepallot/OSKAR
oskar/log/private_log.h
/* * Copyright (c) 2012-2016, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OSKAR_PRIVATE_LOG_H_ #define OSKAR_PRIVATE_LOG_H_ /** * @file private_log.h */ #include <oskar_global.h> #include <stdio.h> #include <time.h> struct oskar_Log { /* Variables to control which log entries will be printed */ int file_priority; /**< Controls which log messages are printed in the log file */ int term_priority; /**< Controls which log messages are printed in the terminal */ /* The column start index for value log entries. */ int value_width; /**< Width of value message */ /* File pointer to the log file */ FILE* file; /**< Pointer to an open log file stream. */ int keep_file; /**< Flag, true if log file will be retained on completion. */ /* Log record meta-data */ int size; /**< The number of entries in the log. */ int capacity; /**< The capacity of the arrays in this structure. */ char* name; /**< The name of the log file. */ char* code; /**< Array containing the code of each entry. */ int* offset; /**< Array containing the memory offsets in bytes of each entry. */ int* length; /**< Array containing the length in bytes of each entry. */ time_t* timestamp; /**< Array containing log time stamps. */ }; #ifndef OSKAR_LOG_TYPEDEF_ #define OSKAR_LOG_TYPEDEF_ typedef struct oskar_Log oskar_Log; #endif /* OSKAR_LOG_TYPEDEF_ */ /* Private function. */ #include <log/oskar_log_write.h> #endif /* OSKAR_PRIVATE_LOG_H_ */