LALInference  4.1.6.1-89842e6
LALInference.c
Go to the documentation of this file.
1 /*
2  * LALInference.c: Bayesian Followup functions
3  *
4  * Copyright (C) 2009, 2012 Ilya Mandel, Vivien Raymond, Christian
5  * Roever, Marc van der Sluys, John Veitch, and Will M. Farr
6  *
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with with program; see the file COPYING. If not, write to the
20  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21  * MA 02110-1301 USA
22  */
23 
24 #include <config.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <math.h>
28 #include <lal/LALInference.h>
29 #include <lal/Units.h>
30 #include <lal/FrequencySeries.h>
31 #include <lal/Sequence.h>
32 #include <lal/TimeSeries.h>
33 #include <lal/TimeFreqFFT.h>
34 #include <lal/VectorOps.h>
35 #include <lal/Date.h>
36 #include <lal/XLALError.h>
37 #include <gsl/gsl_vector.h>
38 #include <gsl/gsl_matrix.h>
39 #include <gsl/gsl_eigen.h>
40 #include <gsl/gsl_interp.h>
41 #include <lal/LALHashFunc.h>
42 #include <lal/LALSimNeutronStar.h>
43 
44 #ifdef __GNUC__
45 #define UNUSED __attribute__ ((unused))
46 #else
47 #define UNUSED
48 #endif
49 
50 #define COL_MAX 128
51 #define STR_MAX 2048
52 
53 typedef struct taghash_elem
54 {
55  const char *name;
57 } hash_elem;
58 
59 static void *new_elem( const char *name, LALInferenceVariableItem *itemPtr )
60 {
61  hash_elem e = { .name=name, .itemPtr=itemPtr };
62  return memcpy( XLALMalloc( sizeof( e ) ), &e, sizeof( e ) );
63 };
64 
65 static void del_elem(void *elem)
66 {
67  XLALFree(elem);
68 }
69 
70 static UINT8 LALInferenceElemHash(const void *elem);
71 static UINT8 LALInferenceElemHash(const void *elem)
72 {
74  size_t len = strnlen(((const hash_elem *)elem)->name,VARNAME_MAX);
75  return(XLALCityHash64(((const hash_elem *)elem)->name, len));
76 }
77 
78 static int LALInferenceElemCmp(const void *elem1, const void *elem2);
79 static int LALInferenceElemCmp(const void *elem1, const void *elem2)
80 {
81  if(!elem1 || !elem2) XLAL_ERROR(XLAL_EINVAL);
82  return(strncmp(((const hash_elem *)elem1)->name,((const hash_elem *)elem2)->name,VARNAME_MAX));
83 }
84 
85 
86 size_t LALInferenceTypeSize[] = {sizeof(INT4),
87  sizeof(INT8),
88  sizeof(UINT4),
89  sizeof(REAL4),
90  sizeof(REAL8),
91  sizeof(COMPLEX8),
92  sizeof(COMPLEX16),
93  sizeof(gsl_matrix *),
94  sizeof(REAL8Vector *),
95  sizeof(INT4Vector *),
96  sizeof(UINT4Vector *),
97  sizeof(COMPLEX16Vector *),
98  sizeof(CHAR *),
99  sizeof(LALInferenceMCMCRunPhase *),
100  sizeof(void *)
101 };
102 
103 
104 /* Initialize an empty thread, saving a timestamp for benchmarking */
106  struct timeval tv;
107 
108  /* Get creation time */
109  gettimeofday(&tv, NULL);
110 
111  if(!thread)
112  thread = XLALCalloc(1, sizeof(LALInferenceThreadState));
113 
114  thread->step = 0;
115  thread->temperature = 1.0;
116  thread->creation_time = tv.tv_sec + tv.tv_usec/1E6;
117  thread->currentPropDensity = -INFINITY;
118  thread->temp_swap_counter = 0;
119  thread->temp_swap_window = 50;
120  thread->temp_swap_accepts = XLALCalloc(thread->temp_swap_window, sizeof(INT4));
121  thread->currentParams = XLALCalloc(1, sizeof(LALInferenceVariables));
122  thread->algorithmParams = XLALCalloc(1, sizeof(LALInferenceVariables));
123  thread->priorArgs=XLALCalloc(1,sizeof(LALInferenceVariables));
124  thread->proposalArgs=XLALCalloc(1,sizeof(LALInferenceVariables));
127 
128  /* Differential evolution (also used for caching output) */
129  thread->differentialPoints = XLALCalloc(1, sizeof(LALInferenceVariables *));
130  thread->differentialPointsLength = 0;
131  thread->differentialPointsSize = 1;
132  thread->differentialPointsSkip = 1;
133 
134  return thread;
135 }
136 
137 /* Initialize a bunch of threads using LALInferenceInitThread */
139  INT4 t;
140 
141  LALInferenceThreadState *threads = XLALCalloc(nthreads, sizeof(LALInferenceThreadState));
142 
143  for (t = 0; t < nthreads; t++)
144  LALInferenceInitThread(&threads[t]);
145 
146  return threads;
147 }
148 
149 
150 /* ============ Accessor functions for the Variable structure: ========== */
151 
152 static char *colNameToParamName(const char *colName);
153 /* Helper functions for sanity check */
157 static INT4 matrix_equal(gsl_matrix *a, gsl_matrix *b);
158 static LALInferenceVariableItem *LALInferenceGetItemSlow(const LALInferenceVariables *vars,const char *name);
159 
160 /* This replaces gsl_matrix_equal which is only available with gsl 1.15+ */
161 /* Return 1 if matrices are equal, 0 otherwise */
162 static INT4 matrix_equal(gsl_matrix *a, gsl_matrix *b)
163 {
164  if(!a||!b) return 0;
165  if(a->size1!=b->size1 || a->size2!=b->size2) return 0;
166  UINT4 i,j;
167  for(i=0;i<a->size1;i++)
168  for(j=0;j<a->size2;j++)
169  if(gsl_matrix_get(a,i,j)!=gsl_matrix_get(b,i,j))
170  return 0;
171 
172  return 1;
173 }
174 
176 /* (this function is only to be used internally) */
177 /* Returns pointer to item for given item name. */
178 {
179  hash_elem tmp; /* Used for hash table lookup */
180  const hash_elem *match=NULL;
181  if(vars==NULL) return NULL;
182  if(vars->dimension==0) return NULL;
183  if(!vars->hash_table) return LALInferenceGetItemSlow(vars,name);
184  tmp.name=name;
185  XLALHashTblFind(vars->hash_table, /**< [in] Pointer to hash table */
186  &tmp, /**< [in] Hash element to match */
187  (const void **)&match /**< [out] Pointer to matched hash element, or NULL if not found */
188  );
189  if(!match) return NULL;
190  return match->itemPtr;
191 }
192 /* Walk through the list to check for an item */
194 {
195  LALInferenceVariableItem *this = vars->head;
196  if(vars->dimension==0) return NULL;
197 
198  while (this != NULL) {
199  if (!strcmp(this->name,name)) break;
200  else this = this->next;
201  }
202 
203  return(this);
204 }
205 
206 
208 /* (this function is only to be used internally) */
209 /* Returns pointer to item for given item number. */
210 {
211  int i=1;
212  if (idx < i) {
213  XLAL_ERROR_NULL(XLAL_EINVAL, "Requesting zero or negative idx entry.");
214  }
215  LALInferenceVariableItem *this=vars->head;
216  while (this != NULL) {
217  if (i == idx) break;
218  else {
219  this = this->next;
220  ++i;
221  }
222  }
223  return(this);
224 }
225 
227 {
228  return (LALInferenceGetItem(vars,name)->vary);
229 }
230 
232 {
234  item->vary = vary;
235  return;
236 }
237 
238 void *LALInferenceGetVariable(const LALInferenceVariables * vars,const char * name)
239 /* Return the value of variable name from the vars structure by walking the list */
240 {
242  item=LALInferenceGetItem(vars,name);
243  if(!item) {
244  XLAL_ERROR_NULL(XLAL_EFAILED, "Entry \"%s\" not found.", name);
245  }
246  return(item->value);
247 }
248 
249 
251 {
252  return(vars->dimension);
253 }
254 
256  INT4 count_vectors = 1;
257  return LALInferenceGetVariableDimensionNonFixedChooseVectors(vars, count_vectors);
258 }
259 
261 {
262  INT4 count=0;
263  gsl_matrix *m=NULL;
264  REAL8Vector *v8=NULL;
265  COMPLEX16Vector *v16=NULL;
267  if (ptr==NULL) return count;
268  else {
269  /* loop over entries: */
270  while (ptr != NULL) {
271  /* print name: */
272  //TBL: LALInferenceGetVariableDimensionNonFixed had to be modified for noise-parameters, which are stored in a gsl_matrix
273  if (LALInferenceCheckVariableNonFixed(vars,ptr->name))
274  {
275  //Generalize to allow for other data types
277  {
278  if (count_vectors) {
279  m = *((gsl_matrix **)ptr->value);
280  count += (INT4)( (m->size1)*(m->size2) );
281  }
282  }
283  else if(ptr->type == LALINFERENCE_UINT4Vector_t)
284  {
285  if (count_vectors) {
286  UINT4Vector *v=NULL;
287  v = *((UINT4Vector **)ptr->value);
288  count += (INT4)( v->length );
289  }
290  }
291  else if(ptr->type == LALINFERENCE_INT4Vector_t)
292  {
293  if (count_vectors) {
294  INT4Vector *v=NULL;
295  v = *((INT4Vector **)ptr->value);
296  count += (INT4)( v->length );
297  }
298  }
299  else if(ptr->type == LALINFERENCE_REAL8Vector_t)
300  {
301  if (count_vectors) {
302  v8 = *(REAL8Vector **)ptr->value;
303  count += (int)(v8->length);
304  }
305  }
307  {
308  if (count_vectors) {
309  v16 = *(COMPLEX16Vector **)ptr->value;
310  count += (int)(v16->length);
311  }
312  }
313  else count++;
314  }
315  ptr = ptr->next;
316  }
317  }
318  return count;
319 }
320 
322 {
323  return LALInferenceGetItem(vars,name)->type;
324 }
325 
327 /* Returns type of the i-th entry, */
328 /* where 1 <= idx <= dimension. */
329 {
331  if ((idx < 1) || (idx > vars->dimension)){
332  XLAL_ERROR(XLAL_EINVAL, "idx = %d, but needs to be 1 <= idx <= dimension = %d.", idx, vars->dimension);
333  }
334  item = LALInferenceGetItemNr(vars, idx);
335  return(item->type);
336 }
337 
338 
340 /* Returns (pointer to) the name of the i-th entry, */
341 /* where 1 <= idx <= dimension. */
342 {
344  if ((idx < 1) || (idx > vars->dimension)){
345  XLAL_ERROR_NULL(XLAL_EINVAL, "idx = %d, but needs to be 1 <= idx <= dimension = %d.", idx, vars->dimension);
346  }
347  item = LALInferenceGetItemNr(vars, idx);
348  return(item->name);
349 }
350 
351 
352 void LALInferenceSetVariable(LALInferenceVariables * vars, const char * name, const void *value)
353 /* Set the value of variable name in the vars structure to value */
354 {
356  item=LALInferenceGetItem(vars,name);
357  if(!item) {
358  XLAL_ERROR_VOID(XLAL_EINVAL, "Entry \"%s\" not found.", name);
359  }
360  if (item->vary==LALINFERENCE_PARAM_FIXED)
361  {
362  XLALPrintWarning("Warning! Attempting to set variable %s which is fixed\n",item->name);
363  return;
364  }
365 
366  /* We own the memory for each of these types, and it's about to be
367  replaced by the new inputs. */
368  switch (item->type) {
370  gsl_matrix_free(*(gsl_matrix **)item->value);
371  break;
374  break;
377  break;
380  break;
383  break;
384  default:
385  /* Do nothing for the other cases. Possibly should deal with
386  string_t, runphase_ptr_t and void_ptr_t, too, but these cases
387  are too complicated to handle! */
388  break;
389  }
390 
391  memcpy(item->value,value,LALInferenceTypeSize[item->type]);
392  return;
393 }
394 
396 /* Add the variable name with type type and value value to vars */
397 /* If variable already exists, it will over-write the current value if type compatible*/
398 {
399  LALInferenceVariableItem *old=NULL;
400  /* Create the hash table if it does not exist */
402 
403  /* Check input value is accessible */
404  if(!value) {
405  XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to access value through null pointer; trying to add \"%s\".", name);
406  }
407 
408  /* Check the name doesn't already exist */
409  if(LALInferenceCheckVariable(vars,name)) {
410  old=LALInferenceGetItem(vars,name);
411  if(old->type != type)
412  {
414  //XLAL_ERROR_VOID(XLAL_EINVAL, "Cannot re-add \"%s\" as previous definition has wrong type.", name);
415  }
416  else{
417  LALInferenceSetVariable(vars,name,value);
418  return;
419  }
420  }
421  //if(!value) {
422  // XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to access value through null pointer; trying to add \"%s\".", name);
423  //}
424 
426 
427  memset(new,0,sizeof(LALInferenceVariableItem));
428  if(new) {
429  new->value = (void *)XLALMalloc(LALInferenceTypeSize[type]);
430  }
431  if(new==NULL||new->value==NULL) {
432  XLAL_ERROR_VOID(XLAL_ENOMEM, "Unable to allocate memory for list item.");
433  }
434  if((VARNAME_MAX <= snprintf(new->name, VARNAME_MAX, "%s", name)))
435  {
436  fprintf(stderr,"Variable name %s too long. Maximum length %i\n",name,VARNAME_MAX);
437  exit(1);
438  }
439  new->type = type;
440  new->vary = vary;
441  memcpy(new->value,value,LALInferenceTypeSize[type]);
442  new->next = vars->head;
443  vars->head = new;
444  hash_elem *elem=new_elem(new->name,new);
445  XLALHashTblAdd(vars->hash_table,(void *)elem);
446  vars->dimension++;
447  return;
448 }
449 
451 {
453  if(!vars)
455  this=vars->head;
456  LALInferenceVariableItem *parent=NULL;
457  while(this){
458  if(!strcmp(this->name,name)) break;
459  else {parent=this; this=this->next;}
460  }
461  if(!this){
462  XLAL_PRINT_WARNING("Entry \"%s\" not found.", name);
463  return;
464  }
465  if(!parent) vars->head=this->next;
466  else parent->next=this->next;
467  /* Remove from hash table */
468  hash_elem elem;
469  elem.name=this->name;
470  XLALHashTblRemove(vars->hash_table,(void *)&elem);
471  /* We own the memory for these types, so have to free. */
472  switch (this->type) {
474  gsl_matrix_free(*(gsl_matrix **)this->value);
475  break;
477  XLALDestroyREAL8Vector(*(REAL8Vector **)this->value);
478  break;
480  XLALDestroyINT4Vector(*(INT4Vector **)this->value);
481  break;
483  XLALDestroyUINT4Vector(*(UINT4Vector **)this->value);
484  break;
487  break;
488  default:
489  /* Do nothing for the other cases. Possibly should deal with
490  string_t, runphase_ptr_t and void_ptr_t, too, but these cases
491  are too complicated to handle! */
492  break;
493  }
494 
495  XLALFree(this->value);
496  this->value=NULL;
497  XLALFree(this);
498  this=NULL;
499  vars->dimension--;
500  return;
501 }
502 
504 /* Checks for a writeable variable */
505 {
507  if(!LALInferenceCheckVariable(vars,name)) return 0;
510  else return 0;
511 
512 }
513 
515 /* Checks for a writeable variable */
516 {
518  if(!LALInferenceCheckVariable(vars,name)) return 0;
521  else return 0;
522 
523 }
524 
526 /* Check for existance of name */
527 {
528  if(LALInferenceGetItem(vars,name)) return 1;
529  else return 0;
530 }
531 
533 /* Free all variables inside the linked list, leaving only the head struct */
534 {
535  LALInferenceVariableItem *this,*next;
536  if(!vars) return;
537  this=vars->head;
538  if(this) next=this->next;
539  while(this){
540  if(this->type==LALINFERENCE_gslMatrix_t) gsl_matrix_free(*(gsl_matrix **)this->value);
541  if(this->type==LALINFERENCE_INT4Vector_t) XLALDestroyINT4Vector(*(INT4Vector **)this->value);
545  XLALFree(this->value);
546  XLALFree(this);
547  this=next;
548  if(this) next=this->next;
549  }
550  vars->head=NULL;
551  vars->dimension=0;
552  if(vars->hash_table) XLALHashTblDestroy(vars->hash_table);
553  vars->hash_table=NULL;
554 
555  return;
556 }
557 
559 /* copy contents of "origin" over to "target" */
560 {
561  int dims = 0, i = 0;
562 
563  /* Check that the source and origin differ */
564  if(origin==target) return;
565 
567  if(!origin)
568  {
569  XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to access origin pointer.");
570  }
571 
572  /* Make sure the structure is initialised */
573  if(!target) XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to copy to uninitialised LALInferenceVariables structure.");
574 
575  /* First clear the target */
577 
578  /* Now add the variables in reverse order, to preserve the
579  * ordering */
580  dims = LALInferenceGetVariableDimension( origin );
581 
582  /* then copy over elements of "origin" - due to how elements are added by
583  LALInferenceAddVariable this has to be done in reverse order to preserve
584  the ordering of "origin" */
585  for ( i = dims; i > 0; i-- ){
586  ptr = LALInferenceGetItemNr(origin, i);
587 
588  if(!ptr)
589  {
590  XLAL_ERROR_VOID(XLAL_EFAULT, "Bad LALInferenceVariable structure found while trying to copy.");
591  }
592  else
593  {
594  if(!ptr->value){
595  XLAL_ERROR_VOID(XLAL_EFAULT, "Badly formed LALInferenceVariableItem structure!");
596  }
597  /* Deep copy matrix and vector types */
598  switch (ptr->type)
599  {
601  {
602  gsl_matrix *old=*(gsl_matrix **)ptr->value;
603  gsl_matrix *new=gsl_matrix_alloc(old->size1,old->size2);
604  if(!new) XLAL_ERROR_VOID(XLAL_ENOMEM,"Unable to create %zux%zu matrix\n",old->size1,old->size2);
605  gsl_matrix_memcpy(new,old);
606  LALInferenceAddVariable(target,ptr->name,(void *)&new,ptr->type,ptr->vary);
607  break;
608  }
610  {
611  INT4Vector *old=*(INT4Vector **)ptr->value;
613  if(new) memcpy(new->data,old->data,new->length*sizeof(new->data[0]));
614  else XLAL_ERROR_VOID(XLAL_ENOMEM,"Unable to copy vector!\n");
615  LALInferenceAddVariable(target,ptr->name,(void *)&new,ptr->type,ptr->vary);
616  break;
617  }
619  {
620  UINT4Vector *old=*(UINT4Vector **)ptr->value;
622  if(new) memcpy(new->data,old->data,new->length*sizeof(new->data[0]));
623  else XLAL_ERROR_VOID(XLAL_ENOMEM,"Unable to copy vector!\n");
624  LALInferenceAddVariable(target,ptr->name,(void *)&new,ptr->type,ptr->vary);
625  break;
626  }
628  {
629  REAL8Vector *old=*(REAL8Vector **)ptr->value;
631  if(new) memcpy(new->data,old->data,new->length*sizeof(REAL8));
632  else XLAL_ERROR_VOID(XLAL_ENOMEM,"Unable to copy vector!\n");
633  LALInferenceAddVariable(target,ptr->name,(void *)&new,ptr->type,ptr->vary);
634  break;
635  }
637  {
640  if(new) memcpy(new->data,old->data,new->length*sizeof(COMPLEX16));
641  else XLAL_ERROR_VOID(XLAL_ENOMEM,"Unable to copy vector!\n");
642  LALInferenceAddVariable(target,ptr->name,(void *)&new,ptr->type,ptr->vary);
643  break;
644  }
645  default:
646  { /* Just memcpy */
647  LALInferenceAddVariable(target, ptr->name, ptr->value, ptr->type,
648  ptr->vary);
649  break;
650  }
651  }
652  }
653  }
654 
655  return;
656 }
657 
658 
660 /* Copy REAL8s from "origin" to "target" if they weren't set on the command line */
662  char valopt[VARNAME_MAX+3];
663 
664  /* Check that the source and origin differ */
665  if (origin==target)
666  return;
667 
668  if (!origin)
669  XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to access origin pointer.");
670 
671  /* Make sure the structure is initialised */
672  if (!target)
673  XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to copy to uninitialised LALInferenceVariables structure.");
674 
675  for (ptr = origin->head; ptr; ptr = ptr->next) {
676  if (LALInferenceGetVariableType(origin, ptr->name) == LALINFERENCE_REAL8_t) {
677  sprintf(valopt, "--%s", ptr->name);
678 
679  if (!LALInferenceGetProcParamVal(commandLine, valopt))
680  LALInferenceSetREAL8Variable(target, ptr->name, *(REAL8 *)ptr->value);
681  }
682  }
683 }
684 
685 /** Prints a variable item to a string (must be pre-allocated!)
686  * Returns the number of bytes necessary to store the output */
688 {
689  if(ptr==NULL) {
690  XLALPrintError("Null LALInferenceVariableItem pointer.");
691  return(0);
692  }
693  if(out==NULL) {
694  XLALPrintError( "Null output string pointer.");
695  return(0);
696  }
697  switch (ptr->type) {
698  case LALINFERENCE_INT4_t:
699  snprintf(out,strsize, "%" LAL_INT4_FORMAT, *(INT4 *) ptr->value);
700  break;
701  case LALINFERENCE_INT8_t:
702  snprintf(out, strsize, "%" LAL_INT8_FORMAT, *(INT8 *) ptr->value);
703  break;
705  snprintf(out, strsize, "%" LAL_UINT4_FORMAT, *(UINT4 *) ptr->value);
706  break;
708  snprintf(out, strsize, "%.15lf", *(REAL4 *) ptr->value);
709  break;
711  snprintf(out, strsize, "%.15lf", *(REAL8 *) ptr->value);
712  break;
714  snprintf(out, strsize, "%e + i*%e",
715  (REAL4) crealf(*(COMPLEX8 *) ptr->value), (REAL4) cimagf(*(COMPLEX8 *) ptr->value));
716  break;
718  snprintf(out, strsize, "%e + i*%e",
719  (REAL8) creal(*(COMPLEX16 *) ptr->value), (REAL8) cimag(*(COMPLEX16 *) ptr->value));
720  break;
722  {
723  UINT4Vector *vec=*(UINT4Vector **)ptr->value;
724  char arrstr[31*vec->length +1]; /* Enough space for 20 chars per entry */
725  sprintf(arrstr,"");
726  for(UINT4 i=0;i<vec->length;i++)
727  {
728  char this[30];
729  snprintf(this,29,"%"LAL_UINT4_FORMAT" ",vec->data[i]);
730  strncat(arrstr,this,30);
731  }
732  size_t actual_len=strlen(arrstr) +1;
733  if(actual_len > strsize)
734  {
735  XLALPrintWarning("Not enough space to print LALInferenceVariableItem %s with %i elements!\n",ptr->name,vec->length);
736  return(actual_len);
737  }
738  snprintf(out,strsize,"%s",arrstr);
739  break;
740  }
742  {
743  INT4Vector *vec=*(INT4Vector **)ptr->value;
744  char arrstr[31*vec->length +1]; /* Enough space for 20 chars per entry */
745  sprintf(arrstr,"");
746  for(UINT4 i=0;i<vec->length;i++)
747  {
748  char this[30];
749  snprintf(this,29,"%"LAL_INT4_FORMAT" ",vec->data[i]);
750  strncat(arrstr,this,30);
751  }
752  size_t actual_len=strlen(arrstr) +1;
753  if(actual_len > strsize)
754  {
755  XLALPrintWarning("Not enough space to print LALInferenceVariableItem %s with %i elements!\n",ptr->name,vec->length);
756  return(actual_len);
757  }
758  snprintf(out,strsize,"%s",arrstr);
759  break;
760  }
761  /* TODO: Implement gsl_matrix output */
762  /*
763  case LALINFERENCE_gslMatrix_t:
764  snprintf(out, strsize,"<can't print matrix>");
765  break;
766  */
768  {
769  REAL8Vector *vec=*(REAL8Vector **)ptr->value;
770  char arrstr[31*vec->length +1]; /* Enough space for 20 chars per entry */
771  sprintf(arrstr,"");
772  for(UINT4 i=0;i<vec->length;i++)
773  {
774  char this[30];
775  snprintf(this,29,"%.20"LAL_REAL8_FORMAT" ",vec->data[i]);
776  strncat(arrstr,this,30);
777  }
778  size_t actual_len=strlen(arrstr) +1;
779  if(actual_len > strsize)
780  {
781  XLALPrintWarning("Not enough space to print LALInferenceVariableItem %s with %i elements!\n",ptr->name,vec->length);
782  return(actual_len);
783  }
784  snprintf(out,strsize,"%s",arrstr);
785  break;
786  }
787  default:
788  {
789  /* Throw a warning and return 0, buffer won't be writen */
790  XLALPrintWarning("%s: Can't print variable of type %i\n",__func__,ptr->type);
791  return 0;
792  }
793  /* sprintf(out, "<can't print>");*/
794  }
795  return(strlen(out));
796 }
797 
799 /**
800  * output contents of a 'LALInferenceVariables' structure * /
801  * / * (by now only prints names and types, but no values)
802  */
803 {
805  fprintf(stdout, "LALInferenceVariables:\n");
806  if (ptr==NULL) fprintf(stdout, " <empty>\n");
807  else {
808  /* loop over entries: */
809  while (ptr != NULL) {
810  /* print name: */
811  fprintf(stdout, " \"%s\"", ptr->name);
812  /* print type: */
813  fprintf(stdout, " (type #%d, ", ((int) ptr->type));
814  switch (ptr->type) {
815  case LALINFERENCE_INT4_t:
816  fprintf(stdout, "'INT4'");
817  break;
818  case LALINFERENCE_INT8_t:
819  fprintf(stdout, "'INT8'");
820  break;
822  fprintf(stdout, "'UINT4'");
823  break;
825  fprintf(stdout, "'REAL4'");
826  break;
828  fprintf(stdout, "'REAL8'");
829  break;
831  fprintf(stdout, "'COMPLEX8'");
832  break;
834  fprintf(stdout, "'COMPLEX16'");
835  break;
837  fprintf(stdout, "'INT4Vector'");
838  break;
840  fprintf(stdout, "'UINT4Vector'");
841  break;
843  fprintf(stdout, "'REAL8Vector'");
844  break;
846  fprintf(stdout, "'gslMatrix'");
847  break;
848  default:
849  fprintf(stdout, "<unknown type>");
850  }
851  fprintf(stdout, ") ");
852  /* print value: */
853  gsl_matrix *matrix = NULL;
854  switch (ptr->type) {
855  case LALINFERENCE_INT4_t:
856  fprintf(stdout, "%d", *(INT4 *) ptr->value);
857  break;
858  case LALINFERENCE_INT8_t:
859  fprintf(stdout, "%" LAL_INT8_FORMAT, *(INT8 *) ptr->value);
860  break;
862  fprintf(stdout, "%u", *(UINT4 *) ptr->value);
863  break;
865  fprintf(stdout, "%.15lf", *(REAL4 *) ptr->value);
866  break;
868  fprintf(stdout, "%.15lf", *(REAL8 *) ptr->value);
869  break;
871  fprintf(stdout, "%e + i*%e",
872  (REAL4) crealf(*(COMPLEX8 *) ptr->value), (REAL4) cimagf(*(COMPLEX8 *) ptr->value));
873  break;
875  fprintf(stdout, "%e + i*%e",
876  (REAL8) creal(*(COMPLEX16 *) ptr->value), (REAL8) cimag(*(COMPLEX16 *) ptr->value));
877  break;
879  //fprintf(stdout,"%iD matrix", (int)((INT4Vector **)ptr->value)->size);
880  fprintf(stdout,"[");
881  fprintf(stdout,"%i]",(int)(*(INT4Vector **)ptr->value)->length);
882  break;
884  //fprintf(stdout,"%iD matrix", (int)((UINT4Vector **)ptr->value)->size);
885  fprintf(stdout,"[");
886  fprintf(stdout,"%i]",(int)(*(UINT4Vector **)ptr->value)->length);
887  break;
889  //fprintf(stdout,"%iD matrix", (int)((REAL8Vector **)ptr->value)->size);
890  fprintf(stdout,"[");
891  fprintf(stdout,"%i]",(int)(*(REAL8Vector **)ptr->value)->length);
892  break;
894  fprintf(stdout,"[");
895  matrix = *((gsl_matrix **)ptr->value);
896  fprintf(stdout,"%ix%i]",(int)(matrix->size1),(int)(matrix->size2));
897  /*
898  for(i=0; i<(int)( matrix->size1 ); i++)
899  {
900  for(j=0;j<(int)( matrix->size2 );j++)
901  {
902  fprintf(stdout,"%.2g",gsl_matrix_get(matrix, i, j));
903  if(j<(int)( matrix->size2 )-1)fprintf(stdout,",");
904  }
905  if(i<(int)( matrix->size1 )-1)fprintf(stdout,"; ");
906  }
907  fprintf(stdout,"]");
908  */
909  break;
911  fprintf(stdout,"%s",*(CHAR **)ptr->value);
912  break;
913  default:
914  fprintf(stdout, "<can't print>");
915  }
916  fprintf(stdout, "\n");
917  ptr = ptr->next;
918  }
919  }
920  return;
921 }
922 
924  UINT4 bufsize=1024;
925  char *buffer=XLALCalloc(bufsize,sizeof(char));
926  if(!buffer) XLAL_ERROR_VOID(XLAL_ENOMEM);
927  UINT4 required_size=0;
928  if(sample==NULL) return;
930  if(fp==NULL) return;
931  while(ptr!=NULL) {
932  required_size=LALInferencePrintNVariableItem(buffer,1024,ptr);
933  if(bufsize < required_size)
934  {
935  bufsize=required_size;
936  buffer=XLALRealloc(buffer,bufsize*sizeof(char));
937  if(!buffer) XLAL_ERROR_VOID(XLAL_ENOMEM);
938  required_size=LALInferencePrintNVariableItem(buffer,bufsize,ptr);
939  }
940  if (required_size>0)
941  fprintf(fp,"%s\t",buffer);
942  ptr=ptr->next;
943  }
944  XLALFree(buffer);
945  return;
946 }
947 
949  UINT4 bufsize=1024;
950  char *buffer=XLALCalloc(bufsize,sizeof(char));
951  if(!buffer) XLAL_ERROR_VOID(XLAL_ENOMEM);
952  UINT4 required_size=0;
953  if(sample==NULL) return;
955  if(fp==NULL) return;
956  while(ptr!=NULL) {
958  required_size=LALInferencePrintNVariableItem(buffer,bufsize,ptr);
959  if(bufsize < required_size)
960  {
961  bufsize=required_size;
962  buffer=XLALRealloc(buffer,bufsize*sizeof(char));
963  if(!buffer) XLAL_ERROR_VOID(XLAL_ENOMEM);
964  required_size=LALInferencePrintNVariableItem(buffer,bufsize,ptr);
965  }
966  fprintf(fp,"%s\t",buffer);
967  }
968  ptr=ptr->next;
969  }
970  XLALFree(buffer);
971  return;
972 }
973 
975  if (p == NULL || fp == NULL) return;
976  LALInferenceVariableItem *item = p->head;
977  while (item != NULL) {
978  if (item->vary != LALINFERENCE_PARAM_FIXED) {
979  switch (item->type) {
980  case LALINFERENCE_INT4_t:
981  if(1!=fscanf(fp, "%"LAL_INT4_FORMAT, (INT4 *)item->value)) XLAL_ERROR_VOID(XLAL_EIO);
982  break;
983  case LALINFERENCE_INT8_t:
984  if(1!=fscanf(fp, "%"LAL_INT8_FORMAT, (INT8 *)item->value)) XLAL_ERROR_VOID(XLAL_EIO);
985  break;
988  break;
991  break;
994  break;
995  default:
996  /* Pass on reading */
997  XLAL_ERROR_VOID(XLAL_EINVAL, "cannot read data type into LALInferenceVariables");
998  break;
999  }
1000  }
1001 
1002  item = item->next;
1003  }
1004 }
1005 
1006 /**
1007  * Utility for readling in delimited ASCII files.
1008  *
1009  * Reads in an ASCII (delimited) file, and returns the results in a REAL8 array.
1010  * @param[in] input Input stream to be parsed.
1011  * @param[in] nCols Number of total columns in the input stream.
1012  * @param[in] wantedCols Array of 0/1 flags (should be \a nCols long), indicating desired columns.
1013  * @param nLines If 0, read until end of file and set to be number of lines
1014  * read. If > 0, only read \a nLines.
1015  * @return A REAL8 array containing the parsed data.
1016  */
1017 REAL8 *LALInferenceParseDelimitedAscii(FILE *input, INT4 nCols, INT4 *wantedCols, INT4 *nLines) {
1018  INT4 nread;
1019  INT4 i=0, par=0, col=0;
1020  REAL8 val=0;
1021 
1022  // Determine the number of wanted columns
1023  INT4 nWantedCols = 0;
1024  for (col = 0; col < nCols; col++)
1025  nWantedCols += wantedCols[col];
1026 
1027  // Determine number of samples to be read
1028  unsigned long starting_pos = ftell(input);
1029  INT4 nSamples = *nLines;
1030 
1031  if (nSamples == 0) {
1032  INT4 ch;
1033  while ( (ch = getc(input)) != EOF) {
1034  if (ch=='\n')
1035  ++nSamples;
1036  }
1037  fseek(input,starting_pos,SEEK_SET);
1038  }
1039 
1040  // Read in samples
1041  REAL8 *sampleArray;
1042  sampleArray = (REAL8*) XLALMalloc(nSamples*nWantedCols*sizeof(REAL8));
1043 
1044  for (i = 0; i < nSamples; i++) {
1045  par=0;
1046  for (col = 0; col < nCols; col++) {
1047  nread = fscanf(input, "%lg", &val);
1048  if (nread != 1) {
1049  fprintf(stderr, "Cannot read sample from file (in %s, line %d)\n",
1050  __FILE__, __LINE__);
1051  exit(1);
1052  }
1053 
1054  if (wantedCols[col]) {
1055  sampleArray[i*nWantedCols + par] = val;
1056  par++;
1057  }
1058  }
1059  }
1060 
1061  *nLines = nSamples;
1062  return sampleArray;
1063 }
1064 
1065 
1066 /**
1067  * Parse a single line of delimited ASCII.
1068  *
1069  * Splits a line using \a delim into an array of strings.
1070  * @param[in] record Line to be parsed.
1071  * @param[in] delim Delimiter to split on.
1072  * @param[out] arr Parsed string.
1073  * @param[out] cnt Total number of fields read.
1074  */
1075 void parseLine(char *record, const char *delim, char arr[][VARNAME_MAX], INT4 *cnt) {
1076  // Discard newline character at end of line to avoid including it in a field
1077  char *newline = strchr(record, '\n');
1078  if (newline)
1079  *newline=0;
1080 
1081  INT4 i=0;
1082  char *p = strtok(record, delim);
1083  while (p) {
1084  strcpy(arr[i], p);
1085  i++;
1086  p = strtok(NULL, delim);
1087  }
1088  *cnt = i;
1089 }
1090 
1091 
1092 /**
1093  * Discard the standard header of a PTMCMC chain file.
1094  *
1095  * Reads a PTMCMC input stream, moving foward until it finds a line beginning
1096  * with "cycle", which is typically the line containing the column names of a
1097  * PTMCMC output file. The final stream points to the line containing the
1098  * column names.
1099  * @param filestream The PTMCMC input stream to discard the header of.
1100  */
1101 void LALInferenceDiscardPTMCMCHeader(FILE *filestream) {
1102  char *str = XLALCalloc(STR_MAX, sizeof(char));
1103  char row[COL_MAX][VARNAME_MAX];
1104  const char *delimiters = " \t";
1105  INT4 nCols;
1106  INT4 last_line = 0;
1107 
1108  if(!fgets(str, sizeof(str), filestream)) XLAL_ERROR_VOID(XLAL_EIO);
1109  parseLine(str, delimiters, row, &nCols);
1110  while (strcmp(row[0], "cycle") && str != NULL) {
1111  last_line = ftell(filestream);
1112  if(!fgets(str, sizeof(str), filestream)) XLAL_ERROR_VOID(XLAL_EIO);
1113  parseLine(str, delimiters, row, &nCols);
1114  }
1115 
1116  if (str == NULL) {
1117  fprintf(stderr, "Couldn't find column headers in PTMCMC file.\n");
1118  exit(1);
1119  } else {
1120  XLALFree(str);
1121  }
1122 
1123  fseek(filestream, last_line, SEEK_SET);
1124  return;
1125 }
1126 
1127 
1128 /**
1129  * Determine burnin cycle from delta-logl criteria.
1130  *
1131  * Find the cycle where the log(likelihood) is within nPar/2 of the
1132  * maximum log(likelihood) sampled by the chain.
1133  * @param filestream The PTMCMC input stream to be burned in.
1134  * @param[in] logl_idx The column containing logl values.
1135  * @param nPar UNDOCUMENTED
1136  */
1137 void LALInferenceBurninPTMCMC(FILE *filestream, INT4 logl_idx, INT4 nPar) {
1138  char *str = XLALCalloc(STR_MAX, sizeof(char));
1139  char row[COL_MAX][VARNAME_MAX];
1140  const char *delimiters = " \t";
1141  INT4 nCols;
1142  REAL8 loglike, maxLogL=-INFINITY;
1143 
1144  // Determine number of samples to be read
1145  unsigned long startPostBurnin = ftell(filestream);
1146 
1147  /* One pass to find max logl */
1148  while (fgets(str, sizeof(str), filestream) != NULL) {
1149  parseLine(str, delimiters, row, &nCols);
1150  loglike = (REAL8) atof(row[logl_idx]);
1151  if (loglike > maxLogL)
1152  maxLogL = loglike;
1153  }
1154 
1155  /* Reset stream */
1156  fseek(filestream, startPostBurnin, SEEK_SET);
1157 
1158  /* Assume nCol = nPar. Burnin can be crude */
1159  REAL8 deltaLogL = maxLogL - (REAL8)nPar/2.0;
1160 
1161  /* Find the cycle where logl gets within nPar/2 of max */
1162  while (fgets(str, sizeof(str), filestream) != NULL) {
1163  parseLine(str, delimiters, row, &nCols);
1164  loglike = (REAL8) atof(row[logl_idx]);
1165  if (loglike > deltaLogL)
1166  break;
1167  }
1168 
1169  if (str == NULL) {
1170  fprintf(stderr, "Error burning in PTMCMC file.\n");
1171  exit(1);
1172  } else {
1173  XLALFree(str);
1174  }
1175 }
1176 
1177 
1178 /**
1179  * Burn-in a generic ASCII stream.
1180  *
1181  * Reads past the desired number of lines of a filestream.
1182  * @param filestream The filestream to be burned in.
1183  * @param[in] burnin Number of lines to read past in \a filestream.
1184  */
1185 void LALInferenceBurninStream(FILE *filestream, INT4 burnin) {
1186  char *str = XLALCalloc(STR_MAX, sizeof(char));
1187  INT4 i=0;
1188 
1189  for (i=0; i<burnin; i++)
1190  if(!fgets(str, sizeof(str), filestream)) XLAL_ERROR_VOID(XLAL_EIO);
1191 
1192  if (str == NULL) {
1193  if (burnin > 0) {
1194  fprintf(stderr, "Error burning in file.\n");
1195  exit(1);
1196  }
1197  } else {
1198  XLALFree(str);
1199  }
1200 }
1201 
1202 /**
1203  * Read column names from an ASCII file.
1204  *
1205  * Reads the column names for an output file.
1206  * @param[in] input The input files stream to parse.
1207  * @param[out] params The column names found in the header.
1208  * @param[out] nCols Number of columns found in the header.
1209  */
1210 void LALInferenceReadAsciiHeader(FILE *input, char params[][VARNAME_MAX], INT4 *nCols) {
1211  INT4 i;
1212  char *str = XLALCalloc(STR_MAX, sizeof(char));
1213  char row[COL_MAX][VARNAME_MAX];
1214  const char *delimiters = " \n\t";
1215  INT4 col_count=0;
1216 
1217  if(!fgets(str, sizeof(str), input)) XLAL_ERROR_VOID(XLAL_EIO);
1218  parseLine(str, delimiters, row, &col_count);
1219 
1220  for (i=0; i<col_count; i++)
1221  strcpy(params[i], row[i]);
1222 
1223  *nCols = col_count;
1224  XLALFree(str);
1225 }
1226 
1227 
1228 /**
1229  * Utility for selecting columns from an array, in the specified order.
1230  *
1231  * Selects a subset of columns from an existing array and create a new array with them.
1232  * @param[in] inarray The array to select columns from.
1233  * @param[in] nRows Number of rows in \a inarray.
1234  * @param[in] nCols Number of columns in \a inarray.
1235  * @param[in] nSelCols Number of columns being extracted.
1236  * @param[in] selCols Array of column numbers to be extracted from \a inarray.
1237  * @returns An array containing the requested columns in the order specified in \a selCols.
1238  */
1239 REAL8 **LALInferenceSelectColsFromArray(REAL8 **inarray, INT4 nRows, INT4 nCols, INT4 nSelCols, INT4 *selCols) {
1240  INT4 i,j;
1241 
1242  REAL8 **array = (REAL8**) XLALMalloc(nRows * sizeof(REAL8*));
1243  for (i = 0; i < nRows; i++) {
1244  array[i] = XLALMalloc(nSelCols * sizeof(REAL8));
1245 
1246  for (j = 0; j < nSelCols; j++) {
1247  if (selCols[j] > nCols) {
1248  XLAL_ERROR_NULL(XLAL_FAILURE, "Requesting a column number that is out of bounds.");
1249  }
1250  array[i][j] = inarray[i][selCols[j]];
1251  }
1252  }
1253  return array;
1254 }
1255 
1257  INT4 i;
1258 
1259  for (i=0; i<cycle->nProposals; i++)
1260  fprintf(fp, "%s\t", cycle->proposals[i]->name);
1261 
1262  fprintf(fp, "\n");
1263 
1264  return 0;
1265 }
1266 
1268  INT4 i;
1269  REAL8 accepted = 0;
1270  REAL8 proposed = 0;
1271  REAL8 acceptanceRate = 0;
1272 
1273  if(cycle==NULL || fp==NULL)
1274  return;
1275 
1276  for (i=0; i<cycle->nProposals; i++) {
1277  accepted = (REAL8) cycle->proposals[i]->accepted;
1278  proposed = (REAL8) cycle->proposals[i]->proposed;
1279  acceptanceRate = accepted/(proposed==0 ? 1.0 : proposed);
1280  fprintf(fp, "%9.5f\t", acceptanceRate);
1281  }
1282 
1283  fprintf(fp, "\n");
1284  return;
1285 }
1286 
1287 const char *LALInferenceTranslateInternalToExternalParamName(const char *inName) {
1288  if (!strcmp(inName, "a_spin1")) {
1289  return "a1";
1290  } else if (!strcmp(inName, "a_spin2")) {
1291  return "a2";
1292  } else if (!strcmp(inName, "tilt_spin1")) {
1293  return "tilt1";
1294  } else if (!strcmp(inName, "tilt_spin2")) {
1295  return "tilt2";
1296  } else if (!strcmp(inName, "chirpmass")) {
1297  return "mc";
1298  } else if (!strcmp(inName, "eta")) {
1299  return "eta";
1300  } else if (!strcmp(inName, "q")) {
1301  return "q";
1302  } else if (!strcmp(inName, "rightascension")) {
1303  return "ra";
1304  } else if (!strcmp(inName, "declination")) {
1305  return "dec";
1306  } else if (!strcmp(inName, "phase")) {
1307  return "phi_orb";
1308  } else if (!strcmp(inName, "polarisation")) {
1309  return "psi";
1310  } else if (!strcmp(inName, "distance")) {
1311  return "dist";
1312  } else if (!strcmp(inName, "polar_angle")) {
1313  return "alpha";
1314  } else {
1315  return inName;
1316  }
1317 }
1318 
1319 void LALInferenceTranslateExternalToInternalParamName(char *outName, const char *inName) {
1320  if (!strcmp(inName, "a1")) {
1321  strcpy(outName, "a_spin1");
1322  } else if (!strcmp(inName, "a2")) {
1323  strcpy(outName, "a_spin2");
1324  } else if (!strcmp(inName, "tilt1")) {
1325  strcpy(outName, "tilt_spin1");
1326  } else if (!strcmp(inName, "tilt2")) {
1327  strcpy(outName, "tilt_spin2");
1328  } else if (!strcmp(inName, "mc")) {
1329  strcpy(outName, "chirpmass");
1330  } else if (!strcmp(inName, "eta")) {
1331  strcpy(outName, "eta");
1332  } else if (!strcmp(inName, "q")) {
1333  strcpy(outName, "q");
1334  } else if (!strcmp(inName, "ra")) {
1335  strcpy(outName, "rightascension");
1336  } else if (!strcmp(inName, "dec")) {
1337  strcpy(outName, "declination");
1338  } else if (!strcmp(inName, "phi_orb")) {
1339  strcpy(outName, "phase");
1340  } else if (!strcmp(inName, "psi")) {
1341  strcpy(outName, "polarisation");
1342  } else if (!strcmp(inName, "theta_jn")) {
1343  strcpy(outName, "theta_jn");
1344  } else if (!strcmp(inName, "phi_jl")) {
1345  strcpy(outName, "phi_jl");
1346  } else if (!strcmp(inName, "dist")) {
1347  strcpy(outName, "distance");
1348  } else if (!strcmp(inName, "alpha")) {
1349  strcpy(outName, "polar_angle");
1350  } else {
1351  strcpy(outName, inName);
1352  }
1353 }
1354 
1355 
1358  int i;//,j;
1359  //gsl_matrix *matrix = NULL;
1360 
1361  while (head != NULL) {
1362  if(head->type==LALINFERENCE_gslMatrix_t)
1363  {
1364  //Commented out since for now gsl matrices are used as nuisance parameters and not printed to the output files.
1365  //We may implement a LALINFERENCE_PARAM_NUISANCE type
1366  //matrix = *((gsl_matrix **)head->value);
1367  //for(i=0; i<(int)matrix->size1; i++)
1368  //{
1369  // for(j=0; j<(int)matrix->size2; j++)
1370  // {
1371  // fprintf(out, "%s%i%i\t", LALInferenceTranslateInternalToExternalParamName(head->name),i,j);
1372  // }
1373  //}
1374  }
1375  else if(head->type==LALINFERENCE_UINT4Vector_t)
1376  {
1377  UINT4Vector *vector = NULL;
1378  vector = *((UINT4Vector **)head->value);
1379  for(i=0; i<(int)vector->length; i++) fprintf(out, "%s%i\t", LALInferenceTranslateInternalToExternalParamName(head->name),i);
1380  }
1381  else if(head->type==LALINFERENCE_INT4Vector_t)
1382  {
1383  INT4Vector *vector = NULL;
1384  vector = *((INT4Vector **)head->value);
1385  for(i=0; i<(int)vector->length; i++) fprintf(out, "%s%i\t", LALInferenceTranslateInternalToExternalParamName(head->name),i);
1386  }
1387  else if(head->type==LALINFERENCE_REAL8Vector_t)
1388  {
1389  REAL8Vector *vector = *(REAL8Vector **)head->value;
1390  for(i=0;i<(int)vector->length;i++) fprintf(out,"%s%i\t",LALInferenceTranslateInternalToExternalParamName(head->name),i);
1391  }
1393  head = head->next;
1394  }
1395  return 0;
1396 }
1397 
1400 
1401  int i;//,j;
1402  //gsl_matrix *matrix = NULL;
1403  while (head != NULL) {
1405  if(head->type==LALINFERENCE_gslMatrix_t)
1406  {
1407  /*
1408  fprintf(stdout,"\n");
1409  fprintf(stdout,"Skipping noise/glitch amplitudes in output files\n");
1410  fprintf(stdout," edit LALInferenceFprintParameterNonFixedHeaders()\n");
1411  fprintf(stdout," and LALInferencePrintSampleNonFixed() to modify\n");
1412  */
1413  /*
1414  matrix = *((gsl_matrix **)head->value);
1415  for(i=0; i<(int)matrix->size1; i++)
1416  {
1417  for(j=0; j<(int)matrix->size2; j++)
1418  {
1419  fprintf(out, "%s%i%i\t", LALInferenceTranslateInternalToExternalParamName(head->name),i,j);
1420  }
1421  }
1422  */
1423  }
1424  else if(head->type==LALINFERENCE_UINT4Vector_t)
1425  {
1426  UINT4Vector *vector = NULL;
1427  vector = *((UINT4Vector **)head->value);
1428  for(i=0; i<(int)vector->length; i++) fprintf(out, "%s%i\t", LALInferenceTranslateInternalToExternalParamName(head->name),i);
1429  }
1430  else if(head->type==LALINFERENCE_INT4Vector_t)
1431  {
1432  INT4Vector *vector = NULL;
1433  vector = *((INT4Vector **)head->value);
1434  for(i=0; i<(int)vector->length; i++) fprintf(out, "%s%i\t", LALInferenceTranslateInternalToExternalParamName(head->name),i);
1435  }
1436  else if(head->type==LALINFERENCE_REAL8Vector_t)
1437  {
1438  REAL8Vector *vector = *(REAL8Vector **)head->value;
1439  for(i=0;i<(int)vector->length;i++) fprintf(out,"%s%i\t",LALInferenceTranslateInternalToExternalParamName(head->name),i);
1440  }
1442  }
1443  head = head->next;
1444  }
1445 
1446  return 0;
1447 }
1448 
1451 
1452  INT4 i,j;
1453  gsl_matrix *matrix = NULL;
1454 
1455  while (head != NULL) {
1456  if (head->vary != LALINFERENCE_PARAM_FIXED) {
1457  if(head->type==LALINFERENCE_gslMatrix_t)
1458  {
1459  matrix = *((gsl_matrix **)head->value);
1460  for(i=0; i<(int)matrix->size1; i++)
1461  {
1462  for(j=0; j<(int)matrix->size2; j++)
1463  {
1464  fprintf(out, "%s_%s%i%i\t", LALInferenceTranslateInternalToExternalParamName(head->name),suffix,i,j);
1465  }
1466  }
1467  }
1468  else fprintf(out, "%s_%s\t", LALInferenceTranslateInternalToExternalParamName(head->name), suffix);
1469  }
1470  head = head->next;
1471  }
1472 
1473  return 0;
1474 }
1475 
1477 /* Compare contents of "var1" and "var2". */
1478 /* Returns zero for equal entries, and one if difference found. */
1479 /* Make sure to only call this function when all entries are */
1480 /* actually comparable. For example, "gslMatrix" type entries */
1481 /* cannot (yet?) be checked for equality. */
1482 {
1483  /* Short-circuit for pointer equality */
1484  if (var1 == var2) return 0;
1485 
1486  /* Short-circuit if passed NULL pointers */
1487  if ((var1 == NULL) || (var2 == NULL))
1488  {
1489  XLALPrintWarning("LALInferenceCompareVariables received a NULL input pointer\n");
1490  return 1;
1491  }
1492 
1493  int result = 0;
1494  UINT4 i;
1495  LALInferenceVariableItem *ptr1 = var1->head;
1496  LALInferenceVariableItem *ptr2 = NULL;
1497  if (var1->dimension != var2->dimension) result = 1; // differing dimension
1498  while ((ptr1 != NULL) && (result == 0)) {
1499  ptr2 = LALInferenceGetItem(var2, ptr1->name);
1500  if (ptr2 != NULL) { // corrsesponding entry exists; now compare type, then value:
1501  if (ptr2->type == ptr1->type) { // entry type identical
1502  switch (ptr1->type) { // do value comparison depending on type:
1503  case LALINFERENCE_INT4_t:
1504  result = ((*(INT4 *) ptr2->value) != (*(INT4 *) ptr1->value));
1505  break;
1506  case LALINFERENCE_INT8_t:
1507  result = ((*(INT8 *) ptr2->value) != (*(INT8 *) ptr1->value));
1508  break;
1509  case LALINFERENCE_UINT4_t:
1510  result = ((*(UINT4 *) ptr2->value) != (*(UINT4 *) ptr1->value));
1511  break;
1512  case LALINFERENCE_REAL4_t:
1513  result = ((*(REAL4 *) ptr2->value) != (*(REAL4 *) ptr1->value));
1514  break;
1515  case LALINFERENCE_REAL8_t:
1516  result = ((*(REAL8 *) ptr2->value) != (*(REAL8 *) ptr1->value));
1517  break;
1519  result = (((REAL4) crealf(*(COMPLEX8 *) ptr2->value) != (REAL4) crealf(*(COMPLEX8 *) ptr1->value))
1520  || ((REAL4) cimagf(*(COMPLEX8 *) ptr2->value) != (REAL4) cimagf(*(COMPLEX8 *) ptr1->value)));
1521  break;
1523  result = (((REAL8) creal(*(COMPLEX16 *) ptr2->value) != (REAL8) creal(*(COMPLEX16 *) ptr1->value))
1524  || ((REAL8) cimag(*(COMPLEX16 *) ptr2->value) != (REAL8) cimag(*(COMPLEX16 *) ptr1->value)));
1525  break;
1527  if( matrix_equal(*(gsl_matrix **)ptr1->value,*(gsl_matrix **)ptr2->value) )
1528  result = 0;
1529  else
1530  result = 1;
1531  break;
1533  {
1534  REAL8Vector *v1=*(REAL8Vector **)ptr1->value;
1535  REAL8Vector *v2=*(REAL8Vector **)ptr2->value;
1536  if(v1->length!=v2->length) result=1;
1537  else
1538  for(i=0;i<v1->length;i++)
1539  {
1540  if(v1->data[i]!=v2->data[i]){
1541  result=1;
1542  break;
1543  }
1544  }
1545  break;
1546  }
1548  {
1549  UINT4Vector *v1=*(UINT4Vector **)ptr1->value;
1550  UINT4Vector *v2=*(UINT4Vector **)ptr2->value;
1551  if(v1->length!=v2->length) result=1;
1552  else
1553  for(i=0;i<v1->length;i++)
1554  {
1555  if(v1->data[i]!=v2->data[i]){
1556  result=1;
1557  break;
1558  }
1559  }
1560  break;
1561  }
1563  {
1564  INT4Vector *v1=*(INT4Vector **)ptr1->value;
1565  INT4Vector *v2=*(INT4Vector **)ptr2->value;
1566  if(v1->length!=v2->length) result=1;
1567  else
1568  for(i=0;i<v1->length;i++)
1569  {
1570  if(v1->data[i]!=v2->data[i]){
1571  result=1;
1572  break;
1573  }
1574  }
1575  break;
1576  }
1577  default:
1578  XLAL_ERROR(XLAL_EFAILED, "Encountered unknown LALInferenceVariables type (entry: \"%s\").", ptr1->name);
1579  }
1580  }
1581  else result = 1; // same name but differing type
1582  }
1583  else result = 1; // entry of given name doesn't exist in var2
1584  ptr1 = ptr1->next;
1585  }
1586  return(result);
1587 }
1588 
1589 
1590 /* Move every *step* entry from the buffer to an array */
1593  INT4 i=0, p=0;
1594 
1595  INT4 nPoints = thread->differentialPointsLength;
1596  for (i = 0; i < nPoints; i+=step) {
1597  ptr=thread->differentialPoints[i]->head;
1598  p=0;
1599  while(ptr!=NULL) {
1601  DEarray[i/step][p]=*(REAL8 *)ptr->value;
1602  p++;
1603  }
1604  ptr=ptr->next;
1605  }
1606  }
1607 
1608  return nPoints/step;
1609 }
1610 
1611 
1612 /* Move the entire buffer to an array */
1614  INT4 step = 1;
1615  return LALInferenceThinnedBufferToArray(thread, DEarray, step);
1616 }
1617 
1618 
1620  gsl_matrix *m = NULL; //for dealing with noise parameters
1621  REAL8Vector *v8 = NULL;
1622  UINT4 j,k;
1623 
1624  /* Make sure the structure is initialised */
1625  if (!target) XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to copy to uninitialised array.");
1626 
1628  INT4 p=0;
1629  while(ptr!=NULL) {
1630  if (LALInferenceCheckVariableNonFixed(origin, ptr->name)) {
1631  //Generalized to allow for parameters stored in gsl_matrix or UINT4Vector
1633  {
1634  m = *((gsl_matrix **)ptr->value);
1635  for(j=0; j<m->size1; j++)
1636  {
1637  for(k=0; k<m->size2; k++)
1638  {
1639  target[p]=gsl_matrix_get(m,j,k);
1640  p++;
1641  }
1642  }
1643  }
1644  else if(ptr->type == LALINFERENCE_UINT4Vector_t)
1645  {
1646  UINT4Vector *v = NULL;
1647  v = *(UINT4Vector **)ptr->value;
1648  for(j=0; j<v->length; j++)
1649  {
1650  target[p]=v->data[j];
1651  p++;
1652  }
1653  }
1654  else if(ptr->type == LALINFERENCE_INT4Vector_t)
1655  {
1656  INT4Vector *v = NULL;
1657  v = *(INT4Vector **)ptr->value;
1658  for(j=0; j<v->length; j++)
1659  {
1660  target[p]=v->data[j];
1661  p++;
1662  }
1663  }
1664  else if(ptr->type == LALINFERENCE_REAL8Vector_t)
1665  {
1666  v8 = *(REAL8Vector **)ptr->value;
1667  for (j = 0; j < v8->length; j++) {
1668  target[p]=v8->data[j];
1669  p++;
1670  }
1671  }
1673  XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to copy complex variables to real array.");
1674  }
1675  else
1676  {
1677  target[p]=*(REAL8 *)ptr->value;
1678  p++;
1679  }
1680  }
1681  ptr=ptr->next;
1682  }
1683 }
1684 
1686  gsl_matrix *m = NULL; //for dealing with noise parameters
1687  REAL8Vector *v8 = NULL;
1688  COMPLEX16Vector *v16 = NULL;
1689  UINT4 j,k;
1690 
1691  LALInferenceVariableItem *ptr = target->head;
1692  INT4 p=0;
1693  while(ptr!=NULL) {
1694  if (LALInferenceCheckVariableNonFixed(target, ptr->name))
1695  {
1696  //Generalized to allow for parameters stored in gsl_matrix
1698  {
1699  m = *((gsl_matrix **)ptr->value);
1700  for(j=0; j<m->size1; j++)
1701  {
1702  for(k=0; k<m->size2; k++)
1703  {
1704  gsl_matrix_set(m,j,k,origin[p]);
1705  p++;
1706  }
1707  }
1708  }
1709  else if(ptr->type == LALINFERENCE_UINT4Vector_t)
1710  {
1711  UINT4Vector *v = NULL; //for dealing with dimension parameters
1712  v = *(UINT4Vector **)ptr->value;
1713  for(j=0; j<v->length; j++)
1714  {
1715  v->data[j] = origin[p];
1716  p++;
1717  }
1718  }
1719  else if(ptr->type == LALINFERENCE_INT4Vector_t)
1720  {
1721  INT4Vector *v = NULL; //for dealing with dimension parameters
1722  v = *(INT4Vector **)ptr->value;
1723  for(j=0; j<v->length; j++)
1724  {
1725  v->data[j] = origin[p];
1726  p++;
1727  }
1728  }
1729  else if(ptr->type == LALINFERENCE_REAL8Vector_t)
1730  {
1731  v8 = *(REAL8Vector **)ptr->value;
1732  for (j=0; j < v8->length; j++)
1733  {
1734  v8->data[j] = origin[p];
1735  p++;
1736  }
1737  }
1739  {
1740  v16 = *(COMPLEX16Vector **)ptr->value;
1741  for (j=0; j < v16->length; j++)
1742  {
1743  v16->data[j] = origin[p];
1744  p++;
1745  }
1746  }
1747  else
1748  {
1749  memcpy(ptr->value,&(origin[p]),LALInferenceTypeSize[ptr->type]);
1750  p++;
1751  }
1752  }
1753  ptr=ptr->next;
1754  }
1755  return;
1756 }
1757 
1758 /* ============ Command line parsing functions etc.: ========== */
1759 
1760 
1761 
1763 /* Returns pointer to element "name" of the ProcessParamsTable, */
1764 /* if present, and NULL otherwise. */
1765 {
1766  ProcessParamsTable *this=procparams;
1767 
1768  if (this==NULL) {
1769  fprintf(stderr, " Warning: ProcessParamsTable is a NULL pointer\n");
1770  exit(1);
1771  }
1772 
1773  while (this!=NULL) {
1774  if (!strcmp(this->param, name)) break;
1775  else this=this->next;
1776  }
1777 
1778  return(this);
1779 }
1780 
1781 
1782 
1783 void LALInferenceParseCharacterOptionString(char *input, char **strings[], UINT4 *n)
1784 /* parses a character string (passed as one of the options) and decomposes */
1785 /* it into individual parameter character strings. Input is of the form */
1786 /* input : "[one,two,three]" */
1787 /* and the resulting output is */
1788 /* strings : {"one", "two", "three"} */
1789 /* length of parameter names is for now limited to 512 characters. */
1790 /* (should 'theoretically' (untested) be able to digest white space as well. */
1791 /* Irrelevant for command line options, though.) */
1792 {
1793  UINT4 i,j,k,l;
1794  /* perform a very basic well-formedness-check and count number of parameters: */
1795  i=0; j=0;
1796  *n = 0;
1797  while (input[i] != '\0') {
1798  if ((j==0) & (input[i]=='[')) j=1;
1799  if ((j==1) & (input[i]==',')) ++*n;
1800  if ((j==1) & (input[i]==']')) {++*n; j=2;}
1801  ++i;
1802  }
1803  if (j!=2) XLAL_ERROR_VOID(XLAL_EINVAL, "Argument vector \"%s\" is not well-formed!", input);
1804  /* now allocate memory for results: */
1805  *strings = (char**) XLALMalloc(sizeof(char*) * (*n));
1806  for (i=0; i<(*n); ++i) (*strings)[i] = (char*) XLALMalloc(sizeof(char)*512);
1807  i=0; j=0;
1808  k=0; /* string counter */
1809  l=0; /* character counter */
1810  while ((input[i] != '\0') & (j<3)) {
1811  /* state transitions: */
1812  if ((j==0) & ((input[i]!='[') & (input[i]!=' '))) j=1;
1813  if (((j==1)|(j==2)) & (input[i]==',')) {(*strings)[k][l]='\0'; j=2; ++k; l=0;}
1814  if ((j==1) & (input[i]==' ')) j=2;
1815  if ((j==1) & (input[i]==']')) {(*strings)[k][l]='\0'; j=3;}
1816  if ((j==2) & (input[i]==']')) {(*strings)[k][l]='\0'; j=3;}
1817  if ((j==2) & ((input[i]!=']') & (input[i]!=',') & (input[i]!=' '))) j=1;
1818  /* actual copying: */
1819  if (j==1) {
1820  if (l>=511) {
1821  XLAL_PRINT_WARNING("Character \"%s\" argument too long!", (*strings)[k]);
1822  }
1823  else {
1824  (*strings)[k][l] = input[i];
1825  ++l;
1826  }
1827  }
1828  ++i;
1829  }
1830 }
1831 
1833 {
1835  for(int i=0;i<argc;i++)
1836  {
1838  }
1841  return(ppt);
1842 }
1843 
1845 /* parse command line and set up & fill in 'ProcessParamsTable' linked list. */
1846 /* If no command line arguments are supplied, the 'ProcessParamsTable' still contains */
1847 /* one empty entry. */
1848 {
1849  int i, state=1;
1850  int argc = arglist->length;
1851  int dbldash;
1852  char **argv = arglist->data;
1853  ProcessParamsTable *head, *ptr=NULL;
1854  /* always (even for argc==1, i.e. no arguments) put one element in list: */
1856  XLALStringCopy(head->program, argv[0], sizeof(CHAR)*LIGOMETA_PROGRAM_MAX);
1857  ptr = head;
1858  i=1;
1859  while ((i<argc) & (state<=3)) {
1860  /* check for a double-dash at beginning of argument #i: */
1861  dbldash = ((argv[i][0]=='-') && (argv[i][1]=='-'));
1862  /* react depending on current state: */
1863  if (state==1){ /* ('state 1' means handling very 1st argument) */
1864  if (dbldash) {
1865  XLALStringCopy(head->param, argv[i], sizeof(CHAR)*LIGOMETA_PARAM_MAX);
1866  XLALStringCopy(ptr->type, "string", sizeof(CHAR)*LIGOMETA_TYPE_MAX);
1867  state = 2;
1868  }
1869  else { /* (very 1st argument needs to start with "--...") */
1870  // TODO: Perhaps this should be a warning?
1871  XLAL_ERROR_NULL(XLAL_EINVAL, "Orphaned first command line argument: \"%s\".", argv[i]);
1872  state = 4;
1873  }
1874  }
1875  else if (state==2) { /* ('state 2' means last entry was a parameter starting with "--") */
1876  if (dbldash) {
1878  ptr = ptr->next;
1879  XLALStringCopy(ptr->program, argv[0],
1880 sizeof(CHAR)*LIGOMETA_PROGRAM_MAX);
1881  XLALStringCopy(ptr->param, argv[i], sizeof(CHAR)*LIGOMETA_PARAM_MAX);
1882  XLALStringCopy(ptr->type, "string", sizeof(CHAR)*LIGOMETA_TYPE_MAX);
1883  }
1884  else {
1885  state = 3;
1886  XLALStringCopy(ptr->value, argv[i], sizeof(CHAR)*LIGOMETA_VALUE_MAX);
1887  }
1888  }
1889  else if (state==3) { /* ('state 3' means last entry was a value) */
1890  if (dbldash) {
1892  ptr = ptr->next;
1893  XLALStringCopy(ptr->program, argv[0],
1894  sizeof(CHAR)*LIGOMETA_PROGRAM_MAX);
1895  XLALStringCopy(ptr->param, argv[i], sizeof(CHAR)*LIGOMETA_PARAM_MAX);
1896  XLALStringCopy(ptr->type, "string", sizeof(CHAR)*LIGOMETA_TYPE_MAX);
1897  state = 2;
1898  }
1899  else {
1900  // TODO: Perhaps this should be a warning?
1901  XLAL_ERROR_NULL(XLAL_EINVAL, "Orphaned last command line argument: \"%s\".", argv[i]);
1902  state = 4;
1903  }
1904  }
1905  ++i;
1906  }
1907 
1908  return head;
1909 }
1910 
1912  /* Version of the below function which can be easily exposed to Python via SWIG. */
1913  return LALInferenceParseCommandLine(args->length,args->data);
1914 }
1915 
1917 {
1918  ProcessParamsTable *this=procparams;
1919  INT8 len=14; //number of characters of the "Command line: " string.
1920  while (this!=NULL) {
1921  len+=strlen(this->param);
1922  len+=strlen(this->value);
1923  len+=2;
1924  this=this->next;
1925  }// Now we know how long the buffer has to be.
1926  char * str = (char*) XLALCalloc(len+1,sizeof(char));
1927  if (str==NULL) {
1928  XLALPrintError("Calloc error, str is NULL (in %s, line %d)\n",__FILE__, __LINE__);
1930  }
1931 
1932  this=procparams;
1933  strcpy (str,"Command line: ");
1934  //strcat (str,this->program);
1935  while (this!=NULL) {
1936  strcat (str," ");
1937  strcat (str,this->param);
1938  strcat (str," ");
1939  strcat (str,this->value);
1940  this=this->next;
1941  }
1942  return str;
1943 }
1944 
1946 /* Execute (forward, time-to-freq) Fourier transform. Contents of
1947 model->timeh... are windowed and FT'ed, results go into
1948 model->freqh...
1949 
1950 NOTE: the windowing is performed *in-place*, so do not call more than
1951 once on a given timeModel!
1952 */
1953 {
1954  UINT4 i;
1955  double norm;
1956  int errnum;
1957 
1958  if (model==NULL) {
1959  fprintf(stderr," ERROR: model is a null pointer at LALInferenceExecuteFT, exiting!.\n");
1961  }
1962 
1963  if(!model->freqhPlus && !model->timehPlus){
1964  XLALPrintError("freqhPlus and timeqhPlus are NULL at LALInferenceExecuteFT, exiting!");
1966  }
1967  else if(!model->freqhCross && !model->timehCross){
1968  XLALPrintError("freqhCross and timeqhCross are NULL at LALInferenceExecuteFT, exiting!");
1970  }
1971 
1972  /* h+ */
1973  if(!model->freqhPlus){
1975 
1976  if (errnum){
1977  XLALPrintError("Could not create COMPLEX16FrequencySeries in LALInferenceExecuteFT");
1978  XLAL_ERROR_VOID(errnum);
1979  }
1980  }
1981 
1982  if (!model->window || !model->window->data){
1983  XLALPrintError("model->window is NULL at LALInferenceExecuteFT: Exiting!");
1985  }
1986 
1987  XLAL_TRY(XLALDDVectorMultiply(model->timehPlus->data, model->timehPlus->data, model->window->data), errnum);
1988 
1989  if (errnum){
1990  XLALPrintError("Could not window time-series in LALInferenceExecuteFT");
1991  XLAL_ERROR_VOID(errnum);
1992  }
1993 
1994  if (!model->timeToFreqFFTPlan){
1995  XLALPrintError("model->timeToFreqFFTPlan is NULL at LALInferenceExecuteFT: Exiting!");
1997  }
1998 
1999  XLAL_TRY(XLALREAL8TimeFreqFFT(model->freqhPlus, model->timehPlus, model->timeToFreqFFTPlan), errnum);
2000 
2001  if (errnum){
2002  XLALPrintError("Could not h_plus FFT time-series");
2003  XLAL_ERROR_VOID(errnum);
2004  }
2005 
2006  /* hx */
2007  if(!model->freqhCross){
2009 
2010  if (errnum){
2011  XLALPrintError("Could not create COMPLEX16FrequencySeries in LALInferenceExecuteFT");
2012  XLAL_ERROR_VOID(errnum);
2013  }
2014  }
2015 
2016  XLAL_TRY(XLALDDVectorMultiply(model->timehCross->data, model->timehCross->data, model->window->data), errnum);
2017 
2018  if (errnum){
2019  XLALPrintError("Could not window time-series in LALInferenceExecuteFT");
2020  XLAL_ERROR_VOID(errnum);
2021  }
2022 
2023  XLAL_TRY(XLALREAL8TimeFreqFFT(model->freqhCross, model->timehCross, model->timeToFreqFFTPlan), errnum);
2024 
2025  if (errnum){
2026  XLALPrintError("Could not FFT h_cross time-series");
2027  XLAL_ERROR_VOID(errnum);
2028  }
2029 
2030  norm=sqrt(model->window->data->length/model->window->sumofsquares);
2031 
2032  for(i=0;i<model->freqhPlus->data->length;i++){
2033  model->freqhPlus->data->data[i] *= ((REAL8) norm);
2034  model->freqhCross->data->data[i] *= ((REAL8) norm);
2035  }
2036 }
2037 
2039 /* Execute inverse (freq-to-time) Fourier transform. */
2040 /* Results go into 'model->timeh...' */
2041 {
2042  if (model->freqToTimeFFTPlan==NULL) {
2043  XLAL_ERROR_VOID(XLAL_EFAULT, "Encountered unallocated \"freqToTimeFFTPlan\".");
2044  }
2045 
2046  /* h+ : */
2047  if (model->timehPlus==NULL) {
2048  XLAL_ERROR_VOID(XLAL_EFAULT, "Encountered unallocated \"timehPlus\".");
2049  }
2050  if (model->freqhPlus==NULL) {
2051  XLAL_ERROR_VOID(XLAL_EFAULT, "Encountered unallocated \"freqhPlus\".");
2052  }
2053 
2055 
2056  /* hx : */
2057  if (model->timehCross==NULL) {
2058  XLAL_ERROR_VOID(XLAL_EFAULT, "Encountered unallocated \"timehCross\".");
2059  }
2060  if (model->freqhCross==NULL) {
2061  XLAL_ERROR_VOID(XLAL_EFAULT, "Encountered unallocated \"freqhCross\".");
2062  }
2063 
2065 }
2066 
2068  size_t i;
2069 
2070  for (i = 0; headers[i] != NULL; i++) {
2071  double param;
2072  int nread;
2073 
2074  nread = fscanf(inp, " %lg ", &param);
2075  if (nread != 1) {
2076  XLAL_ERROR_VOID(XLAL_EFAILED, "Could not read the value of the %zu parameter in the row.", i);
2077  }
2078 
2080  }
2081 }
2082 
2083 /* This function has a Memory Leak! You cannot free the allocated
2084  header buffer (of length MAXSIZE). Don't call it too many times!
2085  (It's only expected to be called once to initialize the
2086  differential evolution array, so this should be OK. */
2087 char **LALInferenceGetHeaderLine(FILE *inp) {
2088  const size_t MAXSIZE=1024;
2089  const char *delimiters = " \n\t";
2090  char *header = XLALMalloc(MAXSIZE*sizeof(char));
2091  char **colNames = NULL; /* Will be filled in with the column names,
2092  terminated by NULL. */
2093  size_t colNamesLen=0, colNamesMaxLen=0;
2094  char *colName = NULL;
2095 
2096  if (!fgets(header, MAXSIZE, inp)) {
2097  /* Some error.... */
2098  XLAL_ERROR_NULL(XLAL_EFAILED, "Error reading header line from file.");
2099  } else if (strlen(header) >= MAXSIZE-1) {
2100  /* Probably ran out of space before reading the entire line. */
2101  XLAL_ERROR_NULL(XLAL_EFAILED, "Header line too long (more than %zu chars).", MAXSIZE - 1);
2102  }
2103 
2104  /* Sure hope we read the whole line. */
2105  colNamesMaxLen=2;
2106  colNames=(char **)XLALMalloc(2*sizeof(char *));
2107 
2108  if (!colNames) {
2109  XLAL_ERROR_NULL(XLAL_ENOMEM, "Failed to allocate memory for colNames.");
2110  }
2111 
2112  colName=strtok(header, delimiters);
2113  strcpy(colNames[0],colNameToParamName(colName));
2114  //colNames[0] = colNameToParamName(colName); /* switched to strcpy() to avoid warning: assignment discards qualifiers from pointer target type */
2115  colNamesLen=1;
2116  do {
2117  colName=strtok(NULL, delimiters);
2118 
2119  strcpy(colNames[colNamesLen],colNameToParamName(colName));
2120  colNamesLen++;
2121 
2122  /* Expand if necessary. */
2123  if (colNamesLen >= colNamesMaxLen) {
2124  colNamesMaxLen *= 2;
2125  colNames=XLALRealloc(colNames, colNamesMaxLen*sizeof(char *));
2126  if (!colNames) {
2127  XLAL_ERROR_NULL(XLAL_ENOMEM, "Failed to XLALReallocate memory for colNames.");
2128  }
2129  }
2130 
2131  } while (colName != NULL);
2132 
2133  /* Trim down to size. */
2134  colNames=XLALRealloc(colNames, colNamesLen*sizeof(char *));
2135 
2136  return colNames;
2137 }
2138 
2139 char *colNameToParamName(const char *colName) {
2140  char *retstr=NULL;
2141  if (colName == NULL) {
2142  return NULL;
2143  }
2144  else if (!strcmp(colName, "dist")) {
2145  retstr=XLALStringDuplicate("distance");
2146  }
2147 
2148  else if (!strcmp(colName, "ra")) {
2149  retstr=XLALStringDuplicate("rightascension");
2150  }
2151 
2152  else if (!strcmp(colName, "psi")) {
2153  retstr=XLALStringDuplicate("polarisation");
2154  }
2155 
2156  else if (!strcmp(colName, "mc")) {
2157  retstr=XLALStringDuplicate("chirpmass");
2158  }
2159 
2160  else if (!strcmp(colName, "phi_orb")) {
2161  retstr=XLALStringDuplicate("phase");
2162  }
2163 
2164  else if (!strcmp(colName, "eta")) {
2165  retstr=XLALStringDuplicate("eta");
2166  }
2167 
2168  else if (!strcmp(colName, "q")) {
2169  retstr=XLALStringDuplicate("q");
2170  }
2171 
2172  else if (!strcmp(colName, "dec")) {
2173  retstr=XLALStringDuplicate("declination");
2174  }
2175 
2176  else if (!strcmp(colName, "a1")) {
2177  retstr=XLALStringDuplicate("a_spin2");
2178  }
2179 
2180  else if (!strcmp(colName, "a2")) {
2181  retstr=XLALStringDuplicate("a_spin1");
2182  }
2183  else retstr=XLALStringDuplicate(colName);
2184  return retstr;
2185 }
2186 
2188 {
2189  LALInferenceVariableItem **prevPtr=&(vars->head);
2190  LALInferenceVariableItem *thisPtr=vars->head;
2191  while(thisPtr)
2192  {
2193  if(!strcmp(thisPtr->name,name))
2194  break;
2195  prevPtr=&(thisPtr->next);
2196  thisPtr=thisPtr->next;
2197  }
2198  if(!thisPtr) return NULL;
2199  *prevPtr=thisPtr->next;
2200  thisPtr->next=NULL;
2201  vars->dimension--;
2202  return thisPtr;
2203 }
2204 
2206 {
2207 
2208  /* Start a new list */
2209  LALInferenceVariableItem *newHead=NULL;
2210 
2211  /* While there are elements in the old list */
2212  while(vars->head)
2213  {
2214  /* Scan through the old list looking for first item alphabetically */
2215  LALInferenceVariableItem *this=NULL,*match=NULL;
2216  for(match=vars->head,this=match->next; this; this=this->next)
2217  if(strcmp(match->name,this->name)<0)
2218  match = this;
2219  /* Remove it from the old list and link it into the new one */
2220  LALInferenceVariableItem *item=LALInferencePopVariableItem(vars,match->name);
2221  item->next=newHead;
2222  newHead=item;
2223  vars->dimension++; /* Increase the dimension which was decreased by PopVariableItem */
2224  }
2225  vars->head=newHead;
2226  return;
2227 }
2228 
2229 /**
2230  * Append the sample to a file. file pointer is stored in state->algorithmParams as a
2231  * LALInferenceVariable called "outfile", as a void ptr.
2232  * Caller is responsible for opening and closing file.
2233  * Variables are alphabetically sorted before being written
2234  */
2236 {
2237  FILE *outfile=NULL;
2238  if(LALInferenceCheckVariable(algorithmParams,"outfile"))
2239  outfile=*(FILE **)LALInferenceGetVariable(algorithmParams,"outfile");
2240  /* Write out old sample */
2241  if(outfile==NULL) return;
2244  fprintf(outfile,"\n");
2245 }
2246 
2247 /**
2248  * Append the sample to an array which can be later processed by the user.
2249  * Array is stored as a C array in a LALInferenceVariable in state->algorithmParams
2250  * called "outputarray". Number of items in the array is stored as "N_outputarray".
2251  * Will create the array and store it in this way if it does not exist.
2252  * DOES NOT FREE ARRAY, user must clean up after use.
2253  * Also outputs sample to disk if possible
2254  */
2256 {
2257  LALInferenceVariables **output_array=NULL;
2258  UINT4 N_output_array=0;
2260  LALInferenceLogSampleToFile(algorithmParams,vars);
2261 
2262  /* Set up the array if it is not already allocated */
2263  if(LALInferenceCheckVariable(algorithmParams,"outputarray"))
2264  output_array=*(LALInferenceVariables ***)LALInferenceGetVariable(algorithmParams,"outputarray");
2265  else
2266  LALInferenceAddVariable(algorithmParams,"outputarray",&output_array,LALINFERENCE_void_ptr_t,LALINFERENCE_PARAM_OUTPUT);
2267 
2268  if(LALInferenceCheckVariable(algorithmParams,"N_outputarray"))
2269  N_output_array=*(INT4 *)LALInferenceGetVariable(algorithmParams,"N_outputarray");
2270  else
2271  LALInferenceAddVariable(algorithmParams,"N_outputarray",&N_output_array,LALINFERENCE_INT4_t,LALINFERENCE_PARAM_OUTPUT);
2272 
2273  /* Expand the array for new sample */
2274  output_array=XLALRealloc(output_array, (N_output_array+1) *sizeof(LALInferenceVariables *));
2275  if(!output_array){
2276  XLAL_ERROR_VOID(XLAL_EFAULT, "Unable to allocate array for samples.");
2277  }
2278  else
2279  {
2280  /* Save sample and update */
2281 
2282  output_array[N_output_array]=XLALCalloc(1,sizeof(LALInferenceVariables));
2283  LALInferenceCopyVariables(vars,output_array[N_output_array]);
2284  N_output_array++;
2285 
2286  LALInferenceSetVariable(algorithmParams,"outputarray",&output_array);
2287  LALInferenceSetVariable(algorithmParams,"N_outputarray",&N_output_array);
2288  }
2289  return;
2290 }
2291 
2292 void LALInferenceMcEta2Masses(double mc, double eta, double *m1, double *m2)
2293 /* Compute individual companion masses (m1, m2) */
2294 /* for given chirp mass (m_c) & mass ratio (eta) */
2295 /* (note: m1 >= m2). */
2296 {
2297  double root = sqrt(0.25-eta);
2298  double fraction = (0.5+root) / (0.5-root);
2299  *m2 = mc * (pow(1+fraction,0.2) / pow(fraction,0.6));
2300  *m1 = mc * (pow(1+1.0/fraction,0.2) / pow(1.0/fraction,0.6));
2301  return;
2302 }
2303 
2304 void LALInferenceMcQ2Masses(double mc, double q, double *m1, double *m2)
2305 /* Compute individual companion masses (m1, m2) */
2306 /* for given chirp mass (m_c) & asymmetric mass */
2307 /* ratio (q). note: q = m2/m1, where m1 >= m2 */
2308 {
2309  double factor = mc * pow(1 + q, 1.0/5.0);
2310  *m1 = factor * pow(q, -3.0/5.0);
2311  *m2 = factor * pow(q, +2.0/5.0);
2312  return;
2313 }
2314 void LALInferenceQ2Eta(double q, double *eta)
2315 /* Compute symmetric mass ratio eta from the */
2316 /* asymmetric mass ratio q. */
2317 {
2318  *eta = q/((1+q)*(1+q));
2319  return;
2320 }
2321 /* Calculate dQuadMon1 and dQuadMon2 from dQaudMonS and dQuadMonA */
2322 void LALInferencedQuadMonSdQuadMonA(REAL8 dQuadMonS, REAL8 dQuadMonA, REAL8 *dQuadMon1, REAL8 *dQuadMon2){
2323  *dQuadMon1=(dQuadMonS+dQuadMonA);
2324  *dQuadMon2=(dQuadMonS-dQuadMonA);
2325  return;
2326 }
2327 
2328 
2330  REAL8 a=(8./13.)*(1.+7.*eta-31.*eta*eta);
2331  REAL8 b=(8./13.)*sqrt(1.-4.*eta)*(1.+9.*eta-11.*eta*eta);
2332  REAL8 c=(1./2.)*sqrt(1.-4.*eta)*(1.-13272.*eta/1319.+8944.*eta*eta/1319.);
2333  REAL8 d=(1./2.)*(1.-15910.*eta/1319.+32850.*eta*eta/1319.+3380.*eta*eta*eta/1319.);
2334  *lambda1=((c-d)*lambdaT-(a-b)*dLambdaT)/(2.*(b*c-a*d));
2335  *lambda2=((c+d)*lambdaT-(a+b)*dLambdaT)/(2.*(a*d-b*c));
2336  return;
2337 }
2338 
2339 /* Find lambda1,2(m1,2|eos) for 4-piece polytrope EOS model */
2340 void LALInferenceLogp1GammasMasses2Lambdas(REAL8 logp1,REAL8 gamma1,REAL8 gamma2,REAL8 gamma3, REAL8 mass1, REAL8 mass2, REAL8 *lambda1, REAL8 *lambda2){
2341 // Convert to SI
2342 REAL8 logp1_si=logp1-1.0;
2343 double mass1_kg=mass1*LAL_MSUN_SI;
2344 double mass2_kg=mass2*LAL_MSUN_SI;
2345 
2346 // Make eos
2347 LALSimNeutronStarEOS *eos = NULL;
2348 LALSimNeutronStarFamily *fam = NULL;
2349 eos = XLALSimNeutronStarEOS4ParameterPiecewisePolytrope(logp1_si, gamma1, gamma2, gamma3);
2351 
2352 // Calculate lambda1(m1|eos)
2353 double r = XLALSimNeutronStarRadius(mass1_kg, fam);
2354 double k = XLALSimNeutronStarLoveNumberK2(mass1_kg, fam);
2355 double c = mass1 * LAL_MRSUN_SI / r;
2356 *lambda1= (2.0/3.0) * k / pow(c , 5.0);
2357 
2358 // Calculate lambda2(m2|eos)
2359 r = XLALSimNeutronStarRadius(mass2_kg, fam);
2360 k = XLALSimNeutronStarLoveNumberK2(mass2_kg, fam);
2361 c = mass2 * LAL_MRSUN_SI / r;
2362 *lambda2= (2.0/3.0) * k / pow(c , 5.0);
2363 
2364 // Clean up
2367 }
2368 
2369 /* Find lambda1,2(m1,2|eos) for spectral EOS model */
2371 
2372 // If unreasonable gammas, do not find lambdas
2374  *lambda1= 0.;
2375  *lambda2= 0.;
2376 }
2377 // Else calculate lambdas
2378 else{
2379  // Convert to SI
2380  double mass1_kg=mass1*LAL_MSUN_SI;
2381  double mass2_kg=mass2*LAL_MSUN_SI;
2382 
2383  // Make eos
2384  LALSimNeutronStarEOS *eos = NULL;
2385  LALSimNeutronStarFamily *fam = NULL;
2387  fam = XLALCreateSimNeutronStarFamily(eos);
2388 
2389  // Calculate lambda1(m1|eos)
2390  double r = XLALSimNeutronStarRadius(mass1_kg, fam);
2391  double k = XLALSimNeutronStarLoveNumberK2(mass1_kg, fam);
2392  double c = mass1 * LAL_MRSUN_SI / r;
2393  *lambda1= (2.0/3.0) * k / pow(c , 5.0);
2394 
2395  // Calculate lambda2(m1|eos)
2396  r = XLALSimNeutronStarRadius(mass2_kg, fam);
2397  k = XLALSimNeutronStarLoveNumberK2(mass2_kg, fam);
2398  c = mass2 * LAL_MRSUN_SI / r;
2399  *lambda2= (2.0/3.0) * k / pow(c , 5.0);
2400 
2401  // Clean up
2404 }
2405 
2406 }
2407 
2408 
2409 /* Checks if EOS allows for acausal speed of sound and unphysical maximum masses */
2411 int ret;
2412 
2413 LALSimNeutronStarEOS *eos=NULL;
2414 LALSimNeutronStarFamily *fam=NULL;
2415 
2416 // If using 4-piece polytrope eos params...
2418 {
2419  // Retrieve EOS params from params linked list
2420  double logp1=*(double *)LALInferenceGetVariable(params,"logp1");
2421  double gamma1=*(double *)LALInferenceGetVariable(params,"gamma1");
2422  double gamma2=*(double *)LALInferenceGetVariable(params,"gamma2");
2423  double gamma3=*(double *)LALInferenceGetVariable(params,"gamma3");
2424 
2425  // Convert to SI
2426  REAL8 logp1_si=logp1-1.0;
2427 
2428  // Make 4-piece polytrope eos
2429  eos = XLALSimNeutronStarEOS4ParameterPiecewisePolytrope(logp1_si,gamma1,gamma2,gamma3);
2430 
2431 // Else if using 4-coeff spectral eos params...
2432 }
2434 {
2435  // Retrieve EOS params from params linked list
2436  double SDgamma0=*(double *)LALInferenceGetVariable(params,"SDgamma0");
2437  double SDgamma1=*(double *)LALInferenceGetVariable(params,"SDgamma1");
2438  double SDgamma2=*(double *)LALInferenceGetVariable(params,"SDgamma2");
2439  double SDgamma3=*(double *)LALInferenceGetVariable(params,"SDgamma3");
2440  double gamma[]={SDgamma0,SDgamma1,SDgamma2,SDgamma3};
2441 
2443  return XLAL_FAILURE;
2444 
2445  // Make 4-piece polytrope eos
2447 
2448 }
2449 // Else fail, since you need an eos
2450 else {
2451  fprintf(stdout,"NO EOS PARAMETERS FOUND\n");
2452  return XLAL_FAILURE;
2453 }
2454 
2455 /* FIXME: This is a little clunky,
2456  Check to make sure family will contain
2457  enough pts for interpolation */
2458 double pdat;
2459 double mdat;
2460 double mdat_prev;
2461 double rdat;
2462 double kdat;
2463 
2464 /* Initialize previous value for mdat comparison, set to something that will always
2465  make (mdat <= mdat_prev) == true. */
2466 mdat_prev = 0.0;
2467 
2468 // Ensure mass turnover does not happen too soon
2469 const double logpmin = 75.5;
2470 double logpmax = log(XLALSimNeutronStarEOSMaxPressure(eos));
2471 double dlogp = (logpmax - logpmin) / 100.;
2472 // Need at least 8 points
2473 for (int i = 0; i < 4; ++i) {
2474  pdat = exp(logpmin + i * dlogp);
2475  XLALSimNeutronStarTOVODEIntegrate(&rdat, &mdat, &kdat, pdat, eos);
2476  /* determine if maximum mass has been found */
2477  if (mdat <= mdat_prev){
2478  fprintf(stdout,"EOS has too few points. Sample rejected.\n");
2480  {
2481  // Retrieve EOS params from params linked list
2482  double SDgamma0=*(double *)LALInferenceGetVariable(params,"SDgamma0");
2483  double SDgamma1=*(double *)LALInferenceGetVariable(params,"SDgamma1");
2484  double SDgamma2=*(double *)LALInferenceGetVariable(params,"SDgamma2");
2485  double SDgamma3=*(double *)LALInferenceGetVariable(params,"SDgamma3");
2486  fprintf(stdout,"spectral: %f %f %f %f\n",SDgamma0,SDgamma1,SDgamma2,SDgamma3);
2487  }
2488  // Clean up
2491  return XLAL_FAILURE;
2492  }
2493  mdat_prev = mdat;
2494 }
2495 
2496 
2497 // Make family
2499 
2500 // Determine which mass parameterization is used
2501 double mass1 = 0.;
2502 double mass2 = 0.;
2503 
2505  // If using (mass1,mass2) parameterization, no need to convert
2506  mass1=*(double *)LALInferenceGetVariable(params,"mass1");
2507  mass2=*(double *)LALInferenceGetVariable(params,"mass2");
2508 }
2509 else if(LALInferenceCheckVariable(params,"chirpmass") && LALInferenceCheckVariable(params,"q")) {
2510  // Convert from (chirpmass,q) -> (m1,m2)
2511  double chirpmass=*(double *)LALInferenceGetVariable(params,"chirpmass");
2512  double q=*(double *)LALInferenceGetVariable(params,"q");
2513  LALInferenceMcQ2Masses(chirpmass,q,&mass1,&mass2);
2514 }
2515 
2516 else if(LALInferenceCheckVariable(params, "chirpmass") && LALInferenceCheckVariable(params, "eta")) {
2517  // Convert from (chirpmass,eta) -> (m1,m2)
2518  double chirpmass=*(double *)LALInferenceGetVariable(params,"chirpmass");
2519  double eta=*(double *)LALInferenceGetVariable(params,"eta");
2520  LALInferenceMcEta2Masses(chirpmass,eta,&mass1,&mass2);
2521 }
2522 else {
2523  // Else fail
2524  fprintf(stdout,"ERROR: NO MASS PARAMETERS FOUND\n");
2525  // Clean up
2528  return XLAL_FAILURE;
2529 }
2530 
2531 // Convert to SI
2532 double mass1_kg= mass1*LAL_MSUN_SI;
2533 double mass2_kg= mass2*LAL_MSUN_SI;
2534 
2535 // Calculate speed of sound and max and min mass allowed by eos
2536 double min_mass_kg = XLALSimNeutronStarFamMinimumMass(fam);
2537 double max_mass_kg = XLALSimNeutronStarMaximumMass(fam);
2538 double pmax = XLALSimNeutronStarCentralPressure(max_mass_kg, fam);
2539 double hmax = XLALSimNeutronStarEOSPseudoEnthalpyOfPressure(pmax, eos);
2540 double vsmax = XLALSimNeutronStarEOSSpeedOfSoundGeometerized(hmax, eos);
2541 
2542 // Read in max observed NS mass, which eos must support
2543 REAL8 ns_max_mass = 0.;
2544 if(LALInferenceGetProcParamVal(commandLine,"--ns-max-mass")) {
2545  ns_max_mass= atof(LALInferenceGetProcParamVal(commandLine,"--ns-max-mass")->value);
2546 }
2547 // If none, then set max to proposed mass, since EOS must support this mass anyway
2548 else{
2549  ns_max_mass = mass2;
2550 }
2551 
2552 // If m1 and m2 are supported by min and max mass allowed by eos
2553 // and if the speed of sound is less than 1.1c (the 0.1 is some wiggle room, since eos is not exact)
2554 // and if the max-mass NS is supported
2555 if(mass1_kg <= max_mass_kg && mass2_kg <= max_mass_kg && mass1_kg >= min_mass_kg && mass2_kg >= min_mass_kg && vsmax <= 1.1 && max_mass_kg >= ns_max_mass*LAL_MSUN_SI){
2556  ret=XLAL_SUCCESS;
2557 // Else fail
2558 }else{
2559  ret=XLAL_FAILURE;
2560 }
2561 
2562 // Clean up
2565 return ret;
2566 }
2567 
2568 
2569 // Determines if current spectral parameters are within Adiabatic 'prior' range
2570 int LALInferenceSDGammaCheck(double gamma[], int size) {
2571 int i;
2572 int ret = XLAL_SUCCESS;
2573 double p0 = 4.43784199e-13;
2574 double xmax = 12.3081;
2575 double pmax = p0 * exp(xmax);
2576 size_t ndat = 500;
2577 
2578 double *pdat;
2579 double *adat;
2580 double *xdat;
2581 
2582 pdat = XLALCalloc(ndat, sizeof(*pdat));
2583 adat = XLALCalloc(ndat, sizeof(*adat));
2584 xdat = XLALCalloc(ndat, sizeof(*xdat));
2585 
2586 // Generating higher density portion of EOS with spectral decomposition
2587 double logpmax = log(pmax);
2588 double logp0 = log(p0);
2589 double dlogp = (logpmax-logp0)/ndat;
2590 // Calculating pressure and adiabatic index table
2591 for(i = 0;i < (int) ndat;i++)
2592 {
2593  pdat[i] = exp(logp0 + dlogp*i);
2594  xdat[i] = log(pdat[i]/p0);
2595  adat[i] = AdiabaticIndex(gamma, xdat[i], size);
2596 }
2597 
2598 // Make sure all values are within Adiabatic Prior range
2599 for(i = 0;i<(int) ndat;i++) {
2600  // FIXME: Should make range adjustable from the commandline
2601  if(adat[i] < 0.6 || adat[i] > 4.5) {
2602  ret = XLAL_FAILURE;
2603  break;
2604  }
2605 }
2606 LALFree(pdat);
2607 LALFree(xdat);
2608 LALFree(adat);
2610 return ret;
2611 }
2612 
2613 /* Specral decomposition of eos's adiabatic index */
2614 double AdiabaticIndex(double gamma[],double x, int size)
2615 {
2616  double Gamma, logGamma = 0;
2617  int i;
2618  for(i=0;i<size;i++)
2619  {
2620  logGamma += gamma[i]*pow(x,(double) i);
2621  }
2622  Gamma = exp(logGamma);
2623  return Gamma;
2624 }
2625 
2626 
2627 
2628 static void deleteCell(LALInferenceKDTree *cell) {
2629  if (cell == NULL) {
2630  return; /* Our work here is done. */
2631  } else {
2632  size_t i;
2633 
2634  deleteCell(cell->left);
2635  deleteCell(cell->right);
2636 
2637  if (cell->lowerLeft != NULL) XLALFree(cell->lowerLeft);
2638  if (cell->upperRight != NULL) XLALFree(cell->upperRight);
2639  if (cell->ptsMean != NULL) XLALFree(cell->ptsMean);
2640  if (cell->eigenMin != NULL) XLALFree(cell->eigenMin);
2641  if (cell->eigenMax != NULL) XLALFree(cell->eigenMax);
2642 
2643  for (i = 0; i < cell->ptsSize; i++) {
2644  if (cell->pts[i] != NULL) XLALFree(cell->pts[i]);
2645  }
2646  if (cell->pts != NULL) XLALFree(cell->pts);
2647 
2648  if (cell->ptsCov != NULL) {
2649  for (i = 0; i < cell->dim; i++) {
2650  XLALFree(cell->ptsCov[i]);
2651  }
2652  XLALFree(cell->ptsCov);
2653  }
2654 
2655  if (cell->ptsCovEigenVects != NULL) {
2656  for (i = 0; i < cell->dim; i++) {
2657  XLALFree(cell->ptsCovEigenVects[i]);
2658  }
2659  XLALFree(cell->ptsCovEigenVects);
2660  }
2661 
2662  XLALFree(cell);
2663 
2664  return;
2665  }
2666 }
2667 
2669  deleteCell(tree);
2670 }
2671 
2672 typedef enum {
2675  TOP
2677 
2678 static LALInferenceKDTree *newCell(size_t ndim, REAL8 *lowerLeft, REAL8 *upperRight, size_t level, cellType type) {
2679  LALInferenceKDTree *cell = XLALCalloc(1, sizeof(LALInferenceKDTree));
2680  size_t i;
2681 
2682  cell->lowerLeft = XLALCalloc(ndim, sizeof(REAL8));
2683  cell->upperRight = XLALCalloc(ndim, sizeof(REAL8));
2684  cell->ptsMean = XLALCalloc(ndim, sizeof(REAL8));
2685  cell->eigenMin = XLALCalloc(ndim, sizeof(REAL8));
2686  cell->eigenMax = XLALCalloc(ndim, sizeof(REAL8));
2687 
2688  cell->pts = XLALCalloc(1, sizeof(REAL8 *));
2689  cell->ptsSize = 1;
2690  cell->npts = 0;
2691  cell->dim = ndim;
2692 
2693  cell->ptsCov = XLALCalloc(ndim, sizeof(REAL8 *));
2694  cell->ptsCovEigenVects = XLALCalloc(ndim, sizeof(REAL8 *));
2695  for (i = 0; i < ndim; i++) {
2696  cell->ptsCov[i] = XLALCalloc(ndim, sizeof(REAL8));
2697  cell->ptsCovEigenVects[i] = XLALCalloc(ndim, sizeof(REAL8));
2698  }
2699 
2700  memcpy(cell->upperRight, upperRight, ndim*sizeof(REAL8));
2701  memcpy(cell->lowerLeft, lowerLeft, ndim*sizeof(REAL8));
2702  if (type == LEFT) {
2703  cell->upperRight[level] = 0.5*(lowerLeft[level] + upperRight[level]);
2704  } else if (type == RIGHT) {
2705  cell->lowerLeft[level] = 0.5*(lowerLeft[level] + upperRight[level]);
2706  } else {
2707  /* Do not change lowerLeft or upperRight, since this is the top-level cell. */
2708  }
2709 
2710  return cell;
2711 }
2712 
2713 LALInferenceKDTree *LALInferenceKDEmpty(REAL8 *lowerLeft, REAL8 *upperRight, size_t ndim) {
2714  LALInferenceKDTree *cell = newCell(ndim, lowerLeft, upperRight, 0, TOP);
2715  return cell;
2716 }
2717 
2718 static int equalPoints(REAL8 *a, REAL8 *b, size_t n) {
2719  size_t i;
2720  for (i = 0; i < n; i++) {
2721  if (a[i] != b[i]) return 0;
2722  }
2723  return 1;
2724 }
2725 
2727  if (cell->npts <= 1) {
2728  return 1;
2729  } else {
2730  size_t i;
2731  REAL8 *pt0 = cell->pts[0];
2732 
2733  for (i = 1; i < cell->npts; i++) {
2734  if (!equalPoints(pt0, cell->pts[i], cell->dim)) return 0;
2735  }
2736 
2737  return 1;
2738  }
2739 }
2740 
2741 static void addPtToCellPts(LALInferenceKDTree *cell, REAL8 *pt) {
2742  size_t ptsSize = cell->ptsSize;
2743  size_t npts = cell->npts;
2744  size_t dim = cell->dim;
2745 
2746  /* copy previous points */
2747  if ( npts == ptsSize ){
2748  REAL8 tmpArr[npts][dim];
2749 
2750  /* copy points from cell */
2751  for( UINT4 i=0; i < npts; i++ ){
2752  for( UINT4 j=0; j < dim; j++ ){
2753  tmpArr[i][j] = cell->pts[i][j];
2754  }
2755  XLALFree(cell->pts[i]); /* free column */
2756  }
2757 
2758  /* free array */
2759  XLALFree(cell->pts);
2760 
2761  /* expand array */
2762  cell->pts = XLALCalloc(2*ptsSize, sizeof(REAL8 *));
2763 
2764  /* copy vector into array */
2765  for( UINT4 i=0; i < 2*ptsSize; i++ ){
2766  cell->pts[i] = XLALCalloc(dim, sizeof(REAL8));
2767 
2768  if (i < npts){
2769  for( UINT4 j=0; j < dim; j++ )
2770  cell->pts[i][j] = tmpArr[i][j];
2771  }
2772  }
2773 
2774  cell->ptsSize *= 2;
2775  }
2776 
2777  if ( npts == 0 ) cell->pts[npts] = XLALCalloc(dim, sizeof(REAL8));
2778 
2779  /* add new point */
2780  for( UINT4 i = 0; i < dim; i++ )
2781  cell->pts[npts][i] = pt[i];
2782 
2783  cell->npts += 1;
2784  cell->eigenFrameStale = 1;
2785 }
2786 
2787 /* The following routine handles inserting new points into the tree.
2788  It is organized recursively, inserting into cells based on the
2789  following three cases:
2790 
2791  1. There are no points in the cell. Then insert the given point,
2792  and stop; we're at a leaf.
2793 
2794  2. Both of the cell's sub-cells are NULL. Then the cell is a leaf
2795  (with some number of points), and the first order of business is to
2796  push the existing points down a level, then insert into this cell,
2797  and the appropriate sub-cell.
2798 
2799  3. This cell has non-null sub-cells. Then it is not a leaf cell,
2800  and we should just insert into this cell, and add the point to the
2801  appropriate sub-cell.
2802 
2803 */
2804 static int insertIntoCell(LALInferenceKDTree *cell, REAL8 *pt, size_t level) {
2805  size_t dim = cell->dim;
2806  size_t nextLevel = (level+1)%dim;
2807  level = level%dim;
2808 
2809  if (cell->npts == 0) {
2810  /* Insert this point into the cell, and quit. */
2811  addPtToCellPts(cell, pt);
2812  return XLAL_SUCCESS;
2813  } else if (cell->left == NULL && cell->right == NULL) {
2814  /* This cell is a leaf node. Insert the point, then (unless the
2815  cell stores many copies of the same point), push everything
2816  down a level. */
2817  addPtToCellPts(cell, pt);
2818 
2819  if (cellAllEqualPoints(cell)) {
2820  /* Done, since there are many copies of the same point---cell
2821  remains a leaf. */
2822  return XLAL_SUCCESS;
2823  } else {
2824  size_t i;
2825  REAL8 mid = 0.5*(cell->lowerLeft[level] + cell->upperRight[level]);
2826 
2827  cell->left = newCell(dim, cell->lowerLeft, cell->upperRight, level, LEFT);
2828  cell->right = newCell(dim, cell->lowerLeft, cell->upperRight, level, RIGHT);
2829 
2830  for (i = 0; i < cell->npts; i++) {
2831  REAL8 *lowerPt = cell->pts[i];
2832 
2833  if (lowerPt[level] <= mid) {
2834  insertIntoCell(cell->left, lowerPt, nextLevel);
2835  } else {
2836  insertIntoCell(cell->right, lowerPt, nextLevel);
2837  }
2838  }
2839 
2840  return XLAL_SUCCESS;
2841  }
2842  } else {
2843  /* This is not a leaf cell, so insert, and then move down the tree. */
2844  REAL8 mid = 0.5*(cell->lowerLeft[level] + cell->upperRight[level]);
2845 
2846  addPtToCellPts(cell, pt);
2847 
2848  if (pt[level] <= mid) {
2849  return insertIntoCell(cell->left, pt, nextLevel);
2850  } else {
2851  return insertIntoCell(cell->right, pt, nextLevel);
2852  }
2853  }
2854 }
2855 
2856 static int inBounds(REAL8 *pt, REAL8 *low, REAL8 *high, size_t n) {
2857  size_t i;
2858 
2859  for (i = 0; i < n; i++) {
2860  if (pt[i] < low[i] || pt[i] > high[i]) return 0;
2861  }
2862 
2863  return 1;
2864 }
2865 
2866 static void computeMean(LALInferenceKDTree *cell) {
2867  REAL8 **pts = cell->pts;
2868  REAL8 *mean = cell->ptsMean;
2869  size_t dim = cell->dim;
2870  size_t npts = cell->npts;
2871  size_t i;
2872 
2873  for (i = 0; i < dim; i++) {
2874  mean[i] = 0.0;
2875  }
2876 
2877  for (i = 0; i < npts; i++) {
2878  size_t j;
2879  for (j = 0; j < dim; j++) {
2880  mean[j] += pts[i][j];
2881  }
2882  }
2883 
2884  for (i = 0; i < dim; i++) {
2885  mean[i] /= npts;
2886  }
2887 }
2888 
2890  REAL8 **cov = cell->ptsCov;
2891  REAL8 **pts = cell->pts;
2892  REAL8 *mu = cell->ptsMean;
2893  size_t npts = cell->npts;
2894  size_t dim = cell->dim;
2895  size_t i;
2896 
2897  for (i = 0; i < dim; i++) {
2898  size_t j;
2899  for (j = 0; j < dim; j++) {
2900  cov[i][j] = 0.0;
2901  }
2902  }
2903 
2904  for (i = 0; i < npts; i++) {
2905  size_t j;
2906 
2907  REAL8 *pt = pts[i];
2908 
2909  for (j = 0; j < dim; j++) {
2910  size_t k;
2911  REAL8 ptj = pt[j];
2912  REAL8 muj = mu[j];
2913 
2914  for (k = 0; k < dim; k++) {
2915  REAL8 ptk = pt[k];
2916  REAL8 muk = mu[k];
2917 
2918  cov[j][k] += (ptj - muj)*(ptk-muk);
2919  }
2920  }
2921  }
2922 
2923  for (i = 0; i < cell->dim; i++) {
2924  size_t j;
2925  for (j = 0; j < cell->dim; j++) {
2926  cov[i][j] /= (npts - 1);
2927  }
2928  }
2929 }
2930 
2931 static void computeEigenVectorsCleanup(gsl_matrix *A, gsl_matrix *evects, gsl_vector *evals,
2932  gsl_eigen_symmv_workspace *ws) {
2933  if (A != NULL) gsl_matrix_free(A);
2934  if (evects != NULL) gsl_matrix_free(evects);
2935  if (evals != NULL) gsl_vector_free(evals);
2936  if (ws != NULL) gsl_eigen_symmv_free(ws);
2937 }
2938 
2940  size_t dim = cell->dim;
2941  gsl_matrix *A = gsl_matrix_alloc(dim, dim);
2942  gsl_matrix *evects = gsl_matrix_alloc(dim, dim);
2943  gsl_vector *evals = gsl_vector_alloc(dim);
2944  gsl_eigen_symmv_workspace *ws = gsl_eigen_symmv_alloc(dim);
2945 
2946  REAL8 **covEVs = cell->ptsCovEigenVects;
2947  REAL8 **cov = cell->ptsCov;
2948 
2949  size_t i;
2950  int status;
2951 
2952  if (A == NULL || evects == NULL || evals == NULL || ws == NULL) {
2953  computeEigenVectorsCleanup(A, evects, evals, ws);
2955  }
2956 
2957  /* Copy covariance matrix into A. */
2958  for (i = 0; i < dim; i++) {
2959  size_t j;
2960 
2961  for (j = 0; j < dim; j++) {
2962  gsl_matrix_set(A, i, j, cov[i][j]);
2963  }
2964  }
2965 
2966  /* Compute evecs. */
2967  if ((status = gsl_eigen_symmv(A, evals, evects, ws)) != GSL_SUCCESS) {
2968  computeEigenVectorsCleanup(A, evects, evals, ws);
2969  XLAL_ERROR_VOID(status, "gsl error");
2970  }
2971 
2972  /* Copy eigenvector matrix into covEVs; [i][j] is the jth component
2973  of the ith eigenvector. */
2974  for (i = 0; i < dim; i++) {
2975  size_t j;
2976 
2977  for (j = 0; j < dim; j++) {
2978  covEVs[i][j] = gsl_matrix_get(evects, j, i);
2979  }
2980  }
2981 
2982  computeEigenVectorsCleanup(A, evects, evals, ws);
2983 }
2984 
2985 /* xe = eigenvs^T x */
2986 static void toEigenFrame( size_t dim, REAL8 **eigenvs, REAL8 *x, REAL8 *xe) {
2987  size_t j;
2988 
2989  memset(xe, 0, dim*sizeof(REAL8));
2990 
2991  for (j = 0; j < dim; j++) {
2992  size_t i;
2993  REAL8 xj = x[j];
2994  REAL8 *evj = eigenvs[j];
2995  for (i = 0; i < dim; i++) {
2996  xe[i] += evj[i]*xj;
2997  }
2998  }
2999 }
3000 
3001 /* x = eigenvs xe */
3002 static void fromEigenFrame( size_t dim, REAL8 **eigenvs, REAL8 *xe, REAL8 *x) {
3003  size_t i;
3004 
3005  memset(x, 0, dim*sizeof(REAL8));
3006 
3007  for (i = 0; i < dim; i++) {
3008  size_t j;
3009  REAL8 *evi = eigenvs[i];
3010  for (j = 0; j < dim; j++) {
3011  x[i] += evi[j]*xe[j];
3012  }
3013  }
3014 }
3015 
3017  REAL8 **pts = cell->pts;
3018  size_t dim = cell->dim;
3019  size_t npts = cell->npts;
3020  REAL8 **eigenvs = cell->ptsCovEigenVects;
3021  REAL8 *mu = cell->ptsMean;
3022 
3023  REAL8 *min = cell->eigenMin;
3024  REAL8 *max = cell->eigenMax;
3025 
3026  REAL8 *xe = NULL, *x = NULL;
3027 
3028  size_t i;
3029 
3030  xe = XLALCalloc(dim, sizeof(REAL8));
3031  if (xe == NULL) XLAL_ERROR_VOID(XLAL_ENOMEM);
3032 
3033  x = XLALCalloc(dim, sizeof(REAL8));
3034  if (x == NULL) {
3035  XLALFree(xe);
3037  }
3038 
3039  for (i = 0; i < dim; i++) {
3040  min[i] = 1.0/0.0;
3041  max[i] = -1.0/0.0;
3042  }
3043 
3044  for (i = 0; i < npts; i++) {
3045  size_t j;
3046 
3047  for (j = 0; j < dim; j++) {
3048  x[j] = pts[i][j] - mu[j];
3049  }
3050 
3051  toEigenFrame(dim, eigenvs, x, xe);
3052 
3053  for (j = 0; j < dim; j++) {
3054  if (xe[j] < min[j]) min[j] = xe[j];
3055  if (xe[j] > max[j]) max[j] = xe[j];
3056  }
3057  }
3058 
3059  XLALFree(x);
3060  XLALFree(xe);
3061 }
3062 
3064  computeMean(cell);
3065  computeCovariance(cell);
3066  computeEigenVectors(cell);
3067  computeEigenMinMax(cell);
3068 
3069  cell->eigenFrameStale = 0;
3070 }
3071 
3073  if (tree == NULL) XLAL_ERROR(XLAL_EINVAL, "given NULL tree");
3074 
3075  if (!inBounds(pt, tree->lowerLeft, tree->upperRight, tree->dim))
3076  XLAL_ERROR(XLAL_EINVAL, "given point that is not in global tree bounds");
3077 
3078  return insertIntoCell(tree, pt, 0);
3079 }
3080 
3081 static LALInferenceKDTree *doFindCell(LALInferenceKDTree *cell, REAL8 *pt, size_t dim, size_t Npts, size_t level) {
3082  if (cell == NULL) {
3083  /* If we encounter a NULL cell, then pass it up the chain. */
3084  return cell;
3085  } else if (cell->npts == 0) {
3086  return NULL;
3087  } else if (cell->npts == 1 || cell->npts < Npts) {
3088  return cell;
3089  } else {
3090  REAL8 mid = 0.5*(cell->lowerLeft[level] + cell->upperRight[level]);
3091 
3092  if (pt[level] <= mid) {
3093  LALInferenceKDTree *maybeCell = doFindCell(cell->left, pt, dim, Npts, (level+1)%dim);
3094  if (maybeCell == NULL) {
3095  return cell; /* If a NULL comes up from below, then this cell
3096  is the one with the fewest points containing
3097  pt. */
3098  } else {
3099  return maybeCell;
3100  }
3101  } else {
3102  LALInferenceKDTree *maybeCell = doFindCell(cell->right, pt, dim, Npts, (level+1)%dim);
3103  if (maybeCell == NULL) {
3104  return cell;
3105  } else {
3106  return maybeCell;
3107  }
3108  }
3109  }
3110 }
3111 
3113  return doFindCell(tree, pt, tree->dim, Npts, 0);
3114 }
3115 
3117  size_t ndim = cell->dim;
3118  size_t i;
3119  REAL8 logVol = 0.0;
3120  for (i = 0; i < ndim; i++) {
3121  logVol += log(cell->upperRight[i] - cell->lowerLeft[i]);
3122  }
3123 
3124  return logVol;
3125 }
3126 
3128  double logVol = 0.0;
3129  size_t ndim = cell->dim;
3130  size_t i;
3131 
3132  if (cell->eigenFrameStale) {
3133  updateEigenSystem(cell);
3134  }
3135 
3136  for (i = 0; i < ndim; i++) {
3137  logVol += log(cell->eigenMax[i] - cell->eigenMin[i]);
3138  }
3139 
3140  return logVol;
3141 }
3142 
3144  LALInferenceVariableItem *templateItem = templt->head;
3145  size_t i = 0;
3146  while (templateItem != NULL) {
3147  if (LALInferenceCheckVariableNonFixed(templt, templateItem->name)) {
3148  pt[i] = *(REAL8 *)LALInferenceGetVariable(params, templateItem->name);
3149  i++;
3150  }
3151  templateItem = templateItem->next;
3152  }
3153 }
3154 
3156  LALInferenceVariableItem *templateItem = templt->head;
3157  size_t i = 0;
3158  while (templateItem != NULL) {
3159  if (LALInferenceCheckVariableNonFixed(templt, templateItem->name)) {
3160  LALInferenceSetVariable(params, templateItem->name, &(pt[i]));
3161  i++;
3162  }
3163  templateItem = templateItem->next;
3164  }
3165 }
3166 
3167 void LALInferenceKDDrawEigenFrame(gsl_rng *rng, LALInferenceKDTree *tree, REAL8 *pt, size_t Npts) {
3168  LALInferenceKDTree *topCell = tree;
3169 
3170  if (topCell == NULL || topCell->npts == 0) XLAL_ERROR_VOID(XLAL_EINVAL, "cannot draw from empty cell");
3171 
3172  LALInferenceKDTree *cell = LALInferenceKDFindCell(tree, topCell->pts[gsl_rng_uniform_int(rng, topCell->npts)], Npts);
3173 
3174  if (cell->npts == 1) {
3175  /* If there is one point, then the covariance matrix is undefined,
3176  and we draw from the rectangular area. */
3177  size_t i;
3178 
3179  for (i = 0; i < cell->dim; i++) {
3180  pt[i] = cell->lowerLeft[i] + gsl_rng_uniform(rng)*(cell->upperRight[i] - cell->lowerLeft[i]);
3181  }
3182  } else {
3183  REAL8 *ept = XLALCalloc(cell->dim, sizeof(REAL8));
3184  size_t i;
3185 
3186  if (cell->eigenFrameStale) {
3187  updateEigenSystem(cell);
3188  }
3189 
3190  do {
3191  for (i = 0; i < cell->dim; i++) {
3192  ept[i] = cell->eigenMin[i] + gsl_rng_uniform(rng)*(cell->eigenMax[i] - cell->eigenMin[i]);
3193  }
3194 
3195  fromEigenFrame(cell->dim, cell->ptsCovEigenVects, ept, pt);
3196 
3197  for (i = 0; i < cell->dim; i++) {
3198  pt[i] += cell->ptsMean[i];
3199  }
3200  } while (!inBounds(pt, cell->lowerLeft, cell->upperRight, cell->dim));
3201 
3202  XLALFree(ept);
3203  }
3204 }
3205 
3206 static int inEigenBox(LALInferenceKDTree *cell, REAL8 *pt) {
3207  REAL8 *shiftedPt, *ept;
3208  size_t i;
3209 
3210  if (cell->eigenFrameStale) {
3211  updateEigenSystem(cell);
3212  }
3213 
3214  shiftedPt = XLALCalloc(cell->dim, sizeof(REAL8));
3215  ept = XLALCalloc(cell->dim, sizeof(REAL8));
3216 
3217  for (i = 0; i < cell->dim; i++) {
3218  shiftedPt[i] = pt[i] - cell->ptsMean[i];
3219  }
3220 
3221  toEigenFrame(cell->dim, cell->ptsCovEigenVects, shiftedPt, ept);
3222 
3223  for (i = 0; i < cell->dim; i++) {
3224  if (ept[i] < cell->eigenMin[i] || ept[i] > cell->eigenMax[i]) {
3225  XLALFree(shiftedPt);
3226  XLALFree(ept);
3227  return 0;
3228  }
3229  }
3230 
3231  XLALFree(shiftedPt);
3232  XLALFree(ept);
3233  return 1;
3234 }
3235 
3237  REAL8 *proposed, size_t Npts) {
3238  LALInferenceKDTree *currentCell = LALInferenceKDFindCell(tree, current, Npts);
3239  LALInferenceKDTree *proposedCell = LALInferenceKDFindCell(tree, proposed, Npts);
3240 
3241  LALInferenceKDTree *topCell = tree;
3242 
3243  size_t npts = topCell->npts;
3244 
3245  REAL8 logCurrentVolume, logProposedVolume;
3246 
3247  if (currentCell->npts > 1) {
3248  if (currentCell->eigenFrameStale) {
3249  updateEigenSystem(currentCell);
3250  }
3251 
3252  if (!inEigenBox(currentCell, current)) {
3253  return log(0.0); /* If the current point is not in the eigen box
3254  of the current cell, then we cannot jump
3255  back there. */
3256  } else {
3257  logCurrentVolume = LALInferenceKDLogCellEigenVolume(currentCell);
3258  }
3259  } else {
3260  logCurrentVolume = LALInferenceKDLogCellVolume(currentCell);
3261  }
3262 
3263  if (proposedCell->npts > 1) {
3264  /* Since we just proposed out of this cell, its eigenframe should
3265  *not* be stale. */
3266  if (proposedCell->eigenFrameStale) {
3267  XLAL_ERROR_REAL8(XLAL_EINVAL, "proposed cell eigen-frame is stale");
3268  }
3269 
3270  logProposedVolume = LALInferenceKDLogCellEigenVolume(proposedCell);
3271  } else {
3272  logProposedVolume = LALInferenceKDLogCellVolume(proposedCell);
3273  }
3274 
3275  REAL8 logCurrentCellFactor = log((REAL8)currentCell->npts / npts);
3276  REAL8 logProposedCellFactor = log((REAL8)proposedCell->npts / npts);
3277 
3278  return logCurrentCellFactor + logCurrentVolume - logProposedCellFactor - logProposedVolume;
3279 }
3280 
3282  gsl_matrix *matrix,
3283  UINT4 dim
3284  )
3285 {
3286  gsl_matrix *m = NULL;
3287  gsl_vector *eigen = NULL;
3288  gsl_eigen_symm_workspace *workspace = NULL;
3289  UINT4 i;
3290 
3291  /* copy input matrix */
3292  m = gsl_matrix_alloc( dim,dim );
3293  gsl_matrix_memcpy( m, matrix);
3294 
3295  /* prepare variables */
3296  eigen = gsl_vector_alloc ( dim );
3297  workspace = gsl_eigen_symm_alloc ( dim );
3298 
3299  /* compute the eigen values */
3300  gsl_eigen_symm ( m, eigen, workspace );
3301 
3302  /* test the result */
3303  for (i = 0; i < dim; i++)
3304  {
3305  /* printf("diag: %f | eigen[%d]= %f\n", gsl_matrix_get( matrix,i,i), i, eigen->data[i]);*/
3306  if (eigen->data[i]<0)
3307  {
3308  printf("NEGATIVE EIGEN VALUE!!! PANIC\n");
3309  return 0;
3310  }
3311  }
3312 
3313  /* freeing unused stuff */
3314  gsl_eigen_symm_free( workspace);
3315  gsl_matrix_free(m);
3316  gsl_vector_free(eigen);
3317 
3318  return 1;
3319 }
3320 
3321 /* Reference: http://www.mail-archive.com/help-gsl@gnu.org/msg00631.html*/
3322 void
3325  gsl_matrix *matrix,
3326  UINT4 dim,
3327  RandomParams *randParam
3328  )
3329 {
3330  UINT4 i=0;
3331  gsl_matrix *work=NULL;
3332  gsl_vector *result = NULL;
3333 
3334  /* check input arguments */
3335  if (!vector || !matrix || !randParam)
3337 
3338  if (dim<1)
3340 
3341  /* copy matrix into workspace */
3342  work = gsl_matrix_alloc(dim,dim);
3343  gsl_matrix_memcpy( work, matrix );
3344 
3345  /* compute the cholesky decomposition */
3346  gsl_linalg_cholesky_decomp(work);
3347 
3348  /* retrieve the normal distributed random numbers (LAL procedure) */
3349  XLALNormalDeviates( vector, randParam );
3350 
3351  /* store this into a gsl vector */
3352  result = gsl_vector_alloc ( (int)dim );
3353  for (i = 0; i < dim; i++)
3354  {
3355  gsl_vector_set (result, i, vector->data[i]);
3356  }
3357 
3358  /* compute the matrix-vector multiplication */
3359  gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasNonUnit, work, result);
3360 
3361  /* recopy the results */
3362  for (i = 0; i < dim; i++)
3363  {
3364  vector->data[i]=gsl_vector_get (result, i);
3365  }
3366 
3367  /* free unused stuff */
3368  gsl_matrix_free(work);
3369  gsl_vector_free(result);
3370 
3371 }
3372 
3373 void
3376  gsl_matrix *matrix,
3377  UINT4 dim,
3378  UINT4 n,
3379  RandomParams *randParam
3380  )
3381 {
3382  REAL4Vector *dummy=NULL;
3383  REAL4 chi=0.0, factor;
3384  UINT4 i;
3385 
3386  /* check input arguments */
3387  if (!vector || !matrix || !randParam)
3389 
3390  if (dim<1)
3392 
3393  if (n<1)
3395 
3396 
3397  /* first draw from MVN */
3398  XLALMultiNormalDeviates( vector, matrix, dim, randParam);
3399 
3400  /* then draw from chi-square with n degrees of freedom;
3401  this is the sum d_i*d_i with d_i drawn from a normal
3402  distribution. */
3403  dummy = XLALCreateREAL4Vector( n );
3404  XLALNormalDeviates( dummy, randParam );
3405 
3406  /* calculate the chisquare distributed value */
3407  for (i=0; i<n; i++)
3408  {
3409  chi+=dummy->data[i]*dummy->data[i];
3410  }
3411 
3412  /* destroy the helping vector */
3413  XLALDestroyREAL4Vector( dummy );
3414 
3415  /* now, finally, calculate the distribution value */
3416  factor=sqrt(n/chi);
3417  for (i=0; i<dim; i++)
3418  {
3419  vector->data[i]*=factor;
3420  }
3421 
3422 }
3423 
3424 /* Calculate shortest angular distance between a1 and a2 */
3426  double raw = (a2>a1 ? a2-a1 : a1-a2);
3427  return(raw>LAL_PI ? 2.0*LAL_PI - raw : raw);
3428 }
3429 
3430 /* Calculate the variance of a modulo-2pi distribution */
3432  int i=0;
3433  REAL8 ang_mean=0.0;
3434  REAL8 var=0.0;
3435  REAL8 ms,mc;
3436  /* Calc mean */
3437  for(i=0,ms=0.0,mc=0.0;i<N;i++) {
3438  ms+=sin(*(REAL8 *)LALInferenceGetVariable(list[i],pname));
3439  mc+=cos(*(REAL8 *)LALInferenceGetVariable(list[i],pname));
3440  }
3441  ms/=N; mc/=N;
3442  ang_mean=atan2(ms,mc);
3443  ang_mean = ang_mean<0? 2.0*LAL_PI + ang_mean : ang_mean;
3444  /* calc variance */
3445  for(i=0;i<N;i++) var+=LALInferenceAngularDistance(*(REAL8 *)LALInferenceGetVariable(list[i],pname),ang_mean)*LALInferenceAngularDistance(*(REAL8 *)LALInferenceGetVariable(list[i],pname),ang_mean);
3446  return(var/(REAL8)N);
3447 }
3448 
3449 /* Sanity check the data structures and print any encountered errors */
3451 {
3452  INT4 retcode=0;
3453  if(!state) {
3454  fprintf(stderr,"NULL state pointer!\n");
3455  return(1);
3456  }
3457 
3458  LALInferenceIFOData *data=state->data;
3459  if(!data) {
3460  fprintf(stderr,"NULL data pointer!\n");
3461  return(1);
3462  }
3463  while(data){
3464  retcode=0;
3465  fprintf(stderr,"Checking %s:\n",data->name);
3466  if(data->timeData) {
3467  fprintf(stderr,"Checking timeData: ");
3468  if(!(retcode|=checkREAL8TimeSeries(data->timeData))) fprintf(stderr," OK\n");
3469  }
3470  if(data->whiteTimeData) {
3471  fprintf(stderr,"Checking whiteTimeData: ");
3472  if(!(retcode|=checkREAL8TimeSeries(data->whiteTimeData))) fprintf(stderr," OK\n");
3473  }
3474  if(data->windowedTimeData) {
3475  fprintf(stderr,"Checking windowedTimeData: ");
3476  if(!(retcode|=checkREAL8TimeSeries(data->windowedTimeData))) fprintf(stderr," OK\n");
3477  }
3478  if(data->freqData) {
3479  fprintf(stderr,"Checking freqData: ");
3480  if(!(retcode|=checkCOMPLEX16FrequencySeries(data->freqData))) fprintf(stderr," OK\n");
3481  }
3482  if(data->whiteFreqData) {
3483  fprintf(stderr,"Checking whiteFreqData: ");
3484  if(!(retcode|=checkCOMPLEX16FrequencySeries(data->whiteFreqData))) fprintf(stderr," OK\n");
3485  }
3486  if(data->oneSidedNoisePowerSpectrum) {
3487  fprintf(stderr,"Checking oneSidedNoisePowerSpectrum: ");
3488  if(!(retcode|=checkREAL8FrequencySeries(data->oneSidedNoisePowerSpectrum))) fprintf(stderr," OK\n");
3489  }
3490  data=data->next;
3491  }
3492 
3493  LALInferenceThreadState *thread=state->threads;
3494  if(!thread) {
3495  fprintf(stderr,"NULL thread pointer!\n");
3496  return(1);
3497  }
3498  for(INT4 i=0;i<state->nthreads;i++){
3499  LALInferenceModel *model = state->threads[i].model;
3500  if(!model) {
3501  fprintf(stderr,"NULL model pointer in thread %d!\n",i);
3502  return(1);
3503  }
3504  retcode=0;
3505  if(model->timehPlus) {
3506  fprintf(stderr,"Checking timehPlus in thread %d: ",i);
3507  if(!(retcode|=checkREAL8TimeSeries(model->timehPlus))) fprintf(stderr," OK\n");
3508  }
3509  if(model->timehCross) {
3510  fprintf(stderr,"Checking timehCross in thread %d: ",i);
3511  if(!(retcode|=checkREAL8TimeSeries(model->timehCross))) fprintf(stderr," OK\n");
3512  }
3513  if(model->freqhPlus) {
3514  fprintf(stderr,"Checking freqhPlus in thread %d: ",i);
3515  if(!(retcode|=checkCOMPLEX16FrequencySeries(model->freqhPlus))) fprintf(stderr," OK\n");
3516  }
3517  if(model->freqhCross) {
3518  fprintf(stderr,"Checking freqhCross in thread %d: ",i);
3519  if(!(retcode|=checkCOMPLEX16FrequencySeries(model->freqhCross))) fprintf(stderr," OK\n");
3520  }
3521  }
3522 
3523  return(retcode);
3524 }
3525 
3526 static INT4 checkREAL8Value(REAL8 val);
3527 
3529 {
3530  UINT4 i;
3531  INT4 retcode=0;
3532  if(!series) fprintf(stderr,"Null REAL8TimeSeries *\n");
3533  else {
3534  if(!series->data) fprintf(stderr,"NULL REAL8Sequence structure in REAL8TimeSeries\n");
3535  else {
3536  if(!series->data->data) fprintf(stderr,"NULL REAL8[] in REAL8Sequence\n");
3537  else {
3538  for(i=0;i<series->data->length;i++) {if(checkREAL8Value(series->data->data[i])) {if(!retcode) fprintf(stderr,"Found value %lf at index %i\n",series->data->data[i],i); retcode+=1;}}
3539  }
3540  }
3541  }
3542  if(retcode>1) fprintf(stderr,"and %i more times\n",retcode);
3543  return(retcode);
3544 }
3545 
3547 {
3548  UINT4 i;
3549  INT4 retcode=0;
3550  if(!series) fprintf(stderr,"Null REAL8FrequencySeries *\n");
3551  else {
3552  if(!series->data) fprintf(stderr,"NULL REAL8Sequence structure in REAL8FrequencySeries\n");
3553  else {
3554  if(!series->data->data) fprintf(stderr,"NULL REAL8[] in REAL8Sequence\n");
3555  else {
3556  for(i=0;i<series->data->length;i++) {if(checkREAL8Value(series->data->data[i])) {if(!retcode) fprintf(stderr,"Found value %lf at index %i\n",series->data->data[i],i); retcode+=1;}}
3557  }
3558  }
3559  }
3560  if(retcode>1) fprintf(stderr,"and %i more times\n",retcode);
3561  return(retcode);
3562 }
3563 
3565 {
3566  UINT4 i;
3567  INT4 retcode=0;
3568  if(!series) fprintf(stderr,"Null COMPLEX16FrequencySeries *\n");
3569  else {
3570  if(!series->data) fprintf(stderr,"NULL COMPLEX16Sequence structure in COMPLEX16FrequencySeries\n");
3571  else {
3572  if(!series->data->data) fprintf(stderr,"NULL REAL8[] in COMPLEX16Sequence\n");
3573  else {
3574  for(i=0;i<series->data->length;i++) {if(checkREAL8Value(creal(series->data->data[i]))) {if(!retcode) fprintf(stderr,"Found real value %lf at index %i\n",creal(series->data->data[i]),i); retcode+=1;}
3575  if(checkREAL8Value(cimag(series->data->data[i]))) {if(!retcode) fprintf(stderr,"Found imag value %lf at index %i\n",cimag(series->data->data[i]),i); retcode+=1;} }
3576  }
3577  }
3578  }
3579  if(retcode>1) fprintf(stderr,"and %i more times\n",retcode);
3580  return(retcode);
3581 }
3582 
3584 {
3585  if(isinf(val)) return 1;
3586  if(isnan(val)) return 1;
3587  return 0;
3588 }
3589 
3590 void LALInferenceDumpWaveforms(LALInferenceModel *model, const char *basefilename)
3591 {
3592  UINT4 i;
3593  FILE *dumpfile=NULL;
3594  char basename[1024]="template_dump";
3595  char filename[1100]="";
3596  if(basefilename!=NULL)
3597  {
3598  sprintf(basename,"%s",basefilename);
3599  }
3600 
3601  if(model->timehPlus && model->timehCross){
3602  snprintf(filename,sizeof(filename),"%s_time.txt",basename);
3603  dumpfile=fopen(filename,"w");
3605  REAL8 dt=model->timehPlus->deltaT;
3606  for(i=0;i<model->timehPlus->data->length;i++) fprintf(dumpfile,"%10.20e %10.20e %10.20e\n",epoch+i*dt,model->timehPlus->data->data[i],model->timehCross->data->data[i]);
3607  fclose(dumpfile);
3608  fprintf(stdout,"Dumped file %s\n",filename);
3609  }
3610  if(model->freqhPlus && model->freqhCross){
3611  snprintf(filename,sizeof(filename),"%s_freq.txt",basename);
3612  dumpfile=fopen(filename,"w");
3613  REAL8 fLow=model->freqhPlus->f0;
3614  REAL8 df=model->freqhPlus->deltaF;
3615  for(i=0;i<model->freqhPlus->data->length;i++) fprintf(dumpfile,"%10.20e %10.20e %10.20e %10.20e %10.20e\n",fLow+i*df,creal(model->freqhPlus->data->data[i]), cimag(model->freqhPlus->data->data[i]),creal(model->freqhCross->data->data[i]), cimag(model->freqhCross->data->data[i]));
3616  fclose(dumpfile);
3617  fprintf(stdout,"Dumped file %s\n",filename);
3618  }
3619 }
3620 
3621 static void REAL8Vector_fwrite(FILE *f, REAL8Vector *vec);
3622 static void REAL8Vector_fwrite(FILE *f, REAL8Vector *vec)
3623 {
3624  if(1!=fwrite(&(vec->length),sizeof(UINT4),1,f)) XLAL_ERROR_VOID(XLAL_EIO);
3625  if(vec->length!=fwrite(vec->data,sizeof(REAL8),vec->length,f)) XLAL_ERROR_VOID(XLAL_EIO);
3626 }
3627 
3628 static void COMPLEX16Vector_fwrite(FILE *f, COMPLEX16Vector *vec);
3629 static void COMPLEX16Vector_fwrite(FILE *f, COMPLEX16Vector *vec)
3630 {
3631  if(1!=fwrite(&(vec->length),sizeof(UINT4),1,f)) XLAL_ERROR_VOID(XLAL_EIO);
3632  if(vec->length!=fwrite(vec->data,sizeof(COMPLEX16),vec->length,f)) XLAL_ERROR_VOID(XLAL_EIO);
3633 }
3634 
3635 static void INT4Vector_fwrite(FILE *f, INT4Vector *vec);
3636 static void INT4Vector_fwrite(FILE *f, INT4Vector *vec)
3637 {
3638  fwrite(&(vec->length),sizeof(vec->length),1,f);
3639  fwrite(vec->data,sizeof(vec->data[0]),vec->length,f);
3640 }
3641 
3642 static void UINT4Vector_fwrite(FILE *f, UINT4Vector *vec);
3643 static void UINT4Vector_fwrite(FILE *f, UINT4Vector *vec)
3644 {
3645  if(1!=fwrite(&(vec->length),sizeof(vec->length),1,f)) XLAL_ERROR_VOID(XLAL_EIO);
3646  if(vec->length!=fwrite(vec->data,sizeof(vec->data[0]),vec->length,f)) XLAL_ERROR_VOID(XLAL_EIO);
3647 }
3648 
3649 static REAL8Vector * REAL8Vector_fread(FILE *f);
3651 {
3652  REAL8Vector *out=NULL;
3653  UINT4 size;
3654  if(1!=fread(&size,sizeof(size),1,f)) XLAL_ERROR_NULL(XLAL_EIO);
3656  if(size!=fread(out->data,sizeof(REAL8),size,f)) XLAL_ERROR_NULL(XLAL_EIO);
3657  return out;
3658 }
3659 
3660 static COMPLEX16Vector * COMPLEX16Vector_fread(FILE *f);
3662 {
3663  COMPLEX16Vector *out=NULL;
3664  UINT4 size;
3665  if(1!=fread(&size,sizeof(size),1,f)) XLAL_ERROR_NULL(XLAL_EIO);
3667  if(size!=fread(out->data,sizeof(COMPLEX16),size,f)) XLAL_ERROR_NULL(XLAL_EIO);
3668  return out;
3669 }
3670 
3671 static INT4Vector * INT4Vector_fread(FILE *f);
3672 static INT4Vector * INT4Vector_fread(FILE *f)
3673 {
3674  INT4 size = 0;
3675  INT4Vector *vec = NULL;
3676 
3677  fread(&size,sizeof(size),1,f);
3678  vec = XLALCreateINT4Vector(size);
3679  fread(vec->data, sizeof(INT4), size, f);
3680  return vec;
3681 }
3682 
3683 static UINT4Vector * UINT4Vector_fread(FILE *f);
3685 {
3686  UINT4 size = 0;
3687  UINT4Vector *vec = NULL;
3688 
3689  if(1!=fread(&size,sizeof(size),1,f)) XLAL_ERROR_NULL(XLAL_EIO);
3690  vec = XLALCreateUINT4Vector(size);
3691  if(size!=fread(vec->data, sizeof(UINT4), size, f)) XLAL_ERROR_NULL(XLAL_EIO);
3692  return vec;
3693 }
3694 
3696 {
3697  int i=0;
3698  char termchar='\n';
3699  if(!vars) return -1;
3700  LALInferenceVariableItem *item=vars->head;
3701  /* Write initial info (number of dimensions) */
3702  if(1!=fwrite(&(vars->dimension),sizeof(vars->dimension),1,file)) XLAL_ERROR(XLAL_EIO);
3703  /* Write each item */
3704  for(i=0;item;i++)
3705  {
3706  /* Name */
3707  fputs(item->name,file);
3708  if(1!=fwrite(&termchar,sizeof(char),1,file)) XLAL_ERROR(XLAL_EIO);
3709  if(1!=fwrite(&(item->type),sizeof(item->type),1,file)) XLAL_ERROR(XLAL_EIO);
3710  if(1!=fwrite(&(item->vary),sizeof(item->vary),1,file)) XLAL_ERROR(XLAL_EIO);
3711  switch(item->type)
3712  {
3714  {
3715  gsl_matrix *matrix=*(gsl_matrix **)item->value;
3716  if(1!=fwrite(&(matrix->size1),sizeof(matrix->size1),1,file)) XLAL_ERROR(XLAL_EIO);
3717  if(1!=fwrite(&(matrix->size2),sizeof(matrix->size2),1,file)) XLAL_ERROR(XLAL_EIO);
3718  gsl_matrix_fwrite(file,matrix);
3719  break;
3720  }
3722  {
3723  REAL8Vector *vec=*(REAL8Vector **)item->value;
3724  REAL8Vector_fwrite(file,vec);
3725  break;
3726  }
3728  {
3729  COMPLEX16Vector *vec=*(COMPLEX16Vector **)item->value;
3731  break;
3732  }
3734  {
3735  UINT4Vector *vec = *(UINT4Vector **)item->value;
3736  UINT4Vector_fwrite(file, vec);
3737  break;
3738  }
3740  {
3741  INT4Vector *vec = *(INT4Vector **)item->value;
3742  INT4Vector_fwrite(file, vec);
3743  break;
3744  }
3745  case LALINFERENCE_string_t:
3746  {
3747  char *value = *((char **)item->value);
3748  size_t len = strlen(value);
3749  if(1!=fwrite(&len, sizeof(size_t),1, file)) XLAL_ERROR(XLAL_EIO);
3750  if(len!=fwrite(value, sizeof(char), len, file)) XLAL_ERROR(XLAL_EIO);
3751  break;
3752  }
3754  {
3756  if(1!=fwrite(ph, sizeof(LALInferenceMCMCRunPhase), 1, file)) XLAL_ERROR(XLAL_EIO);
3757  break;
3758  }
3760  {
3761  /* Write void_ptr as NULL, so fails if used without
3762  initialization on restart. */
3763  void *out = NULL;
3764  if(1!=fwrite(&out,sizeof(void*),1,file)) XLAL_ERROR(XLAL_EIO);
3765  break;
3766  }
3767  default:
3768  {
3769  if(1!=fwrite(item->value,LALInferenceTypeSize[item->type],1,file)) XLAL_ERROR(XLAL_EIO);
3770  break;
3771  }
3772  }
3773  item=item->next;
3774  }
3775  return i;
3776 }
3777 
3779 {
3780  UINT4 j;
3781  UINT4 dim;
3784  LALInferenceVariables *ret_vars = XLALCalloc(1, sizeof(LALInferenceVariables));
3785 
3786  /* Number of variables to read */
3787  if(1!=fread(&dim, sizeof(vars->dimension), 1, stream)) XLAL_ERROR_NULL(XLAL_EIO);
3788 
3789  /* Now read them in */
3790  for(;dim>0;dim--)
3791  {
3792  char name[VARNAME_MAX];
3795  if(!fgets(name,sizeof(name),stream)) XLAL_ERROR_NULL(XLAL_EIO);
3796 
3797  for(j=0;j<sizeof(name);j++) if(name[j]=='\n') {name[j]='\0'; break;}
3798  if(j==sizeof(name))
3799  {
3800  fprintf(stderr,"ERROR reading saved variable!");
3801  return(NULL);
3802  }
3803  if(1!=fread(&type,sizeof(type),1,stream)) XLAL_ERROR_NULL(XLAL_EIO);
3804  if(1!=fread(&vary,sizeof(vary),1,stream)) XLAL_ERROR_NULL(XLAL_EIO);
3805  switch(type)
3806  {
3808  {
3809  size_t size1,size2;
3810  if(1!=fread(&size1,sizeof(size1),1,stream)) XLAL_ERROR_NULL(XLAL_EIO);
3811  if(1!=fread(&size2,sizeof(size2),1,stream)) XLAL_ERROR_NULL(XLAL_EIO);
3812  gsl_matrix *matrix=gsl_matrix_alloc(size1,size2);
3813  gsl_matrix_fread(stream,matrix);
3814  LALInferenceAddVariable(vars,name,&matrix,type,vary);
3815 
3816  break;
3817  }
3819  {
3820  REAL8Vector *v=REAL8Vector_fread(stream);
3821  LALInferenceAddVariable(vars,name,&v,type,vary);
3822 
3823  break;
3824  }
3826  {
3828  LALInferenceAddVariable(vars,name,&v,type,vary);
3829 
3830  break;
3831  }
3833  {
3834  UINT4Vector *vec = UINT4Vector_fread(stream);
3835  LALInferenceAddVariable(vars,name,&vec,type,vary);
3836  break;
3837  }
3839  {
3840  INT4Vector *vec = INT4Vector_fread(stream);
3841  LALInferenceAddVariable(vars,name,&vec,type,vary);
3842  break;
3843  }
3844  case LALINFERENCE_string_t:
3845  {
3846  size_t len = 0;
3847  char *string = NULL;
3848 
3849  if(1!=fread(&len, sizeof(size_t), 1, stream)) XLAL_ERROR_NULL(XLAL_EIO);
3850  string = XLALCalloc(sizeof(char), len+1); /* One extra character: '\0' */
3851  if(len!=fread(string, sizeof(char), len, stream)) XLAL_ERROR_NULL(XLAL_EIO);
3852  LALInferenceAddVariable(vars,name,&string,type,vary);
3853  break;
3854  }
3856  {
3858  if(1!=fread(ph, sizeof(LALInferenceMCMCRunPhase), 1, stream)) XLAL_ERROR_NULL(XLAL_EIO);
3859  LALInferenceAddVariable(vars,name,&ph,type,vary);
3860  break;
3861  }
3863  {
3864  void *ptr = NULL;
3865  if(1!=fread(&ptr,sizeof(void *), 1, stream)) XLAL_ERROR_NULL(XLAL_EIO);
3866  LALInferenceAddVariable(vars,name,&ptr,type,vary);
3867  break;
3868  }
3869  default:
3870  {
3871  void *value=NULL;
3872  UINT4 storagesize=LALInferenceTypeSize[type];
3873  value=XLALCalloc(1,storagesize);
3874  if(1!=fread(value, storagesize, 1, stream)) XLAL_ERROR_NULL(XLAL_EIO);
3875  LALInferenceAddVariable(vars,name,value,type,vary);
3876  }
3877  }
3878  }
3879 
3880  /* LALInferenceAddVariable() builds the array backwards, so reverse it. */
3881  item = vars->head;
3882  for (item = vars->head; item; item = item->next)
3883  {
3884  LALInferenceAddVariable(ret_vars, item->name, item->value, item->type, item->vary);
3885  }
3886  /* Free the memory for the original (reversed) vars */
3887  while(vars->head)
3888  {
3889  item=LALInferencePopVariableItem(vars,vars->head->name);
3890  if(item->value) XLALFree(item->value);
3891  XLALFree(item);
3892  }
3893  XLALFree(vars);
3894 
3895  return ret_vars;
3896 }
3897 
3899 {
3900  UINT4 i=0;
3901  int errnum;
3902  for(i=0;i<N;i++)
3903  {
3905  if(errnum!=XLAL_SUCCESS) XLAL_ERROR(XLAL_EIO,"Unable to write variables as binary\n");
3906  }
3907  return N;
3908 }
3909 
3911 {
3912  UINT4 i=0;
3913  int errnum;
3914  for(i=0;i<N;i++){
3916  if(errnum!=XLAL_SUCCESS) XLAL_ERROR(XLAL_EIO,"Unable to read variables from binary file\n");
3917  }
3918  return N;
3919 }
3920 
3922 {
3923  int flag=0;
3924  flag|=gsl_rng_fwrite (file , runState->GSLrandom);
3928  return flag;
3929 }
3930 
3932 {
3933  gsl_rng_fread(file, runState->GSLrandom);
3937 
3938  return 0;
3939 }
3940 
3942 /* Typed version of LALInferenceAddVariable for INT4 values.*/
3943 {
3944  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_INT4_t,vary);
3945 }
3946 
3948 /* Typed version of LALInferenceGetVariable for INT4 values.*/
3949 {
3950 
3952  XLAL_ERROR(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
3953  }
3954 
3955  INT4* rvalue=(INT4*)LALInferenceGetVariable(vars,name);
3956 
3957  return *rvalue;
3958 }
3959 
3960 void LALInferenceSetINT4Variable(LALInferenceVariables* vars,const char* name,INT4 value){
3961  LALInferenceSetVariable(vars,name,(void*)&value);
3962 }
3963 
3965 /* Typed version of LALInferenceAddVariable for INT8 values.*/
3966 {
3967  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_INT8_t,vary);
3968 }
3969 
3971 /* Typed version of LALInferenceGetVariable for INT8 values.*/
3972 {
3973 
3975  XLAL_ERROR(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
3976  }
3977 
3978  INT8* rvalue=(INT8*)LALInferenceGetVariable(vars,name);
3979 
3980  return *rvalue;
3981 }
3982 
3983 void LALInferenceSetINT8Variable(LALInferenceVariables* vars,const char* name,INT8 value){
3984  LALInferenceSetVariable(vars,name,(void*)&value);
3985 }
3986 
3988 /* Typed version of LALInferenceAddVariable for UINT4 values.*/
3989 {
3990  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_UINT4_t,vary);
3991 }
3992 
3994 /* Typed version of LALInferenceGetVariable for UINT4 values.*/
3995 {
3996 
3998  XLAL_ERROR(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
3999  }
4000 
4001  UINT4* rvalue=(UINT4*)LALInferenceGetVariable(vars,name);
4002 
4003  return *rvalue;
4004 }
4005 
4006 void LALInferenceSetUINT4Variable(LALInferenceVariables* vars,const char* name,UINT4 value){
4007  LALInferenceSetVariable(vars,name,(void*)&value);
4008 }
4009 
4011 /* Typed version of LALInferenceAddVariable for REAL4 values.*/
4012 {
4013  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_REAL4_t,vary);
4014 }
4015 
4017 /* Typed version of LALInferenceGetVariable for REAL4 values.*/
4018 {
4019 
4021  XLAL_ERROR_REAL4(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4022  }
4023 
4024  REAL4* rvalue=(REAL4*)LALInferenceGetVariable(vars,name);
4025 
4026  return *rvalue;
4027 }
4028 
4029 void LALInferenceSetREAL4Variable(LALInferenceVariables* vars,const char* name,REAL4 value){
4030  LALInferenceSetVariable(vars,name,(void*)&value);
4031 }
4032 
4034 /* Typed version of LALInferenceAddVariable for REAL8 values.*/
4035 {
4036  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_REAL8_t,vary);
4037 }
4038 
4040 /* Typed version of LALInferenceGetVariable for REAL8 values.*/
4041 {
4042 
4044  XLAL_ERROR_REAL8(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4045  }
4046 
4047  REAL8* rvalue=(REAL8*)LALInferenceGetVariable(vars,name);
4048 
4049  return *rvalue;
4050 }
4051 
4052 void LALInferenceSetREAL8Variable(LALInferenceVariables* vars,const char* name,REAL8 value){
4053  LALInferenceSetVariable(vars,name,(void*)&value);
4054 }
4055 
4057 /* Typed version of LALInferenceAddVariable for COMPLEX8 values.*/
4058 {
4059  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_COMPLEX8_t,vary);
4060 }
4061 
4063 /* Typed version of LALInferenceGetVariable for COMPLEX8 values.*/
4064 {
4065 
4067 
4068  return *rvalue;
4069 }
4070 
4072  LALInferenceSetVariable(vars,name,(void*)&value);
4073 }
4074 
4076 /* Typed version of LALInferenceAddVariable for COMPLEX16 values.*/
4077 {
4078  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_COMPLEX16_t,vary);
4079 }
4080 
4082 /* Typed version of LALInferenceGetVariable for COMPLEX16 values.*/
4083 {
4084 
4086 
4087  return *rvalue;
4088 }
4089 
4091  LALInferenceSetVariable(vars,name,(void*)&value);
4092 }
4093 
4094 void LALInferenceAddgslMatrixVariable(LALInferenceVariables * vars, const char * name, gsl_matrix* value, LALInferenceParamVaryType vary)
4095 /* Typed version of LALInferenceAddVariable for gsl_matrix values.*/
4096 {
4097  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_gslMatrix_t,vary);
4098 }
4099 
4100 gsl_matrix* LALInferenceGetgslMatrixVariable(LALInferenceVariables * vars, const char * name)
4101 /* Typed version of LALInferenceGetVariable for gsl_matrix values.*/
4102 {
4103 
4105  XLAL_ERROR_NULL(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4106  }
4107 
4108  gsl_matrix* rvalue=*(gsl_matrix **)LALInferenceGetVariable(vars,name);
4109 
4110  return rvalue;
4111 }
4112 
4113 void LALInferenceSetgslMatrixVariable(LALInferenceVariables* vars,const char* name,gsl_matrix* value){
4114  LALInferenceSetVariable(vars,name,(void*)&value);
4115 }
4116 
4118 /* Typed version of LALInferenceAddVariable for REAL8Vector values.*/
4119 {
4120  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_REAL8Vector_t,vary);
4121 }
4122 
4124 /* Typed version of LALInferenceGetVariable for REAL8Vector values.*/
4125 {
4126 
4128  XLAL_ERROR_NULL(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4129  }
4130 
4132 
4133  return rvalue;
4134 }
4135 
4137  LALInferenceSetVariable(vars,name,(void*)&value);
4138 }
4139 
4141 /* Typed version of LALInferenceAddVariable for COMPLEX16Vector values.*/
4142 {
4144 }
4145 
4147 /* Typed version of LALInferenceGetVariable for COMPLEX16Vector values.*/
4148 {
4149 
4151  XLAL_ERROR_NULL(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4152  }
4153 
4155 
4156  return rvalue;
4157 }
4158 
4160  LALInferenceSetVariable(vars,name,(void*)&value);
4161 }
4162 
4164 /* Typed version of LALInferenceAddVariable for UINT4Vector values.*/
4165 {
4166  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_UINT4Vector_t,vary);
4167 }
4168 
4170 /* Typed version of LALInferenceAddVariable for INT4Vector values.*/
4171 {
4172  LALInferenceAddVariable(vars,name,(void*)&value,LALINFERENCE_INT4Vector_t,vary);
4173 }
4174 
4176 /* Typed version of LALInferenceGetVariable for UINT4Vector values.*/
4177 {
4178 
4180  XLAL_ERROR_NULL(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4181  }
4182 
4184 
4185  return rvalue;
4186 }
4187 
4189 /* Typed version of LALInferenceGetVariable for INT4Vector values.*/
4190 {
4191 
4193  XLAL_ERROR_NULL(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4194  }
4195 
4197 
4198  return rvalue;
4199 }
4200 
4202  LALInferenceSetVariable(vars,name,(void*)&value);
4203 }
4204 
4206  LALInferenceSetVariable(vars,name,(void*)&value);
4207 }
4208 
4210 /* Typed version of LALInferenceAddVariable for LALInferenceMCMCRunPhase values.*/
4211 {
4213 }
4214 
4216 /* Typed version of LALInferenceGetVariable for LALInferenceMCMCRunPhase values.*/
4217 {
4218 
4220  XLAL_ERROR_NULL(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4221  }
4222 
4224 
4225  return rvalue;
4226 }
4227 
4229  LALInferenceSetVariable(vars,name,(void*)&value);
4230 }
4231 
4232 void LALInferenceAddstringVariable(LALInferenceVariables * vars, const char * name, const CHAR* value, LALInferenceParamVaryType vary)
4233 /* Typed version of LALInferenceAddVariable for CHAR values.*/
4234 {
4236 }
4237 
4239 /* Typed version of LALInferenceGetVariable for CHAR values.*/
4240 {
4241 
4243  XLAL_ERROR_NULL(XLAL_ETYPE, "Entry \"%s\" not found or of wrong type.", name);
4244  }
4245 
4246  CHAR* rvalue=*(CHAR**)LALInferenceGetVariable(vars,name);
4247 
4248  return rvalue;
4249 }
4250 
4251 void LALInferenceSetstringVariable(LALInferenceVariables* vars,const char* name, const CHAR* value){
4252  LALInferenceSetVariable(vars,name,&value);
4253 }
4254 
4256  REAL8Vector *deltaAmps,
4257  REAL8Vector *deltaPhases,
4258  COMPLEX16FrequencySeries *calFactor) {
4259  size_t i = 0;
4260  gsl_interp_accel *ampAcc = NULL, *phaseAcc = NULL;
4261  gsl_interp *ampInterp = NULL, *phaseInterp = NULL;
4262 
4263  int status = XLAL_SUCCESS;
4264  const char *fmt = "";
4265 
4266  size_t N = 0;
4267 
4268  if (logfreqs == NULL || deltaAmps == NULL || deltaPhases == NULL || calFactor == NULL) {
4269  status = XLAL_EINVAL;
4270  fmt = "bad input";
4271  goto cleanup;
4272  }
4273 
4274  if (logfreqs->length != deltaAmps->length || deltaAmps->length != deltaPhases->length) {
4275  status = XLAL_EINVAL;
4276  fmt = "input lengths differ";
4277  goto cleanup;
4278  }
4279 
4280  N = logfreqs->length;
4281 
4282  ampInterp = gsl_interp_alloc(gsl_interp_cspline, N);
4283  phaseInterp = gsl_interp_alloc(gsl_interp_cspline, N);
4284 
4285  if (ampInterp == NULL || phaseInterp == NULL) {
4286  status = XLAL_ENOMEM;
4287  fmt = "could not allocate GSL interpolation objects";
4288  goto cleanup;
4289  }
4290 
4291  ampAcc = gsl_interp_accel_alloc();
4292  phaseAcc = gsl_interp_accel_alloc();
4293 
4294  if (ampAcc == NULL || phaseAcc == NULL) {
4295  status = XLAL_ENOMEM;
4296  fmt = "could not allocate interpolation acceleration objects";
4297  goto cleanup;
4298  }
4299 
4300  gsl_interp_init(ampInterp, logfreqs->data, deltaAmps->data, N);
4301  gsl_interp_init(phaseInterp, logfreqs->data, deltaPhases->data, N);
4302 
4303  REAL8 lowf = exp(logfreqs->data[0]);
4304  REAL8 highf = exp(logfreqs->data[N-1]);
4305  for (i = 0; i < calFactor->data->length; i++) {
4306  REAL8 dA = 0.0, dPhi = 0.0;
4307  REAL8 f = calFactor->deltaF*i;
4308 
4309  if (f < lowf || f > highf) {
4310  dA = 0.0;
4311  dPhi = 0.0;
4312  } else {
4313  dA = gsl_interp_eval(ampInterp, logfreqs->data, deltaAmps->data, log(f), ampAcc);
4314  dPhi = gsl_interp_eval(phaseInterp, logfreqs->data, deltaPhases->data, log(f), phaseAcc);
4315  }
4316 
4317  calFactor->data->data[i] = (1.0 + dA)*(2.0 + I*dPhi)/(2.0 - I*dPhi);
4318  }
4319 
4320  cleanup:
4321  if (ampInterp != NULL) gsl_interp_free(ampInterp);
4322  if (phaseInterp != NULL) gsl_interp_free(phaseInterp);
4323  if (ampAcc != NULL) gsl_interp_accel_free(ampAcc);
4324  if (phaseAcc != NULL) gsl_interp_accel_free(phaseAcc);
4325 
4326  if (status == XLAL_SUCCESS) {
4327  return status;
4328  } else {
4329  XLAL_ERROR(status, "%s", fmt);
4330  }
4331 }
4332 
4334  REAL8Vector *deltaAmps,
4335  REAL8Vector *deltaPhases,
4336  REAL8Sequence *freqNodesLin,
4337  COMPLEX16Sequence **calFactorROQLin,
4338  REAL8Sequence *freqNodesQuad,
4339  COMPLEX16Sequence **calFactorROQQuad) {
4340 
4341  gsl_interp_accel *ampAcc = NULL, *phaseAcc = NULL;
4342  gsl_interp *ampInterp = NULL, *phaseInterp = NULL;
4343 
4344  int status = XLAL_SUCCESS;
4345  const char *fmt = "";
4346 
4347  size_t N = 0;
4348 
4349  /* should I check that calFactorROQ = NULL as well? */
4350 
4351  if (logfreqs == NULL || deltaAmps == NULL || deltaPhases == NULL || freqNodesLin == NULL || freqNodesQuad == NULL) {
4352  status = XLAL_EINVAL;
4353  fmt = "bad input";
4354  goto cleanup;
4355  }
4356 
4357  if (logfreqs->length != deltaAmps->length || deltaAmps->length != deltaPhases->length || freqNodesLin->length != (*calFactorROQLin)->length || freqNodesQuad->length != (*calFactorROQQuad)->length) {
4358  status = XLAL_EINVAL;
4359  fmt = "input lengths differ";
4360  goto cleanup;
4361  }
4362 
4363 
4364  N = logfreqs->length;
4365 
4366  ampInterp = gsl_interp_alloc(gsl_interp_cspline, N);
4367  phaseInterp = gsl_interp_alloc(gsl_interp_cspline, N);
4368 
4369  if (ampInterp == NULL || phaseInterp == NULL) {
4370  status = XLAL_ENOMEM;
4371  fmt = "could not allocate GSL interpolation objects";
4372  goto cleanup;
4373  }
4374 
4375  ampAcc = gsl_interp_accel_alloc();
4376  phaseAcc = gsl_interp_accel_alloc();
4377 
4378  if (ampAcc == NULL || phaseAcc == NULL) {
4379  status = XLAL_ENOMEM;
4380  fmt = "could not allocate interpolation acceleration objects";
4381  goto cleanup;
4382  }
4383 
4384  gsl_interp_init(ampInterp, logfreqs->data, deltaAmps->data, N);
4385  gsl_interp_init(phaseInterp, logfreqs->data, deltaPhases->data, N);
4386 
4387  REAL8 lowf = exp(logfreqs->data[0]);
4388  REAL8 highf = exp(logfreqs->data[N-1]);
4389  REAL8 dA = 0.0, dPhi = 0.0;
4390 
4391  for (unsigned int i = 0; i < freqNodesLin->length; i++) {
4392  REAL8 f = freqNodesLin->data[i];
4393  if (f < lowf || f > highf) {
4394  dA = 0.0;
4395  dPhi = 0.0;
4396  } else {
4397  dA = gsl_interp_eval(ampInterp, logfreqs->data, deltaAmps->data, log(f), ampAcc);
4398  dPhi = gsl_interp_eval(phaseInterp, logfreqs->data, deltaPhases->data, log(f), phaseAcc);
4399  }
4400 
4401  (*calFactorROQLin)->data[i] = (1.0 + dA)*(2.0 + I*dPhi)/(2.0 - I*dPhi);
4402  }
4403 
4404  for (unsigned int j = 0; j < freqNodesQuad->length; j++) {
4405  REAL8 f = freqNodesQuad->data[j];
4406  if (f < lowf || f > highf) {
4407  dA = 0.0;
4408  dPhi = 0.0;
4409  } else {
4410  dA = gsl_interp_eval(ampInterp, logfreqs->data, deltaAmps->data, log(f), ampAcc);
4411  dPhi = gsl_interp_eval(phaseInterp, logfreqs->data, deltaPhases->data, log(f), phaseAcc);
4412  }
4413 
4414  (*calFactorROQQuad)->data[j] = (1.0 + dA)*(2.0 + I*dPhi)/(2.0 - I*dPhi);
4415 
4416  }
4417 
4418  cleanup:
4419  if (ampInterp != NULL) gsl_interp_free(ampInterp);
4420  if (phaseInterp != NULL) gsl_interp_free(phaseInterp);
4421  if (ampAcc != NULL) gsl_interp_accel_free(ampAcc);
4422  if (phaseAcc != NULL) gsl_interp_accel_free(phaseAcc);
4423 
4424  if (status == XLAL_SUCCESS) {
4425  return status;
4426  } else {
4427  XLAL_ERROR(status, "%s", fmt);
4428  }
4429 }
4430 
4432  INT4 i, nifo;
4433  char **ifo_names = NULL;
4434 
4435  UINT4 ncal = *(UINT4 *)LALInferenceGetVariable(thread->currentParams, "spcal_npts");
4436 
4437  nifo = LALInferenceGetINT4Variable(thread->proposalArgs, "nDet");
4438  ifo_names = *(char ***)LALInferenceGetVariable(thread->proposalArgs, "detector_names");
4439 
4440  for (i=0; i<nifo; i++) {
4441  char parname[VARNAME_MAX];
4442  size_t j;
4443 
4444  for (j = 0; j < ncal; j++) {
4445  snprintf(parname, VARNAME_MAX, "%sspcalamp%02zd", ifo_names[i], j);
4446  fprintf(output, "%s\t", parname);
4447  }
4448 
4449  for (j = 0; j < ncal; j++) {
4450  snprintf(parname, VARNAME_MAX, "%sspcalphase%02zd", ifo_names[i], j);
4451  fprintf(output, "%s\t", parname);
4452  }
4453  }
4454 }
4455 
4457  INT4 i, nifo;
4458  char **ifo_names = NULL;
4459 
4460  nifo = LALInferenceGetINT4Variable(thread->proposalArgs, "nDet");
4461  ifo_names = *(char ***)LALInferenceGetVariable(thread->proposalArgs, "detector_names");
4462 
4463  for (i=0; i<nifo; i++) {
4464  size_t j;
4465 
4466  char ampVarName[VARNAME_MAX];
4467  char phaseVarName[VARNAME_MAX];
4468 
4469  REAL8Vector *amp = NULL;
4470  REAL8Vector *phase = NULL;
4471 
4472  snprintf(ampVarName, VARNAME_MAX, "%s_spcal_amp", ifo_names[i]);
4473  snprintf(phaseVarName, VARNAME_MAX, "%s_spcal_phase", ifo_names[i]);
4474 
4475  amp = *(REAL8Vector **)LALInferenceGetVariable(thread->currentParams, ampVarName);
4476  phase = *(REAL8Vector **)LALInferenceGetVariable(thread->currentParams, phaseVarName);
4477 
4478  for (j = 0; j < amp->length; j++) {
4479  fprintf(output, "%g\t", amp->data[j]);
4480  }
4481 
4482  for (j = 0; j < phase->length; j++) {
4483  fprintf(output, "%g\t", phase->data[j]);
4484  }
4485  }
4486 }
4487 
4489 
4490  /**
4491  * Implelentation of the parametrization from Chatziioannou, Haster, Zimmerman (2018)
4492  * https://doi.org/10.1103/PhysRevD.97.104036
4493  */
4494 
4495  REAL8 lambdaS = *(REAL8*) LALInferenceGetVariable(vars, "lambdaS");
4496  REAL8 lambdaSm1o5 = pow(lambdaS,-1.0/5.0);
4497  REAL8 lambdaSm2o5 = lambdaSm1o5*lambdaSm1o5;
4498  REAL8 lambdaSm3o5 = lambdaSm2o5*lambdaSm1o5;
4499  REAL8 lambdaSsqrt = sqrt(lambdaS);
4500 
4501  REAL8 q=1.0;
4502 
4503  if (LALInferenceCheckVariable(vars,"q")) {
4504  q = *(REAL8 *)LALInferenceGetVariable(vars,"q");
4505  }
4506  else{
4507  REAL8 m1 = *(REAL8 *)LALInferenceGetVariable(vars,"mass1");
4508  REAL8 m2 = *(REAL8 *)LALInferenceGetVariable(vars,"mass2");
4509  q = m2/m1;
4510  }
4511  REAL8 q2 = q*q;
4512 
4513  /* Eqn 2 , incorporating the dependance on mass ratio */
4514 
4515  REAL8 BL_n = 0.743;
4516  REAL8 q_for_Fnofq = pow(q,10.0/(3.0-BL_n));
4517  REAL8 Fnofq = (1.0-q_for_Fnofq)/(1.0+q_for_Fnofq);
4518 
4519  /* bXX and cXX coefficients are given in Table I */
4520 
4521  REAL8 b11 = -27.7408;
4522  REAL8 b12 = 8.42358;
4523  REAL8 b21 = 122.686;
4524  REAL8 b22 = -19.7551;
4525  REAL8 b31 = -175.496;
4526  REAL8 b32 = 133.708;
4527 
4528  REAL8 c11 = -25.5593;
4529  REAL8 c12 = 5.58527;
4530  REAL8 c21 = 92.0337;
4531  REAL8 c22 = 26.8586;
4532  REAL8 c31 = -70.247;
4533  REAL8 c32 = -56.3076i;
4534 
4535  /* Eqn 1, giving the lambdaA_fitOnly, not yet accounting for the uncertainty in the fit */
4536 
4537  REAL8 numerator = 1.0 + (b11*q*lambdaSm1o5) + (b12*q2*lambdaSm1o5) + (b21*q*lambdaSm2o5) + (b22*q2*lambdaSm2o5) + (b31*q*lambdaSm3o5) + (b32*q2*lambdaSm3o5);
4538 
4539  REAL8 denominator = 1.0 + (c11*q*lambdaSm1o5) + (c12*q2*lambdaSm1o5) + (c21*q*lambdaSm2o5) + (c22*q2*lambdaSm2o5) + (c31*q*lambdaSm3o5) + (c32*q2*lambdaSm3o5);
4540 
4541  REAL8 lambdaA_fitOnly = Fnofq*lambdaS*numerator/denominator;
4542 
4543  /* Eqn 6, correction on fit for lambdaA caused by uncertainty in the mean of the lambdaS residual fit,
4544  * using coefficients mu_1, mu_2 and mu_3 from Table II */
4545 
4546  REAL8 lambdaA_lambdaS_meanCorr = (137.1252739/(lambdaS*lambdaS)) - (32.8026613/lambdaS) + 0.5168637;
4547 
4548  /* Eqn 8, correction on fit for lambdaA caused by uncertainty in the standard deviation of lambdaS residual fit,
4549  * using coefficients sigma_1, sigma_2 sigma_3 and sigma_4 from Table II */
4550 
4551  REAL8 lambdaA_lambdaS_stdCorr = (-0.0000739*lambdaS*lambdaSsqrt) + (0.0103778*lambdaS) + (0.4581717*lambdaSsqrt) - 0.8341913;
4552 
4553  /* Eqn 7, correction on fit for lambdaA caused by uncertainty in the mean of the q residual fit,
4554  * using coefficients mu_4 and mu_5 from Table II */
4555 
4556  REAL8 lambdaA_q_meanCorr = (-11.2765281*q2) + (14.9499544*q) - 4.6638851;
4557 
4558  /* Eqn 9, correction on fit for lambdaA caused by uncertainty in the standard deviation of the q residual fit,
4559  * using coefficients sigma_5, sigma_6 and sigma_7 from Table II */
4560 
4561  REAL8 lambdaA_q_stdCorr = (-201.4323962*q2) + (273.9268276*q) - 71.2342246;
4562 
4563  /* Eqn 4, averaging the corrections from the mean of the residual fits */
4564 
4565  REAL8 lambdaA_meanCorr = (lambdaA_lambdaS_meanCorr + lambdaA_q_meanCorr)/2.0;
4566 
4567  /* Eqn 5, averaging the corrections from the standard deviations of the residual fits */
4568 
4569  REAL8 lambdaA_stdCorr = sqrt((lambdaA_lambdaS_stdCorr*lambdaA_lambdaS_stdCorr) + (lambdaA_q_stdCorr*lambdaA_q_stdCorr));
4570 
4571  /* Draw a correction on the fit from a Gaussian distribution wiht width lambdaA_stdCorr
4572  * this is done by sampling a inverse cdf through a U{0,1} variable called BLuni */
4573 
4574  REAL8 BLuni = *(REAL8*) LALInferenceGetVariable(vars, "BLuni");
4575 
4576  REAL8 lambdaA_scatter = gsl_cdf_gaussian_Pinv(BLuni, lambdaA_stdCorr);
4577 
4578  /* Add the correction of the residual mean and the Gaussian scatter to the lambdaA_fitOnly value */
4579 
4580  REAL8 lambdaA = lambdaA_fitOnly + (lambdaA_meanCorr + lambdaA_scatter);
4581 
4582  *lambda1 = lambdaS - lambdaA;
4583  *lambda2 = lambdaS + lambdaA;
4584  return;
4585 }
static COMPLEX16Vector * COMPLEX16Vector_fread(FILE *f)
static REAL8Vector * REAL8Vector_fread(FILE *f)
static void INT4Vector_fwrite(FILE *f, INT4Vector *vec)
static int LALInferenceElemCmp(const void *elem1, const void *elem2)
Definition: LALInference.c:79
static void computeMean(LALInferenceKDTree *cell)
static void updateEigenSystem(LALInferenceKDTree *cell)
static void del_elem(void *elem)
Definition: LALInference.c:65
cellType
@ TOP
@ LEFT
@ RIGHT
static int cellAllEqualPoints(LALInferenceKDTree *cell)
ProcessParamsTable * LALInferenceParseCommandLine(int argc, char *argv[])
static INT4Vector * INT4Vector_fread(FILE *f)
static void computeCovariance(LALInferenceKDTree *cell)
static int inEigenBox(LALInferenceKDTree *cell, REAL8 *pt)
static void deleteCell(LALInferenceKDTree *cell)
static LALInferenceVariableItem * LALInferenceGetItemSlow(const LALInferenceVariables *vars, const char *name)
Definition: LALInference.c:193
static UINT4Vector * UINT4Vector_fread(FILE *f)
static INT4 checkREAL8TimeSeries(REAL8TimeSeries *series)
static INT4 checkREAL8Value(REAL8 val)
static LALInferenceKDTree * newCell(size_t ndim, REAL8 *lowerLeft, REAL8 *upperRight, size_t level, cellType type)
static void toEigenFrame(size_t dim, REAL8 **eigenvs, REAL8 *x, REAL8 *xe)
static void * new_elem(const char *name, LALInferenceVariableItem *itemPtr)
Definition: LALInference.c:59
static LALInferenceKDTree * doFindCell(LALInferenceKDTree *cell, REAL8 *pt, size_t dim, size_t Npts, size_t level)
#define STR_MAX
Definition: LALInference.c:51
static void fromEigenFrame(size_t dim, REAL8 **eigenvs, REAL8 *xe, REAL8 *x)
static void REAL8Vector_fwrite(FILE *f, REAL8Vector *vec)
static void UINT4Vector_fwrite(FILE *f, UINT4Vector *vec)
static void computeEigenVectorsCleanup(gsl_matrix *A, gsl_matrix *evects, gsl_vector *evals, gsl_eigen_symmv_workspace *ws)
static INT4 checkCOMPLEX16FrequencySeries(COMPLEX16FrequencySeries *series)
static void computeEigenVectors(LALInferenceKDTree *cell)
static int inBounds(REAL8 *pt, REAL8 *low, REAL8 *high, size_t n)
static INT4 checkREAL8FrequencySeries(REAL8FrequencySeries *series)
static int equalPoints(REAL8 *a, REAL8 *b, size_t n)
static INT4 matrix_equal(gsl_matrix *a, gsl_matrix *b)
Definition: LALInference.c:162
#define COL_MAX
Definition: LALInference.c:50
static void addPtToCellPts(LALInferenceKDTree *cell, REAL8 *pt)
static char * colNameToParamName(const char *colName)
static void computeEigenMinMax(LALInferenceKDTree *cell)
static UINT8 LALInferenceElemHash(const void *elem)
Definition: LALInference.c:71
static void COMPLEX16Vector_fwrite(FILE *f, COMPLEX16Vector *vec)
static int insertIntoCell(LALInferenceKDTree *cell, REAL8 *pt, size_t level)
static REAL8 mean(REAL8 *array, int N)
static REAL8 norm(const REAL8 x[3])
#define max(a, b)
ProcessParamsTable * ppt
int j
ProcessParamsTable * ptr
int k
void LALCheckMemoryLeaks(void)
#define LALFree(p)
#define gamma
struct tagLALSimNeutronStarFamily LALSimNeutronStarFamily
struct tagLALSimNeutronStarEOS LALSimNeutronStarEOS
#define LIGOMETA_TYPE_MAX
#define LIGOMETA_PROGRAM_MAX
#define LIGOMETA_VALUE_MAX
#define LIGOMETA_PARAM_MAX
#define fscanf
#define fprintf
const char *const name
int l
double e
const double a2
sigmaKerr data[0]
COMPLEX16FrequencySeries * XLALCreateCOMPLEX16FrequencySeries(const CHAR *name, const LIGOTimeGPS *epoch, REAL8 f0, REAL8 deltaF, const LALUnit *sampleUnits, size_t length)
#define LAL_MSUN_SI
#define LAL_PI
#define LAL_MRSUN_SI
uint64_t UINT8
double complex COMPLEX16
double REAL8
int64_t INT8
char CHAR
uint32_t UINT4
float complex COMPLEX8
int32_t INT4
float REAL4
UINT8 XLALCityHash64(const char *buf, size_t len)
int XLALHashTblFind(const LALHashTbl *ht, const void *x, const void **y)
LALHashTbl * XLALHashTblCreate(LALHashTblDtorFcn dtor, LALHashTblHashFcn hash, LALHashTblCmpFcn cmp)
int XLALHashTblAdd(LALHashTbl *ht, void *x)
int XLALHashTblRemove(LALHashTbl *ht, const void *x)
void XLALHashTblDestroy(LALHashTbl *ht)
void LALInferenceMcQ2Masses(double mc, double q, double *m1, double *m2)
Convert from Mc, q space to m1, m2 space (q = m2/m1, with m1 > m2).
REAL8 LALInferenceAngularDistance(REAL8 a1, REAL8 a2)
Calculate shortest angular distance between a1 and a2 (modulo 2PI)
INT4 LALInferenceBufferToArray(LALInferenceThreadState *thread, REAL8 **DEarray)
LALInferenceThreadState * LALInferenceInitThreads(INT4 nthreads)
Definition: LALInference.c:138
int LALInferenceKDAddPoint(LALInferenceKDTree *tree, REAL8 *pt)
Adds a point to the kD-tree, returns 0 on successful exit.
INT4 LALInferenceThinnedBufferToArray(LALInferenceThreadState *thread, REAL8 **DEarray, INT4 step)
LALInferenceVariable buffer to array and vica versa.
void LALInferencePrintSampleNonFixed(FILE *fp, LALInferenceVariables *sample)
Output only non-fixed parameters.
Definition: LALInference.c:948
void LALInferenceReadAsciiHeader(FILE *input, char params[][VARNAME_MAX], INT4 *nCols)
Read column names from an ASCII file.
void LALInferenceAddINT8Variable(LALInferenceVariables *vars, const char *name, INT8 value, LALInferenceParamVaryType vary)
int LALInferenceReadVariablesArrayBinary(FILE *file, LALInferenceVariables **vars, UINT4 N)
Read N LALInferenceVariables from the binary FILE *file, previously written with LALInferenceWriteVar...
INT4 LALInferenceGetVariableDimensionNonFixedChooseVectors(LALInferenceVariables *vars, INT4 count_vectors)
Get number of dimensions in vars which are not fixed to a certain value, with a flag for skipping cou...
Definition: LALInference.c:260
REAL8 * LALInferenceParseDelimitedAscii(FILE *input, INT4 nCols, INT4 *wantedCols, INT4 *nLines)
Utility for readling in delimited ASCII files.
void LALInferenceSetstringVariable(LALInferenceVariables *vars, const char *name, const CHAR *value)
void LALInferencedQuadMonSdQuadMonA(REAL8 dQuadMonS, REAL8 dQuadMonA, REAL8 *dQuadMon1, REAL8 *dQuadMon2)
Convert from dQuadMonS, dQuadMonA to dQuadMon1, dQuadMon2.
LALInferenceMCMCRunPhase * LALInferenceGetMCMCrunphase_ptrVariable(LALInferenceVariables *vars, const char *name)
LALInferenceVariableType LALInferenceGetVariableType(const LALInferenceVariables *vars, const char *name)
Get the LALInferenceVariableType of the parameter named name in vars.
Definition: LALInference.c:321
void LALInferenceDiscardPTMCMCHeader(FILE *filestream)
Discard the standard header of a PTMCMC chain file.
void LALInferenceQ2Eta(double q, double *eta)
Convert from q to eta (q = m2/m1, with m1 > m2).
#define VARNAME_MAX
Definition: LALInference.h:50
int LALInferenceFprintParameterNonFixedHeaders(FILE *out, LALInferenceVariables *params)
Print the parameters which do not vary to a file as a tab-separated ASCII line.
UINT4 LALInferenceGetUINT4Variable(LALInferenceVariables *vars, const char *name)
void LALInferencePrintSample(FILE *fp, LALInferenceVariables *sample)
Output the sample to file *fp, in ASCII format.
Definition: LALInference.c:923
INT4 LALInferenceGetVariableDimensionNonFixed(LALInferenceVariables *vars)
Get number of dimensions in vars which are not fixed to a certain value.
Definition: LALInference.c:255
char ** LALInferenceGetHeaderLine(FILE *inp)
Returns an array of header strings (terminated by NULL) from a common-format output file.
gsl_matrix * LALInferenceGetgslMatrixVariable(LALInferenceVariables *vars, const char *name)
int LALInferenceFprintParameterHeaders(FILE *out, LALInferenceVariables *params)
Print the parameter names to a file as a tab-separated ASCII line.
double AdiabaticIndex(double gamma[], double x, int size)
Specral decomposition of eos's adiabatic index.
REAL8Vector * LALInferenceGetREAL8VectorVariable(LALInferenceVariables *vars, const char *name)
int LALInferenceSplineCalibrationFactorROQ(REAL8Vector *logfreqs, REAL8Vector *deltaAmps, REAL8Vector *deltaPhases, REAL8Sequence *freqNodesLin, COMPLEX16Sequence **calFactorROQLin, REAL8Sequence *freqNodesQuad, COMPLEX16Sequence **calFactorROQQuad)
Modified version of LALInferenceSplineCalibrationFactor to compute the calibration factors for the sp...
void LALInferenceAddREAL8VectorVariable(LALInferenceVariables *vars, const char *name, REAL8Vector *value, LALInferenceParamVaryType vary)
void LALInferencePrintSplineCalibration(FILE *output, LALInferenceThreadState *thread)
Output spline calibration parameters.
void LALInferenceAddVariable(LALInferenceVariables *vars, const char *name, const void *value, LALInferenceVariableType type, LALInferenceParamVaryType vary)
Add a variable named name to vars with initial value referenced by value.
Definition: LALInference.c:395
REAL4 LALInferenceGetREAL4Variable(LALInferenceVariables *vars, const char *name)
double LALInferenceKDLogCellVolume(LALInferenceKDTree *cell)
Returns the log of the volume of the given cell, which is part of the given tree.
int LALInferenceWriteVariablesArrayBinary(FILE *file, LALInferenceVariables **vars, UINT4 N)
Write an array N of LALInferenceVariables to the given FILE * using LALInferenceWriteVariablesBinary(...
void LALInferenceKDVariablesToREAL8(LALInferenceVariables *params, REAL8 *pt, LALInferenceVariables *templt)
Fills in the given REAL8 array with the parameter values from params; the ordering of the variables i...
LALInferenceThreadState * LALInferenceInitThread(LALInferenceThreadState *thread)
Structure to contain data-related Reduced Order Quadrature quantities.
Definition: LALInference.c:105
void LALInferenceAddINT4VectorVariable(LALInferenceVariables *vars, const char *name, INT4Vector *value, LALInferenceParamVaryType vary)
int LALInferenceWriteRunStateBinary(FILE *file, LALInferenceRunState *runState)
Write the LALInferenceVariables contents of runState to a file in binary format.
void LALInferenceLogSampleToFile(LALInferenceVariables *algorithmParams, LALInferenceVariables *vars)
Append the sample to a file.
UINT4 LALInferencePrintNVariableItem(char *out, UINT4 strsize, const LALInferenceVariableItem *const ptr)
Prints a variable item to a string (must be pre-allocated!) Returns the number of bytes necessary to ...
Definition: LALInference.c:687
void LALInferenceLogp1GammasMasses2Lambdas(REAL8 logp1, REAL8 gamma1, REAL8 gamma2, REAL8 gamma3, REAL8 mass1, REAL8 mass2, REAL8 *lambda1, REAL8 *lambda2)
Calculate lambda1,2(m1,2|eos(logp1,gamma1,gamma2,gamma3))
REAL8 LALInferenceGetREAL8Variable(LALInferenceVariables *vars, const char *name)
REAL8 LALInferenceKDLogProposalRatio(LALInferenceKDTree *tree, REAL8 *current, REAL8 *proposed, size_t Npts)
Returns the log of the jump proposal probability ratio for the LALInferenceKDDrawEigenFrame() proposa...
REAL8 ** LALInferenceSelectColsFromArray(REAL8 **inarray, INT4 nRows, INT4 nCols, INT4 nSelCols, INT4 *selCols)
Utility for selecting columns from an array, in the specified order.
COMPLEX8 LALInferenceGetCOMPLEX8Variable(LALInferenceVariables *vars, const char *name)
void LALInferenceSetREAL8Variable(LALInferenceVariables *vars, const char *name, REAL8 value)
void LALInferenceExecuteFT(LALInferenceModel *model)
Execute FFT for data in IFOdata.
size_t LALInferenceTypeSize[]
Definition: LALInference.c:86
double LALInferenceKDLogCellEigenVolume(LALInferenceKDTree *cell)
Returns the log of the volume of the box aligned with the principal axes of the points in the given c...
int LALInferenceCompareVariables(LALInferenceVariables *var1, LALInferenceVariables *var2)
Check for equality in two variables.
int LALInferenceEOSPhysicalCheck(LALInferenceVariables *params, ProcessParamsTable *commandLine)
Check for causality violation and mass conflict given masses and eos.
char * LALInferenceGetVariableName(LALInferenceVariables *vars, int idx)
Get the name of the idx-th variable Indexing starts at 1.
Definition: LALInference.c:339
void LALInferenceRemoveVariable(LALInferenceVariables *vars, const char *name)
Remove name from vars Frees the memory for the name structure and its contents.
Definition: LALInference.c:450
LALInferenceKDTree * LALInferenceKDFindCell(LALInferenceKDTree *tree, REAL8 *pt, size_t Npts)
Returns the first cell that contains the given point that also contains fewer than Npts points,...
void LALInferenceAddstringVariable(LALInferenceVariables *vars, const char *name, const CHAR *value, LALInferenceParamVaryType vary)
void LALInferenceLambdaTsEta2Lambdas(REAL8 lambdaT, REAL8 dLambdaT, REAL8 eta, REAL8 *lambda1, REAL8 *lambda2)
Convert from lambdaT, dLambdaT, and eta to lambda1 and lambda2.
INT4 LALInferenceGetVariableTypeByIndex(LALInferenceVariables *vars, int idx)
Get the LALInferenceVariableType of the idx -th item in the vars Indexing starts at 1.
Definition: LALInference.c:326
int LALInferenceSDGammaCheck(double gamma[], int size)
Determine if the Adiabatic index is within 'prior' range.
LALInferenceParamVaryType
An enumerated type for denoting the topology of a parameter.
Definition: LALInference.h:127
void LALInferenceReadSampleNonFixed(FILE *fp, LALInferenceVariables *p)
Read in the non-fixed parameters from the given file (position in the file must be arranged properly ...
Definition: LALInference.c:974
void LALInferenceSetCOMPLEX16Variable(LALInferenceVariables *vars, const char *name, COMPLEX16 value)
void LALInferenceSetUINT4VectorVariable(LALInferenceVariables *vars, const char *name, UINT4Vector *value)
void LALInferenceAddCOMPLEX16VectorVariable(LALInferenceVariables *vars, const char *name, COMPLEX16Vector *value, LALInferenceParamVaryType vary)
void LALInferenceDumpWaveforms(LALInferenceModel *model, const char *basefilename)
Dump all waveforms from the ifodata structure.
void LALInferenceSetCOMPLEX16VectorVariable(LALInferenceVariables *vars, const char *name, COMPLEX16Vector *value)
void LALInferenceCopyVariables(LALInferenceVariables *origin, LALInferenceVariables *target)
Deep copy the variables from one to another LALInferenceVariables structure.
Definition: LALInference.c:558
void LALInferenceBurninStream(FILE *filestream, INT4 burnin)
Burn-in a generic ASCII stream.
void LALInferenceAddREAL8Variable(LALInferenceVariables *vars, const char *name, REAL8 value, LALInferenceParamVaryType vary)
INT4 LALInferenceGetINT4Variable(LALInferenceVariables *vars, const char *name)
ProcessParamsTable * LALInferenceParseStringVector(LALStringVector *arglist)
Return a ProcessParamsTrable from a string vector.
void LALInferenceAddUINT4Variable(LALInferenceVariables *vars, const char *name, UINT4 value, LALInferenceParamVaryType vary)
REAL8 LALInferenceAngularVariance(LALInferenceVariables **list, const char *pname, int N)
Calculate the variance of a distribution on an angle (modulo 2PI)
int LALInferencePrintProposalStatsHeader(FILE *fp, LALInferenceProposalCycle *cycle)
Output proposal statistics header to file *fp.
void LALInferenceKDDrawEigenFrame(gsl_rng *rng, LALInferenceKDTree *tree, REAL8 *pt, size_t Npts)
Draws a pt uniformly from a randomly chosen cell of tree.
void LALInferencePrintProposalStats(FILE *fp, LALInferenceProposalCycle *cycle)
Output proposal statistics to file *fp.
void LALInferenceProcessParamLine(FILE *inp, char **headers, LALInferenceVariables *vars)
Reads one line from the given file and stores the values there into the variable structure,...
COMPLEX16Vector * LALInferenceGetCOMPLEX16VectorVariable(LALInferenceVariables *vars, const char *name)
void LALInferenceAddCOMPLEX16Variable(LALInferenceVariables *vars, const char *name, COMPLEX16 value, LALInferenceParamVaryType vary)
void LALInferenceAddINT4Variable(LALInferenceVariables *vars, const char *name, INT4 value, LALInferenceParamVaryType vary)
LALInferenceKDTree * LALInferenceKDEmpty(REAL8 *lowerLeft, REAL8 *upperRight, size_t ndim)
Constructs a fresh, empty kD tree.
INT4Vector * LALInferenceGetINT4VectorVariable(LALInferenceVariables *vars, const char *name)
void LALInferenceFprintSplineCalibrationHeader(FILE *output, LALInferenceThreadState *thread)
Print spline calibration parameter names as tab-separated ASCII.
LALInferenceMCMCRunPhase
Phase of MCMC run (depending on burn-in status, different actions are performed during the run,...
Definition: LALInference.h:180
ProcessParamsTable * LALInferenceParseCommandLineStringVector(LALStringVector *args)
Return a ProcessParamsTable from the command line arguments (SWIG version)
void LALInferenceCopyArrayToVariables(REAL8 *origin, LALInferenceVariables *target)
void LALInferenceKDTreeDelete(LALInferenceKDTree *tree)
Delete a kD-tree.
void LALInferenceSetParamVaryType(LALInferenceVariables *vars, const char *name, LALInferenceParamVaryType vary)
Set the LALInferenceParamVaryType of the parameter named name in vars, see the declaration of LALInfe...
Definition: LALInference.c:231
UINT4Vector * LALInferenceGetUINT4VectorVariable(LALInferenceVariables *vars, const char *name)
void LALInferenceSetUINT4Variable(LALInferenceVariables *vars, const char *name, UINT4 value)
void LALInferenceBurninPTMCMC(FILE *filestream, INT4 logl_idx, INT4 nPar)
Determine burnin cycle from delta-logl criteria.
INT4 LALInferenceGetVariableDimension(LALInferenceVariables *vars)
Get number of dimensions in variable vars.
Definition: LALInference.c:250
void LALInferenceAddMCMCrunphase_ptrVariable(LALInferenceVariables *vars, const char *name, LALInferenceMCMCRunPhase *value, LALInferenceParamVaryType vary)
void LALInferenceSetINT4Variable(LALInferenceVariables *vars, const char *name, INT4 value)
int LALInferenceCheckVariableToPrint(LALInferenceVariables *vars, const char *name)
Definition: LALInference.c:514
UINT4 LALInferenceCheckPositiveDefinite(gsl_matrix *matrix, UINT4 dim)
Check matrix is positive definite.
void LALInferenceSDGammasMasses2Lambdas(REAL8 gamma[], REAL8 mass1, REAL8 mass2, REAL8 *lambda1, REAL8 *lambda2, int size)
Convert from spectral parameters to lambda1, lambda2.
void LALInferenceParseCharacterOptionString(char *input, char **strings[], UINT4 *n)
parses a character string (passed as one of the options) and decomposes it into individual parameter ...
void LALInferenceClearVariables(LALInferenceVariables *vars)
Delete the variables in this structure.
Definition: LALInference.c:532
LALInferenceVariableItem * LALInferencePopVariableItem(LALInferenceVariables *vars, const char *name)
Pop the list node for "name".
void LALInferenceSortVariablesByName(LALInferenceVariables *vars)
Sorts the variable structure by name.
void XLALMultiStudentDeviates(REAL4Vector *vector, gsl_matrix *matrix, UINT4 dim, UINT4 n, RandomParams *randParam)
Draw a random multivariate vector from student-t distr given covariance matrix.
void LALInferenceSetINT4VectorVariable(LALInferenceVariables *vars, const char *name, INT4Vector *value)
void LALInferenceAddgslMatrixVariable(LALInferenceVariables *vars, const char *name, gsl_matrix *value, LALInferenceParamVaryType vary)
void parseLine(char *record, const char *delim, char arr[][VARNAME_MAX], INT4 *cnt)
Parse a single line of delimited ASCII.
void LALInferenceBinaryLove(LALInferenceVariables *vars, REAL8 *lambda1, REAL8 *lambda2)
Compute Tidal deformabilities following BinaryLove Universal relations.
void LALInferenceCopyVariablesToArray(LALInferenceVariables *origin, REAL8 *target)
LALInference variables to an array, and vica versa.
void LALInferenceMcEta2Masses(double mc, double eta, double *m1, double *m2)
Convert from Mc, eta space to m1, m2 space (note m1 > m2).
ProcessParamsTable * LALInferenceGetProcParamVal(ProcessParamsTable *procparams, const char *name)
Returns the element of the process params table with "name".
INT4 LALInferenceFprintParameterNonFixedHeadersWithSuffix(FILE *out, LALInferenceVariables *params, const char *suffix)
Print the parameters which do not vary to a file as a tab-separated ASCII line, adding the given suff...
int LALInferenceWriteVariablesBinary(FILE *file, LALInferenceVariables *vars)
Write a LALInferenceVariables as binary to a given FILE pointer, returns the number of items written ...
void * LALInferenceGetVariable(const LALInferenceVariables *vars, const char *name)
Return a pointer to the memory the variable vars is stored in specified by name User must cast this p...
Definition: LALInference.c:238
void XLALMultiNormalDeviates(REAL4Vector *vector, gsl_matrix *matrix, UINT4 dim, RandomParams *randParam)
Draw a random multivariate vector from Gaussian distr given covariance matrix.
int LALInferenceSplineCalibrationFactor(REAL8Vector *logfreqs, REAL8Vector *deltaAmps, REAL8Vector *deltaPhases, COMPLEX16FrequencySeries *calFactor)
Computes the factor relating the physical waveform to a measured waveform for a spline-fit calibratio...
INT4 LALInferenceSanityCheck(LALInferenceRunState *state)
Sanity check the structures in the given state.
void LALInferenceLogSampleToArray(LALInferenceVariables *algorithmParams, LALInferenceVariables *vars)
Append the sample to an array which can be later processed by the user.
void LALInferencePrintVariables(LALInferenceVariables *var)
output contents of a 'LALInferenceVariables' structure * / / * (by now only prints names and types,...
Definition: LALInference.c:798
void LALInferenceExecuteInvFT(LALInferenceModel *model)
Execute Inverse FFT for data in IFOdata.
const CHAR * LALInferenceGetstringVariable(LALInferenceVariables *vars, const char *name)
LALInferenceVariables * LALInferenceReadVariablesBinary(FILE *stream)
Read from the given FILE * a LALInferenceVariables, which was previously written with LALInferenceWri...
void LALInferenceSetINT8Variable(LALInferenceVariables *vars, const char *name, INT8 value)
void LALInferenceSetREAL4Variable(LALInferenceVariables *vars, const char *name, REAL4 value)
int LALInferenceCheckVariable(LALInferenceVariables *vars, const char *name)
Checks for name being present in vars returns 1(==true) or 0.
Definition: LALInference.c:525
void LALInferenceSetgslMatrixVariable(LALInferenceVariables *vars, const char *name, gsl_matrix *value)
void LALInferenceCopyUnsetREAL8Variables(LALInferenceVariables *origin, LALInferenceVariables *target, ProcessParamsTable *commandLine)
Definition: LALInference.c:659
LALInferenceVariableItem * LALInferenceGetItemNr(LALInferenceVariables *vars, int idx)
Return the list node for the idx-th item - do not rely on this Indexing starts at 1.
Definition: LALInference.c:207
void LALInferenceSetMCMCrunphase_ptrVariable(LALInferenceVariables *vars, const char *name, LALInferenceMCMCRunPhase *value)
void LALInferenceAddUINT4VectorVariable(LALInferenceVariables *vars, const char *name, UINT4Vector *value, LALInferenceParamVaryType vary)
void LALInferenceTranslateExternalToInternalParamName(char *outName, const char *inName)
Converts between externally used parameter names and those internal.
INT8 LALInferenceGetINT8Variable(LALInferenceVariables *vars, const char *name)
void LALInferenceSetCOMPLEX8Variable(LALInferenceVariables *vars, const char *name, COMPLEX8 value)
COMPLEX16 LALInferenceGetCOMPLEX16Variable(LALInferenceVariables *vars, const char *name)
LALInferenceVariableType
An enumerated type for denoting the type of a variable.
Definition: LALInference.h:104
LALInferenceParamVaryType LALInferenceGetVariableVaryType(LALInferenceVariables *vars, const char *name)
Get the LALInferenceParamVaryType of the parameter named name in vars see the declaration of LALInfer...
Definition: LALInference.c:226
char * LALInferencePrintCommandLine(ProcessParamsTable *procparams)
Output the command line based on the ProcessParamsTable procparams.
LALInferenceVariableItem * LALInferenceGetItem(const LALInferenceVariables *vars, const char *name)
Return the list node for "name" - do not rely on this.
Definition: LALInference.c:175
void LALInferenceAddREAL4Variable(LALInferenceVariables *vars, const char *name, REAL4 value, LALInferenceParamVaryType vary)
void LALInferenceSetVariable(LALInferenceVariables *vars, const char *name, const void *value)
Set a variable named name in vars with a value.
Definition: LALInference.c:352
void LALInferenceSetREAL8VectorVariable(LALInferenceVariables *vars, const char *name, REAL8Vector *value)
int LALInferenceCheckVariableNonFixed(LALInferenceVariables *vars, const char *name)
Checks for name being present in vars and having type LINEAR or CIRCULAR.
Definition: LALInference.c:503
int LALInferenceReadRunStateBinary(FILE *file, LALInferenceRunState *runState)
Reads the file and populates LALInferenceVariables in the runState that were saved with LALInferenceR...
const char * LALInferenceTranslateInternalToExternalParamName(const char *inName)
Converts between internally used parameter names and those external (e.g.
void LALInferenceKDREAL8ToVariables(LALInferenceVariables *params, REAL8 *pt, LALInferenceVariables *templt)
Fills in the non-fixed variables in params from the given REAL8 array.
void LALInferenceAddCOMPLEX8Variable(LALInferenceVariables *vars, const char *name, COMPLEX8 value, LALInferenceParamVaryType vary)
@ LALINFERENCE_PARAM_OUTPUT
A parameter that never changes, functions should respect this.
Definition: LALInference.h:131
@ LALINFERENCE_PARAM_FIXED
A parameter that is cyclic, such as an angle between 0 and 2pi.
Definition: LALInference.h:130
@ LALINFERENCE_PARAM_CIRCULAR
A parameter that simply has a maximum and a minimum.
Definition: LALInference.h:129
@ LALINFERENCE_PARAM_LINEAR
Definition: LALInference.h:128
@ LALINFERENCE_string_t
Definition: LALInference.h:117
@ LALINFERENCE_COMPLEX16_t
Definition: LALInference.h:111
@ LALINFERENCE_MCMCrunphase_ptr_t
Definition: LALInference.h:118
@ LALINFERENCE_REAL8_t
Definition: LALInference.h:109
@ LALINFERENCE_INT4Vector_t
Definition: LALInference.h:114
@ LALINFERENCE_REAL4_t
Definition: LALInference.h:108
@ LALINFERENCE_INT4_t
Definition: LALInference.h:105
@ LALINFERENCE_REAL8Vector_t
Definition: LALInference.h:113
@ LALINFERENCE_void_ptr_t
Definition: LALInference.h:119
@ LALINFERENCE_UINT4_t
Definition: LALInference.h:107
@ LALINFERENCE_UINT4Vector_t
Definition: LALInference.h:115
@ LALINFERENCE_gslMatrix_t
Definition: LALInference.h:112
@ LALINFERENCE_INT8_t
Definition: LALInference.h:106
@ LALINFERENCE_COMPLEX8_t
Definition: LALInference.h:110
@ LALINFERENCE_COMPLEX16Vector_t
Definition: LALInference.h:116
void * XLALCalloc(size_t m, size_t n)
void * XLALMalloc(size_t n)
void * XLALRealloc(void *p, size_t n)
void XLALFree(void *p)
LALSimNeutronStarEOS * XLALSimNeutronStarEOSSpectralDecomposition(double gamma[], int size)
LALSimNeutronStarEOS * XLALSimNeutronStarEOS4ParameterPiecewisePolytrope(double logp1_si, double gamma1, double gamma2, double gamma3)
double XLALSimNeutronStarEOSPseudoEnthalpyOfPressure(double p, LALSimNeutronStarEOS *eos)
double XLALSimNeutronStarEOSSpeedOfSoundGeometerized(double h, LALSimNeutronStarEOS *eos)
double XLALSimNeutronStarEOSMaxPressure(LALSimNeutronStarEOS *eos)
void XLALDestroySimNeutronStarEOS(LALSimNeutronStarEOS *eos)
double XLALSimNeutronStarLoveNumberK2(double m, LALSimNeutronStarFamily *fam)
void XLALDestroySimNeutronStarFamily(LALSimNeutronStarFamily *fam)
double XLALSimNeutronStarRadius(double m, LALSimNeutronStarFamily *fam)
double XLALSimNeutronStarFamMinimumMass(LALSimNeutronStarFamily *fam)
double XLALSimNeutronStarCentralPressure(double m, LALSimNeutronStarFamily *fam)
LALSimNeutronStarFamily * XLALCreateSimNeutronStarFamily(LALSimNeutronStarEOS *eos)
double XLALSimNeutronStarMaximumMass(LALSimNeutronStarFamily *fam)
int XLALSimNeutronStarTOVODEIntegrate(double *radius, double *mass, double *love_number_k2, double central_pressure_si, LALSimNeutronStarEOS *eos)
#define LAL_REAL8_FORMAT
#define LAL_INT8_FORMAT
#define LAL_INT4_FORMAT
#define LAL_REAL4_FORMAT
#define LAL_UINT4_FORMAT
size_t XLALStringCopy(char *dst, const char *src, size_t size)
char char * XLALStringDuplicate(const char *s)
static const INT4 r
static const INT4 m
static const INT4 q
int XLALNormalDeviates(REAL4Vector *deviates, RandomParams *params)
static const INT4 a
LALStringVector * XLALAppendString2Vector(LALStringVector *vect, const CHAR *string)
void XLALDestroyStringVector(LALStringVector *vect)
LALStringVector * XLALCreateEmptyStringVector(UINT4 length)
int XLALREAL8TimeFreqFFT(COMPLEX16FrequencySeries *freq, const REAL8TimeSeries *tser, const REAL8FFTPlan *plan)
int XLALREAL8FreqTimeFFT(REAL8TimeSeries *tser, const COMPLEX16FrequencySeries *freq, const REAL8FFTPlan *plan)
const LALUnit lalDimensionlessUnit
INT4Vector * XLALCreateINT4Vector(UINT4 length)
void XLALDestroyUINT4Vector(UINT4Vector *vector)
COMPLEX16Vector * XLALCreateCOMPLEX16Vector(UINT4 length)
void XLALDestroyREAL4Vector(REAL4Vector *vector)
UINT4Vector * XLALCreateUINT4Vector(UINT4 length)
void XLALDestroyINT4Vector(INT4Vector *vector)
REAL4Vector * XLALCreateREAL4Vector(UINT4 length)
REAL8Vector * XLALCreateREAL8Vector(UINT4 length)
void XLALDestroyREAL8Vector(REAL8Vector *vector)
void XLALDestroyCOMPLEX16Vector(COMPLEX16Vector *vector)
REAL8Vector * XLALDDVectorMultiply(REAL8Vector *out, const REAL8Vector *in1, const REAL8Vector *in2)
#define XLAL_ERROR_VOID(...)
#define XLAL_ERROR_REAL8(...)
#define XLAL_ERROR_NULL(...)
#define XLAL_ERROR(...)
#define XLAL_PRINT_WARNING(...)
#define XLAL_TRY(statement, errnum)
int XLALPrintError(const char *fmt,...) _LAL_GCC_PRINTF_FORMAT_(1
int int XLALPrintWarning(const char *fmt,...) _LAL_GCC_PRINTF_FORMAT_(1
#define XLAL_ERROR_REAL4(...)
XLAL_ENOMEM
XLAL_SUCCESS
XLAL_EFAULT
XLAL_ETYPE
XLAL_EIO
XLAL_EINVAL
XLAL_EFAILED
XLAL_FAILURE
list mu
header
args
type
deltaLogL
c
COMPLEX16Sequence * data
COMPLEX16 * data
INT4 * data
UINT4 length
Structure to contain IFO data.
Definition: LALInference.h:625
The kD trees in LALInference are composed of cells.
Definition: LALInference.h:915
struct tagLALInferenceKDTree * right
Left (i.e.
Definition: LALInference.h:936
int eigenFrameStale
Maximum coordinates of points in the eigen-frame.
Definition: LALInference.h:930
REAL8 * eigenMax
Minimum coordinates of points in the eigen-frame.
Definition: LALInference.h:929
REAL8 * upperRight
Lower left (i.e.
Definition: LALInference.h:923
REAL8 ** ptsCovEigenVects
dim-by-dim covariance matrix.
Definition: LALInference.h:925
size_t ptsSize
Stores the number of tree points that lie in the cell.
Definition: LALInference.h:917
size_t dim
Size of the pts buffer.
Definition: LALInference.h:918
REAL8 * lowerLeft
Mean of pts.
Definition: LALInference.h:921
REAL8 ** pts
Dimension of the system.
Definition: LALInference.h:919
struct tagLALInferenceKDTree * left
== 1 when the mean, covariance, and eigenvectors are out of date (i.e.
Definition: LALInference.h:933
REAL8 * eigenMin
Eigenvectors of the covariance matrix: [i][j] is the jth component of the ith eigenvector.
Definition: LALInference.h:928
REAL8 ** ptsCov
Upper right (i.e.
Definition: LALInference.h:924
Structure to constain a model and its parameters.
Definition: LALInference.h:436
REAL8FFTPlan * timeToFreqFFTPlan
Burst Waveform cache for LIB.
Definition: LALInference.h:460
COMPLEX16FrequencySeries * freqhPlus
Time series model buffers.
Definition: LALInference.h:454
REAL8TimeSeries * timehCross
Definition: LALInference.h:453
REAL8TimeSeries * timehPlus
Definition: LALInference.h:453
COMPLEX16FrequencySeries * freqhCross
Definition: LALInference.h:454
REAL8FFTPlan * freqToTimeFFTPlan
Definition: LALInference.h:460
INT4 freqLength
Sampling rate information.
Definition: LALInference.h:451
REAL8Window * window
Pre-calculated FFT plans for forward and reverse FFTs.
Definition: LALInference.h:461
Structure for holding a proposal cycle.
Definition: LALInference.h:526
LALInferenceProposal ** proposals
Definition: LALInference.h:527
INT4 nProposals
Length of cycle.
Definition: LALInference.h:530
char name[VARNAME_MAX]
Definition: LALInference.h:514
Structure containing inference run state This includes pointers to the function types required to run...
Definition: LALInference.h:592
LALInferenceVariables * proposalArgs
The data from the interferometers.
Definition: LALInference.h:602
LALInferenceVariables * algorithmParams
Any special arguments for the prior function.
Definition: LALInference.h:604
INT4 nthreads
Array of live points for Nested Sampling.
Definition: LALInference.h:606
struct tagLALInferenceIFOData * data
Log sample, i.e.
Definition: LALInference.h:601
LALInferenceVariables * priorArgs
Common arguments needed by proposals, to be copied to thread->cycle.
Definition: LALInference.h:603
LALInferenceThreadState * threads
Definition: LALInference.h:612
Structure containing chain-specific variables.
Definition: LALInference.h:541
LALInferenceVariables * proposedParams
Current location going into jump proposal.
Definition: LALInference.h:558
LALInferenceVariables * algorithmParams
Arguments needed by proposals.
Definition: LALInference.h:552
LALInferenceVariables * currentParams
Prior boundaries, etc.
Definition: LALInference.h:556
LALInferenceVariables * priorArgs
Stope things such as output arrays.
Definition: LALInference.h:553
REAL8 currentPropDensity
Stucture containing model buffers and parameters.
Definition: LALInference.h:549
LALInferenceModel * model
Cycle of proposals to call.
Definition: LALInference.h:548
size_t differentialPointsLength
Array of points for differential evolution.
Definition: LALInference.h:560
LALInferenceVariables * proposalArgs
Definition: LALInference.h:551
REAL8 temperature
Array containing multiple proposal densities.
Definition: LALInference.h:550
INT4 * temp_swap_accepts
Pointer to the parent RunState of the thread.
Definition: LALInference.h:579
size_t differentialPointsSize
Length of the current differential points stored in differentialPoints.
Definition: LALInference.h:563
size_t differentialPointsSkip
Size of the differentialPoints memory block (must be >= length of differential points).
Definition: LALInference.h:566
LALInferenceVariables ** differentialPoints
Parameters proposed.
Definition: LALInference.h:559
LALInferenceVariables * preProposalParams
The current parameters.
Definition: LALInference.h:557
The LALInferenceVariableItem list node structure This should only be accessed using the accessor func...
Definition: LALInference.h:154
char name[VARNAME_MAX]
Definition: LALInference.h:155
LALInferenceVariableType type
Definition: LALInference.h:157
struct tagVariableItem * next
Definition: LALInference.h:159
LALInferenceParamVaryType vary
Definition: LALInference.h:158
The LALInferenceVariables structure to contain a set of parameters Implemented as a linked list of LA...
Definition: LALInference.h:170
LALHashTbl * hash_table
Definition: LALInference.h:173
LALInferenceVariableItem * head
Definition: LALInference.h:171
INT4 gpsNanoSeconds
CHAR type[LIGOMETA_TYPE_MAX]
CHAR param[LIGOMETA_PARAM_MAX]
CHAR value[LIGOMETA_VALUE_MAX]
struct tagProcessParamsTable * next
CHAR program[LIGOMETA_PROGRAM_MAX]
REAL4 * data
REAL8Sequence * data
REAL8Sequence * data
LIGOTimeGPS epoch
REAL8 * data
REAL8Sequence * data
REAL8 sumofsquares
UINT4 * data
LALInferenceVariableItem * itemPtr
Definition: LALInference.c:56
const char * name
Definition: LALInference.c:55
FILE * fp
enum @1 epoch
double df
char * outfile