int* lowly_get_ell(int *pnell, int *inell, int lmax,error **err) { int *outell; int nell,i; nell = *pnell; if (nell==0) { outell = malloc_err(sizeof(int)*(lmax+1),err); forwardError(*err,__LINE__,NULL); for(i=0;i<lmax+1;i++) { outell[i]=i; } nell = lmax+1; } else { outell = malloc_err(sizeof(int)*nell,err); forwardError(*err,__LINE__,NULL); memcpy(outell,inell,sizeof(int)*nell); } *pnell = nell; if (lmax!=0) { for(i=0;i<nell;i++) { testErrorRetVA(outell[i]>lmax,lowly_lbig,"ell[%d]=%d>lmax (%d)",*err,__LINE__,NULL,i,outell[i],lmax); } } return outell; }
int lklbs_get_par_id(lklbs* self,extraname name, error **err) { int i; void *old; if (self->rbs->xnames!=NULL) { // check whether the parameter is not one of the bs parameters for(i=0;i<self->ndim;i++) { if (strcmp(self->rbs->xnames[i],name)==0) { return i-self->ndim; } } } if (self->xdim==0) { self->xnames = malloc_err(sizeof(extraname),err); sprintf(self->xnames[0],"%s",name); self->xdim = 1; return 0; } for(i=0;i<self->xdim;i++) { if (strcmp(self->xnames[i],name)==0) { return i; } } old = self->xnames; self->xnames = malloc_err(sizeof(extraname)*(self->xdim+1),err); forwardError(*err,__LINE__,-1); memcpy(self->xnames,old,self->xdim*sizeof(extraname)); sprintf(self->xnames[self->xdim],"%s",name); self->xdim++; free(old); return self->xdim-1; }
particle_t *initialize_particle_t(int d, error **err) { particle_t *pa = (particle_t*)malloc_err(sizeof(particle_t), err); forwardError(*err, __LINE__,); pa->d = d; pa->diff = 0.0; pa->weight = 0.0; pa->param = (double*)malloc_err(d * sizeof(double), err); forwardError(*err, __LINE__,); pa->param_gsl = gsl_vector_alloc(d); return pa; }
cmblkl *init_cmblkl(void* lkl_data, posterior_log_pdf_func* lkl_func, posterior_log_free *lkl_free, int nell,int* ell,int* has_cl,int lmax, double unit, double *wl, int wlselect,double *bins,int nbins,int xdim, error **err) { cmblkl *self; int *_ell,_nell; self = malloc_err(sizeof(cmblkl),err); forwardError(*err,__LINE__,NULL); self->unit = unit; self->lkl_data = lkl_data; self->lkl_func = lkl_func; self->lkl_free = lkl_free; self->nell = nell; self->ell = lowly_get_ell(&self->nell, ell, lmax, err); forwardError(*err,__LINE__,NULL); _ell = self->ell; _nell = self->nell; self->ndim = lowly_get_offset_cl(has_cl, self->offset_cl,self->nell); self->xdim = xdim; self->wl=NULL; if (wl!=NULL) { self->wl = malloc_err(sizeof(double)*_nell,err); forwardError(*err,__LINE__,NULL); if (wlselect==1) { memcpy(self->wl,wl,sizeof(double)*_nell); } else { int il; for(il=0;il<_nell;il++) { self->wl[il] = wl[_ell[il]]; } } } self->bins = NULL; self->nbins = self->ndim; // if I have no binning matrix, nbins = ndim if (nbins!=0 && bins!=NULL) { self->nbins = nbins; self->pls = malloc_err(sizeof(double)*((self->ndim+1)*self->nbins+self->xdim), err); self->bins = self->pls + self->nbins + self->xdim; forwardError(*err,__LINE__,NULL); memcpy(self->bins,bins,sizeof(double)*self->ndim*self->nbins); } self->xnames = NULL; return self; }
distribution* init_distribution_full(int ndim, void* data, posterior_log_pdf_func* log_pdf, posterior_log_free* freef, simulate_func *simulate, int n_ded, retrieve_ded_func* retrieve, error **err) { distribution *dist; testErrorRet(n_ded!=0 && retrieve==NULL,dist_undef, "Target invalid, expect deduced parameters, but no function provided...", *err,__LINE__,NULL); dist = malloc_err(sizeof(distribution),err); forwardError(*err,__LINE__,NULL); dist->ndim = ndim; dist->n_ded = n_ded; dist->data = data; dist->log_pdf = log_pdf; dist->free = freef; dist->simulate = simulate; dist->retrieve = retrieve; dist->broadcast_mpi = NULL; dist->ndef = 0; dist->def = NULL; dist->pars = NULL; dist->dlhandle = NULL; dist->name = NULL; dist->f_der = NULL; dist->d_der = NULL; return dist; }
map_t *initialize_map_t(int N1, int N2, double theta_pix, error **err) { map_t *kMap = (map_t*)malloc_err(sizeof(map_t), err); forwardError(*err, __LINE__,); kMap->N1 = N1; kMap->N2 = N2; kMap->length = N1 * N2; kMap->theta_pix = theta_pix; kMap->center[0] = 0.0; kMap->center[1] = 0.0; kMap->limits[0] = -0.5 * N1 * theta_pix; kMap->limits[1] = -kMap->limits[0]; kMap->limits[2] = -0.5 * N2 * theta_pix; kMap->limits[3] = -kMap->limits[2]; kMap->type = kappa_map; kMap->kappa_mean = 0.0; kMap->kappa = (double*)malloc_err(kMap->length * sizeof(double), err); forwardError(*err, __LINE__,); return kMap; }
particle_arr *initialize_particle_arr(int d, int p, error **err) { particle_arr *part = (particle_arr*)malloc_err(sizeof(particle_arr), err); forwardError(*err, __LINE__,); part->d = d; part->p = p; part->nbAttempts = 0; part->array = (particle_t**)malloc_err(p * sizeof(particle_t*), err); forwardError(*err, __LINE__,); part->mean = initialize_double_arr(d); part->cov = gsl_matrix_alloc(d, d); part->cov2 = gsl_matrix_alloc(d, d); part->invCov = gsl_matrix_alloc(d, d); part->perm = gsl_permutation_alloc(d); int i; for (i=0; i<p; i++) { part->array[i] = initialize_particle_t(d, err); forwardError(*err, __LINE__,); } return part; }
cmblkl *init_cmblkl_select(void* lkl_data, posterior_log_pdf_func* lkl_func, posterior_log_free *lkl_free, int *lmax, int xdim, error **err) { cmblkl_select *selec; cmblkl *self; int mlmax,i; int has_cl[6]; int np; selec = malloc_err(sizeof(cmblkl_select),err); forwardError(*err,__LINE__,NULL); np = lmax[0]+1; mlmax = lmax[0]; for (i=0;i<6;i++) { has_cl[i]=0; if (lmax[i]!=-1) { has_cl[i] = 1; } if (lmax[i]>mlmax) { mlmax = lmax[i]; } selec->lmax[i] = lmax[i]; np += lmax[i] + 1; } selec->mlmax = mlmax; selec->lkl_data = lkl_data; selec->lkl_func = lkl_func; selec->lkl_free = lkl_free; selec->xdim = xdim; selec->ndim = np; selec->pars = malloc_err(sizeof(double)*(np+xdim),err); forwardError(*err,__LINE__,NULL); self = init_cmblkl(selec,select_func,select_free,0,NULL,has_cl,mlmax,1,NULL,0,NULL,0,xdim,err); forwardError(*err,__LINE__,NULL); return self; }
void cmblkl_set_names(cmblkl *lkl, char **names, error **err) { int i; if (lkl->xnames!=NULL) { free(lkl->xnames); } lkl->xnames = malloc_err(sizeof(extraname)*lkl->xdim,err); forwardError(*err,__LINE__,); for(i=0;i<lkl->xdim;i++) { sprintf(lkl->xnames[i],"%s",names[i]); } }
bs_struct *init_bs_struct(int ndim, void* bs, compute_cl_func* bs_compute, posterior_log_free* bs_free, char **_xnames, error **err) { bs_struct *rbs; rbs = malloc_err(sizeof(bs_struct), err); forwardError(*err,__LINE__,NULL); rbs->bs = bs; rbs->bs_compute = bs_compute; rbs->bs_free = bs_free; rbs->ndim = ndim; rbs->xnames = NULL; if (_xnames!=NULL) { int i; rbs->xnames = malloc_err(sizeof(extraname)*ndim,err); forwardError(*err,__LINE__,NULL); for (i=0;i<ndim;i++) { sprintf(rbs->xnames[i],"%s",_xnames[i]); } } return rbs; }
zero_bs* init_zero_bs(int *lmax, error **err) { zero_bs *zbs; int i; zbs = malloc_err(sizeof(zero_bs), err); forwardError(*err,__LINE__,NULL); zbs->ndim = 0; for (i=0; i<6; i++) { zbs->lmax[i] = lmax[i]; //_DEBUGHERE_("zzz lmax %d %d",lmax[i],zbs->ndim); zbs->ndim += lmax[i] + 1; } //_DEBUGHERE_("zzz ndim %d",zbs->ndim); return zbs; }
struct OmitID3frame *AddOmitID3framelist(struct OmitID3frame *ptr,const char *frameid) { struct OmitID3frame *temp; assert_wrapper(frameid != NULL); //Allocate and init new link temp=malloc_err(sizeof(struct OmitID3frame)); temp->frameid=DuplicateString(frameid); //Append link to existing list if applicable temp->next=ptr; //The new link becomes the head and points forward to whatever the head was return temp; //Otherwise return the new linked list head }
void cmblkl_check_xnames(cmblkl *self,int ii,error **err) { int i; char name_tpl[50]; if (self->xnames!=NULL || self->xdim==0) { return; } sprintf(name_tpl,"LKL_%d",ii); self->xnames = malloc_err(sizeof(extraname)*self->xdim,err); forwardError(*err,__LINE__,); for(i=0;i<self->xdim;i++) { sprintf(self->xnames[i],"%s_extra_%d",name_tpl,i); } }
chi2_t *initialize_chi2_t(int N, int d, error **err) { //-- N = number of data //-- d = dimension of observable vector //-- *X_model = observables from model, mean of several realizations for Camelus //-- *intermediate = to stock invCov * (X_model - X_obs) //-- *X_obs = observables from observation //-- *cov = covariance matrix for X_model, debiased //-- *cov2 = just a copy of cov //-- *invCov = inverse of cov, debiased //-- *perm = used for matrix inversion chi2_t *chichi = (chi2_t*)malloc_err(sizeof(chi2_t), err); forwardError(*err, __LINE__,); chichi->N = N; chichi->d = d; chichi->X_model = gsl_vector_alloc(d); chichi->intermediate = gsl_vector_alloc(d); chichi->X_obs = gsl_vector_alloc(d); chichi->cov = gsl_matrix_alloc(d, d); chichi->cov2 = gsl_matrix_alloc(d, d); chichi->invCov = gsl_matrix_alloc(d, d); chichi->perm = gsl_permutation_alloc(d); return chichi; }
cmblkl* wlik_wmap_init(char *dirname, int ttmin, int ttmax, int temin, int temax, int use_gibbs, int use_lowl_pol, error **err) { int bok; cmblkl *cing,*target; int mlmax; char pwd[5000]; int has_cl[6],lmaxs[6]; int *ell; int lmax,l,n_cl,cli; zero_bs* zbs; //only one wmap wmap_extra_only_one_(&bok); testErrorRet(bok!=0,-100,"wmap already initialized",*err,__LINE__,NULL); //change dir testErrorRetVA(getcwd(pwd,4096)==NULL,-101010,"can't get cwd name (cause = '%s')",*err,__LINE__,NULL,strerror(errno)); testErrorRetVA(chdir(dirname)!=0,-100,"Cannot change dir to %s (cause = '%s')",*err,__LINE__,NULL,dirname,strerror(errno)); // call wmap_init wmap_extra_parameter_init_(&ttmin,&ttmax,&temin,&temax,&use_gibbs,&use_lowl_pol); //change dir back testErrorRetVA(chdir(pwd)!=0,-100,"Cannot change dir to %s (cause = '%s')",*err,__LINE__,NULL,pwd,strerror(errno)); lmax = ttmax; if (temax>ttmax) { lmax = temax; } has_cl[0]=0; has_cl[1]=0; has_cl[2]=0; has_cl[3]=0; has_cl[4]=0; has_cl[5]=0; lmaxs[0]=-1; lmaxs[1]=-1; lmaxs[2]=-1; lmaxs[3]=-1; lmaxs[4]=-1; lmaxs[5]=-1; if (ttmin<=ttmax && ttmax>0) { has_cl[0]=1; } if (temin<=temax && temax>0) { has_cl[1]=1; has_cl[2]=1; has_cl[3]=1; } ell = malloc_err(sizeof(double)*(lmax+1),err); forwardError(*err,__LINE__,NULL); for(l=0;l<=lmax;l++) { ell[l] = l; } cing = init_cmblkl(NULL, &wmap_lkl, &free_wmap, lmax+1,ell, has_cl,lmax,1,NULL,0,NULL,0,0,err); forwardError(*err,__LINE__,NULL); n_cl = 0; for(cli=0;cli<6;cli++) { n_cl += (lmax+1)*has_cl[cli]; } cmblkl_max_lmax(cing,lmaxs,err); forwardError(*err,__LINE__,NULL); zbs = init_zero_bs(lmaxs, err); forwardError(*err,__LINE__,NULL); target = init_multilklbs_distribution(n_cl , &cing,1, zbs, &zero_bs_compute, &free_zero_bs, lmaxs, err); forwardError(*err,__LINE__,NULL); free(ell); return target; }
void JB_Load(FILE *inf) { size_t maxlinelength; //I will count the length of the longest line (including NULL char/newline) in the //input file so I can create a buffer large enough to read any line into char *buffer; //Will be an array large enough to hold the largest line of text from input file unsigned long index=0; //Used to index within a line of input text unsigned long index2=0; //Used to index within an output buffer char textbuffer[101]={0}; //Allow for a 100 character lyric text unsigned long processedctr=0; //The current line number being processed in the text file unsigned long bufferctr=0; //Ensure textbuffer[] isn't overflowed char notename=0; //Used for parsing note names double timestamp=0.0; //Used to read timestamp char linetype=0; //Is set to one of the following: 1 = lyric, 2 = line break, 3 = end of file unsigned char pitch=0; //Stores the lyric pitch transposed to middle octave int readerrordetected = 0; assert_wrapper(inf != NULL); //This must not be NULL //Find the length of the longest line maxlinelength=FindLongestLineLength(inf,1); //Allocate memory buffer large enough to hold any line in this file buffer=(char *)malloc_err(maxlinelength); (void) fgets_err(buffer,(int)maxlinelength,inf); //Read first line of text, capping it to prevent buffer overflow if(Lyrics.verbose) printf("\nImporting C9C lyrics from file \"%s\"\n\n",Lyrics.infilename); processedctr=0; //This will be set to 1 at the beginning of the main while loop while(!feof(inf) && !readerrordetected) //Until end of file is reached or fgets() returns an I/O error { processedctr++; if(Lyrics.verbose) printf("\tProcessing line %lu\n",processedctr); index = 0; //Read end of file if(strcasestr_spec(buffer,"ENDFILE")) { //A line starting with "ENDFILE" denotes the end of the lyric entries linetype = 3; } //Read the lyric pitch else if(isalpha(buffer[index])) { //A line starting with an alphabetical letter is a normal lyric entry linetype = 1; notename = toupper(buffer[index++]); if(isalpha(buffer[index])) index++; //The first lyric entry seems to repeat the note name pitch=60; //The pitches will be interpreted as ranging from C4 to B4 switch(notename) //Add value of note in current octave { case 'B': pitch+=11; break; case 'A': pitch+=9; break; case 'G': pitch+=7; break; case 'F': pitch+=5; break; case 'E': pitch+=4; break; case 'D': pitch+=2; break; default: break; } if(buffer[index] == '#') { //If the note name is followed by a sharp character, pitch++; //increase the pitch by one half step index++; //Seek past the sharp character } while(buffer[index] != ':') { //Seek to the expected colon character if(buffer[index] == '\0') { //The line ends unexpectedly printf("Error: Invalid lyric entry in line %lu during C9C lyric import (colon missing)\nAborting\n",processedctr); exit_wrapper(1); } index++; } index++; //Seek beyond the colon //Read the lyric text index2=bufferctr=0; while(!isspace(buffer[index])) { //Until whitespace is reached if(buffer[index] == '\0') { //The line ends unexpectedly printf("Error: Invalid lyric entry in line %lu during C9C lyric import (whitespace missing)\nAborting\n",processedctr); exit_wrapper(2); } textbuffer[index2++] = buffer[index++]; //Copy the character to a buffer bufferctr++; if(bufferctr == 100) { //Unexpectedly long lyric reached printf("Error: Invalid lyric entry in line %lu during C9C lyric import (lyric is too long)\nAborting\n",processedctr); exit_wrapper(3); } } textbuffer[index2++] = '\0'; //Terminate the string }//A line starting with an alphabetical letter is a normal lyric entry //Read line break else if(buffer[index] == '-') { //A line starting with "--:S" is the start of a period of silence between lyrics (will be treated as a line break) linetype = 2; } else { //Invalid input printf("Error: Invalid input \"%s\" in line %lu during C9C import\nAborting\n",&(buffer[index]),processedctr); exit_wrapper(4); } //Seek to timestamp while(!isdigit(buffer[index])) { //Until a number (the timestamp) is reached if(buffer[index] == '\0') { //The line ends unexpectedly printf("Error: Invalid line break entry in line %lu during C9C lyric import (timestamp missing)\nAborting\n",processedctr); exit_wrapper(5); } index++; } //Read timestamp if(sscanf(&(buffer[index]), "%20lf", ×tamp) != 1) { //Double floating point value didn't parse printf("Error: Invalid lyric entry in line %lu during C9C lyric import (error parsing timestamp)\nAborting\n",processedctr); exit_wrapper(6); } timestamp *= 1000.0; //Convert to milliseconds //Adjust previous lyric's end position if(Lyrics.lastpiece) { //If there was a previous lyric unsigned long length; assert_wrapper(Lyrics.lastpiece->lyric != NULL); length = (unsigned long)strlen(Lyrics.lastpiece->lyric); Lyrics.lastpiece->duration = timestamp + 0.5 - Lyrics.realoffset - Lyrics.lastpiece->start; //Remember to offset start by realoffset, otherwise Lyrics.lastpiece->start could be the larger operand, causing an overflow if(Lyrics.lastpiece->lyric[length - 1] == '-') { //If the previous lyric ended in a hyphen, the previous lyric lasts all the way up to the start of this one Lyrics.lastpiece->groupswithnext=1; //The previous lyric piece will group with this one } else { //Otherwise space out the lyrics a bit, 1/32 second was suggested if(Lyrics.lastpiece->duration > 31) Lyrics.lastpiece->duration -= 31; //31ms ~= 1 sec/32 } } //Add lyric if(linetype == 1) //If this line defined a new lyric { //Track for pitch changes, enabling Lyrics.pitch_tracking if applicable if((Lyrics.last_pitch != 0) && (Lyrics.last_pitch != pitch)) //There's a pitch change Lyrics.pitch_tracking=1; Lyrics.last_pitch=pitch; //Consider this the last defined pitch if(Lyrics.line_on != 1) //If we're at this point, there should be a line of lyrics in progress CreateLyricLine(); AddLyricPiece(textbuffer,timestamp + 0.5,timestamp + 0.5,pitch,0); //Add lyric with no defined duration } //Add line break else if(linetype == 2) { //If this line defined a line break EndLyricLine(); Lyrics.lastpiece = NULL; //Prevent the first lyric from the new line from altering the previous lyric's duration, which was set by the line break position } //End processing else break; if(fgets(buffer, (int)maxlinelength,inf) == NULL) //Read next line of text, so the EOF condition can be checked, don't exit on EOF readerrordetected = 1; }//while(!feof(inf) && !readerrordetected) free(buffer); //No longer needed, release the memory before exiting function ForceEndLyricLine(); RecountLineVars(Lyrics.lines); //Rebuild line durations since this lyric format required adjusting timestamps after lines were parsed if(Lyrics.verbose) printf("C9C import complete. %lu lyrics loaded\n\n",Lyrics.piececount); }
SMC_ABC_t *initialize_SMC_ABC_t(peak_param *peak, error **err) { SMC_ABC_t *ABC = (SMC_ABC_t*)malloc_err(sizeof(SMC_ABC_t), err); forwardError(*err, __LINE__,); ABC->d = peak->ABC_d; ABC->p = peak->ABC_p; ABC->r_stop = peak->ABC_r_stop; int i; STRING2ENUM(ABC->summ, peak->ABC_summ, summary_t, STR_SUMMARY_T, i, NB_SUMMARY_T, err); forwardError(*err, __LINE__,); ABC->epsilon_0 = DBL_MAX; ABC->priorFct = prior_pentagon; ABC->t = 0; ABC->oldPart = initialize_particle_arr(ABC->d, ABC->p, err); forwardError(*err, __LINE__,); ABC->newPart = initialize_particle_arr(ABC->d, ABC->p, err); forwardError(*err, __LINE__,); ABC->diffList = initialize_double_arr(ABC->p); if (ABC->summ == abd6) { ABC->obsSummary = initialize_double_arr(6); ABC->simulSummary = initialize_double_arr(6); ABC->peakHist = initialize_hist_t(6); set_hist_t(ABC->peakHist, 3.5, 6.5); ABC->peakHist->x_max = 1000.0; //-- So that bins are [3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 1000.0] ABC->summaryFct = summary_abd_all; ABC->distFct = dist_abd6; } else if (ABC->summ == pct6) { ABC->obsSummary = initialize_double_arr(6); ABC->simulSummary = initialize_double_arr(6); ABC->summaryFct = summary_pct6; ABC->distFct = dist_6D; } else if (ABC->summ == cut6) { ABC->obsSummary = initialize_double_arr(6); ABC->simulSummary = initialize_double_arr(6); ABC->summaryFct = summary_cut6; ABC->distFct = dist_6D; } else if (ABC->summ == abd5) { ABC->obsSummary = initialize_double_arr(5); ABC->simulSummary = initialize_double_arr(5); ABC->peakHist = initialize_hist_t(5); ABC->peakHist->x_lower[0] = 3.0; ABC->peakHist->x_lower[1] = 3.8; ABC->peakHist->x_lower[2] = 4.5; ABC->peakHist->x_lower[3] = 5.3; ABC->peakHist->x_lower[4] = 6.2; ABC->peakHist->x_max = 1000.0; //-- So that bins are [3.0, 3.8, 4.5, 5.3, 6.2, 1000.0] ABC->summaryFct = summary_abd_all; ABC->distFct = dist_abd5; } else if (ABC->summ == pct5) { ABC->obsSummary = initialize_double_arr(5); ABC->simulSummary = initialize_double_arr(5); ABC->summaryFct = summary_pct5; ABC->distFct = dist_pct5; } else if (ABC->summ == cut5) { ABC->obsSummary = initialize_double_arr(5); ABC->simulSummary = initialize_double_arr(5); ABC->summaryFct = summary_cut5; ABC->distFct = dist_cut5; } else if (ABC->summ == pct4) { ABC->obsSummary = initialize_double_arr(4); ABC->simulSummary = initialize_double_arr(4); ABC->summaryFct = summary_pct4; ABC->distFct = dist_4D; } else if (ABC->summ == pct998) { ABC->obsSummary = initialize_double_arr(1); ABC->simulSummary = initialize_double_arr(1); ABC->summaryFct = summary_pct998; ABC->distFct = dist_1D; } else if (ABC->summ == pct996) { ABC->obsSummary = initialize_double_arr(1); ABC->simulSummary = initialize_double_arr(1); ABC->summaryFct = summary_pct996; ABC->distFct = dist_1D; } else if (ABC->summ == cut900) { ABC->obsSummary = initialize_double_arr(1); ABC->simulSummary = initialize_double_arr(1); ABC->summaryFct = summary_cut900; ABC->distFct = dist_1D; } else {*err = addError(peak_unknown, "Unknown summary type", *err, __LINE__); forwardError(*err, __LINE__,);} int length = (peak->resol[0] - 2 * peak->bufferSize) * (peak->resol[1] - 2 * peak->bufferSize); cosmo_hm *cmhm = initialize_cosmo_hm_default(err); forwardError(*err, __LINE__,); ABC->sampArr = initialize_sampler_arr(peak->N_z_halo, peak->nbMassBins); ABC->hMap = initialize_halo_map(peak->resol[0], peak->resol[1], peak->theta_pix, err); forwardError(*err, __LINE__,); ABC->gMap = initialize_gal_map(peak->resol[0], peak->resol[1], peak->theta_pix, err); forwardError(*err, __LINE__,); makeGalaxies(cmhm, peak, ABC->gMap, err); forwardError(*err, __LINE__,); ABC->kMap = initialize_map_t(peak->resol[0], peak->resol[1], peak->theta_pix, err); forwardError(*err, __LINE__,); ABC->nMap = initialize_map_t(peak->resol[0], peak->resol[1], peak->theta_pix, err); forwardError(*err, __LINE__,); ABC->transformer = initialize_FFT_t(peak->FFTSize, peak->FFTSize); fillGaussianKernel(ABC->transformer, peak->s); ABC->peakList = initialize_double_arr(length); free_parameters_hm(&cmhm); printf("ABC initialization done\n"); return ABC; }
void SRT_Load(FILE *inf) { char *buffer; //Buffer used to read from input file char *temp=NULL; //Used for string processing unsigned long processedctr=0; //The current line number being processed in the text file size_t maxlinelength; //I will count the length of the longest line (including NULL char/newline) in the //input file so I can create a buffer large enough to read any line into unsigned long startstamp=0,endstamp=0; unsigned long ctr=0; assert_wrapper(inf != NULL); //This must not be NULL //Find the length of the longest line maxlinelength=FindLongestLineLength(inf,1); //Allocate buffers to read file line by line buffer=malloc_err(maxlinelength); //Process each line of input file if(Lyrics.verbose) printf("\nImporting SRT subtitles from file \"%s\"\n\n",Lyrics.infilename); processedctr=0; //This will be set to 1 at the beginning of the main while loop while(fgets(buffer,(int)maxlinelength,inf) != NULL) //Read lines until end of file is reached, don't exit on EOF { processedctr++; //Find first timestamp in this line temp=SeekNextSRTTimestamp(buffer); //Point temp to first timestamp if(temp == NULL) //If there is none, skip this line continue; //Skip processing and read next line startstamp=ConvertSRTTimestamp(&temp,NULL); //Find second timestamp in this line temp=SeekNextSRTTimestamp(temp); //Point temp to second timestamp if(temp == NULL) { if(Lyrics.verbose) printf("Warning: Line #%lu does not contain the ending timestamp. Ignoring\n",processedctr); continue; //Skip processing and read next line } endstamp=ConvertSRTTimestamp(&temp,NULL); //Read next line, which is expected to be the subtitle entry if(fgets(buffer,(int)maxlinelength,inf) == NULL) break; //If another line couldn't be read, exit loop ctr = (unsigned long)strlen(buffer); //Find index of the string's NULL terminator while((ctr > 0) && ((buffer[ctr-1] == '\n') || (buffer[ctr-1] == '\r'))) { //If the string isn't empty and the last character is a newline or carriage return buffer[ctr-1] = '\0'; //Truncate it from the string ctr--; //Track the position of the end of the string } //Add lyric piece as a lyric line CreateLyricLine(); AddLyricPiece(buffer,startstamp,endstamp,PITCHLESS,0); //Write lyric with no defined pitch EndLyricLine(); }//end while(fgets(buffer,maxlinelength,inf) != NULL) ForceEndLyricLine(); //Release memory buffers and return free(buffer); if(Lyrics.verbose) printf("SRT import complete. %lu subtitles loaded\n\n",Lyrics.piececount); }
lklbs* init_fulllklbs(cmblkl** lkls,int nlkl, bs_struct* rbs, int *lmax, error **err) { lklbs* self; int cli,ilkl; int lndim; int ofx; int nrx,irx; self = malloc_err(sizeof(lklbs),err); forwardError(*err,__LINE__,NULL); self->rbs = rbs; self->ndim = rbs->ndim; self->lkls = malloc_err(sizeof(cmblkl*)*nlkl,err); forwardError(*err,__LINE__,NULL); self->ofx = malloc_err(sizeof(int)*nlkl,err); forwardError(*err,__LINE__,NULL); memcpy(self->lkls,lkls,sizeof(cmblkl*)*nlkl); self->nlkl = nlkl; lndim = 0; ofx = 0; self->xdim=0; nrx = 0; for(ilkl=0;ilkl<self->nlkl;ilkl++) { nrx += lkls[ilkl]->xdim; } if (nrx!=0) { self->rx = malloc_err(sizeof(int)*nrx,err); forwardError(*err,__LINE__,NULL); } self->nrx = nrx; irx = 0; for(ilkl=0;ilkl<self->nlkl;ilkl++) { int nd; int xi; int ipos; cmblkl_check_lmax(self->lkls[ilkl],lmax,err); forwardError(*err,__LINE__,NULL); cmblkl_check_xnames(self->lkls[ilkl],ilkl,err); forwardError(*err,__LINE__,NULL); for (xi=0;xi<lkls[ilkl]->xdim;xi++) { ipos = lklbs_get_par_id(self,lkls[ilkl]->xnames[xi],err); forwardError(*err,__LINE__,NULL); self->rx[irx+xi] = ipos; } self->ofx[ilkl] = irx; irx += lkls[ilkl]->xdim; nd = lkls[ilkl]->ndim + lkls[ilkl]->xdim; if(lndim<nd) { lndim=nd; } self->ofx[ilkl] = ofx; ofx += lkls[ilkl]->xdim; } self->tot_cl = 0; for(cli=0;cli<6;cli++) { if (lmax[cli]!=-1) { self->offset_lmax[cli] = self->tot_cl; self->tot_cl += lmax[cli] + 1; } else { self->offset_lmax[cli] = -1; } } self->cl_theo=malloc_err(sizeof(double)*(lndim+self->tot_cl),err); forwardError(*err,__LINE__,NULL); self->cl_select=self->cl_theo + self->tot_cl; return self; }
unsigned long ID3FrameProcessor(struct ID3Tag *ptr) { unsigned char header[10]={0}; //Used to store the ID3 frame header unsigned long filepos=0; int ctr2=0; //Used to validate frame ID struct ID3Frame *temp=NULL; //Used to allocate an ID3Frame link struct ID3Frame *head=NULL; //Used as the head pointer struct ID3Frame *cond=NULL; //Used as the conductor unsigned long ctr=0; //Count the number of frames processed unsigned long framesize=0; //Used to validate frame size char buffer[31]={0}; //Used to read an ID3v1 tag in the absence of an ID3v2 tag static struct ID3Frame emptyID3Frame; //Auto-initialize all members to 0/NULL //Validate input parameter if((ptr == NULL) || (ptr->fp == NULL)) return 0; //Return failure //Find and parse the ID3 header //ID3v1 fseek_err(ptr->fp,-128,SEEK_END); //Seek 128 back from the end of the file, where this tag would exist fread_err(buffer,3,1,ptr->fp); //Read 3 bytes for the "TAG" header buffer[3] = '\0'; //Ensure NULL termination if(strcasecmp(buffer,"TAG") == 0) //If this is an ID3v1 header { if(Lyrics.verbose) (void) puts("Loading ID3v1 tag"); ptr->id3v1present=1; //Track that this tag exists fread_err(buffer,30,1,ptr->fp); //Read the first field in the tag (song title) buffer[30] = '\0'; //Ensure NULL termination if(buffer[0] != '\0') //If the string isn't empty { ptr->id3v1present=2; //Track that this tag is populated ptr->id3v1title=DuplicateString(buffer); if(Lyrics.verbose) (void) puts("\tTitle loaded"); } fread_err(buffer,30,1,ptr->fp); //Read the second field in the tag (artist) buffer[30] = '\0'; //Ensure NULL termination if(buffer[0] != '\0') //If the string isn't empty { ptr->id3v1present=2; //Track that this tag is populated ptr->id3v1artist=DuplicateString(buffer); if(Lyrics.verbose) (void) puts("\tArtist loaded"); } fread_err(buffer,30,1,ptr->fp); //Read the third field in the tag (album) buffer[30] = '\0'; //Ensure NULL termination if(buffer[0] != '\0') //If the string isn't empty { ptr->id3v1present=2; //Track that this tag is populated ptr->id3v1album=DuplicateString(buffer); if(Lyrics.verbose) (void) puts("\tAlbum loaded"); } fread_err(buffer,4,1,ptr->fp); //Read the fourth field in the tag (year) buffer[4]='\0'; //Terminate the buffer to make it a string if(buffer[0] != '\0') //If the string isn't empty { ptr->id3v1present=2; //Track that this tag is populated ptr->id3v1year=DuplicateString(buffer); if(Lyrics.verbose) (void) puts("\tYear loaded"); } } //ID3v2 //Load ID3 frames into linked list rewind_err(ptr->fp); //Rewind file so that the ID3v2 header can be searched for if(FindID3Tag(ptr) == 0) //Locate the ID3 tag return 0; //Return if there was none if(Lyrics.verbose) (void) puts("Loading ID3v2 tag"); fseek_err(ptr->fp,ptr->framestart,SEEK_SET); //Seek to first ID3 frame filepos=ftell_err(ptr->fp); //Record file position of first expected ID3 frame while((filepos >= ptr->framestart) && (filepos < ptr->tagend)) { //While file position is at or after the end of the ID3 header, before or at end of the ID3 tag //Read frame header into buffer if(fread(header,10,1,ptr->fp) != 1) { ptr->frames=head; //Store the linked list into the ID3 tag structure return 0; //Return failure on I/O error } //Validate frame ID for(ctr2=0;ctr2<4;ctr2++) { if(!isupper(header[ctr2]) && !isdigit(header[ctr2])) //If the character is NOT valid for an ID3 frame ID { ptr->frames=head; //Store the linked list into the ID3 tag structure return ctr; //Return the number of frames that were already processed } } //Validate frame end framesize=((unsigned long)header[4]<<24) | ((unsigned long)header[5]<<16) | ((unsigned long)header[6]<<8) | ((unsigned long)header[7]); //Convert to 4 byte integer if(filepos + framesize + 10 > ptr->tagend) //If the defined frame size would cause the frame to extend beyond the end of the ID3 tag { ptr->frames=head; //Store the linked list into the ID3 tag structure return 0; //Return failure } //Initialize an ID3Frame structure temp=malloc_err(sizeof(struct ID3Frame)); //Allocate memory *temp=emptyID3Frame; //Reliably initialize all values to 0/NULL temp->frameid=malloc_err(5); //Allocate 5 bytes for the ID3 frame ID memcpy(temp->frameid,header,4); //Copy the 4 byte ID3 frame ID into the pre-terminated string temp->frameid[4]='\0'; //Terminate the string temp->pos=filepos; //Record the file position of the ID3 frame temp->length=((unsigned long)header[4]<<24) | ((unsigned long)header[5]<<16) | ((unsigned long)header[6]<<8) | ((unsigned long)header[7]); //Record the frame length (defined in header as 4 byte Big Endian integer) //Append ID3Frame link to the list if(head == NULL) //Empty list { head=temp; //Point head to new link cond=temp; //Point conductor to new link } else { assert_wrapper(cond != NULL); //The linked list is expected to not be corrupted cond->next=temp; //Conductor points forward to new link temp->prev=cond; //New link points back to conductor cond=temp; //Conductor points to new link } if(Lyrics.verbose >= 2) printf("\tFrame ID %s loaded\n",temp->frameid); ctr++; //Iterate counter (void) fseek(ptr->fp,framesize,SEEK_CUR); //Seek ahead to the beginning of the next ID3 frame filepos+=framesize + 10; //Update file position }//While file position is at or after the end of the ID3 header, before or at end of the ID3 tag if(Lyrics.verbose) printf("%lu ID3 frames loaded\n\n",ctr); ptr->frames=head; //Store the linked list into the ID3 tag structure return ctr; //Return the number of frames loaded }
int VL_PreLoad(FILE *inf,char validate) { long ftell_result=0; //Used to store return value from ftell() char buffer[5]= {0}; //Used to read word/doubleword integers from file unsigned long ctr=0; //Generic counter char *temp=NULL; //Temporary pointer for allocated strings struct VL_Sync_entry se= {0,0,0,0,0,NULL}; //Used to store sync entries from file during parsing struct VL_Text_entry *ptr1=NULL; //Used for allocating links for the text chunk list struct VL_Sync_entry *ptr2=NULL; //Used for allocation links for the sync chunk list struct VL_Text_entry *curtext; //Conductor for text chunk linked list struct VL_Sync_entry *cursync; //Conductor for sync chunk linked list assert_wrapper(inf != NULL); //Initialize variables VL.numlines=0; VL.numsyncs=0; VL.filesize=0; VL.textsize=0; VL.syncsize=0; VL.Lyrics=NULL; VL.Syncs=NULL; curtext=NULL; //list starts out empty cursync=NULL; //list starts out empty se.next=NULL; //In terms of linked lists, this always represents the last link if(Lyrics.verbose) (void) puts("Reading VL file header"); //Read file header fread_err(buffer,4,1,inf); //Read 4 bytes, which should be 'V','L','2',0 ReadDWORDLE(inf,&(VL.filesize)); //Read doubleword from file in little endian format if(strncmp(buffer,"VL2",4) != 0) { if(validate) return 1; else { (void) puts("Error: Invalid file header string\nAborting"); exit_wrapper(1); } } //Read text header fread_err(buffer,4,1,inf); //Read 4 bytes, which should be 'T','E','X','T' buffer[4]='\0'; //Add a NULL character to make buffer into a proper string ReadDWORDLE(inf,&(VL.textsize)); //Read doubleword from file in little endian format if(VL.textsize % 4 != 0) { (void) puts("Error: VL spec. violation: Sync chunk is not padded to a double-word alignment"); if(validate) return 2; else { (void) puts("Aborting"); exit_wrapper(2); } } if(strncmp(buffer,"TEXT",5) != 0) { (void) puts("Error: Invalid text header string"); if(validate) return 3; else { (void) puts("Aborting"); exit_wrapper(3); } } //Read sync header, which should be th.textsize+16 bytes into the file fseek_err(inf,VL.textsize+16,SEEK_SET); fread_err(buffer,4,1,inf); //Read 4 bytes, which should be 'S','Y','N','C' buffer[4]='\0'; //Add a NULL character to make buffer into a proper string ReadDWORDLE(inf,&(VL.syncsize)); //Read doubleword from file in little endian format if(strncmp(buffer,"SYNC",5) != 0) { (void) puts("Error: Invalid sync header string"); if(validate) return 4; else { (void) puts("Aborting"); exit_wrapper(4); } } //Validate chunk sizes given in headers (textsize was already validated if the Sync header was correctly read) fseek_err(inf,0,SEEK_END); //Seek to end of file ftell_result = ftell(inf); //Get position of end of file if(ftell_result < 0) { printf("Error determining file length during file size validation: %s\n",strerror(errno)); if(validate) return 5; else { (void) puts("Aborting"); exit_wrapper(5); } } if((unsigned long)ftell_result != VL.filesize+8) //Validate filesize { (void) puts("Error: Filesize does not match size given in file header"); if(validate) return 6; else { (void) puts("Aborting"); exit_wrapper(6); } } if(VL.filesize != VL.textsize + VL.syncsize + 16) //Validate syncsize { (void) puts("Error: Incorrect size given in sync chunk"); if(validate) return 7; else { (void) puts("Aborting"); exit_wrapper(7); } } //Load tags if(Lyrics.verbose) (void) puts("Loading VL tag strings"); fseek_err(inf,16,SEEK_SET); //Seek to the Title tag for(ctr=0; ctr<5; ctr++) //Expecting 5 null terminated unicode strings { temp=ReadUnicodeString(inf); //Allocate array and read Unicode string if(temp[0] != '\0') //If the string wasn't empty, save the tag switch(ctr) { //Look at ctr to determine which tag we have read, and assign to the appropriate tag string: case 0: SetTag(temp,'n',0); break; case 1: SetTag(temp,'s',0); break; case 2: SetTag(temp,'a',0); break; case 3: SetTag(temp,'e',0); break; case 4: //Offset SetTag(temp,'o',0); //Do not multiply the offset by -1 break; default: (void) puts("Unexpected error"); if(validate) return 8; else { (void) puts("Aborting"); exit_wrapper(8); } break; }//end switch(ctr) free(temp); //Free string, a copy of which would have been stored in the Lyrics structure as necessary }//end for(ctr=0;ctr<5;) //Validate the existence of three empty unicode strings for(ctr=0; ctr<3; ctr++) //Expecting 3 empty, null terminated unicode strings if(ParseUnicodeString(inf) != 0) { (void) puts("Error: Reserved string is not empty during load"); if(validate) return 9; else { (void) puts("Aborting"); exit_wrapper(9); } } //Load the lyric strings if(Lyrics.verbose) (void) puts("Loading text chunk entries"); while(1) //Read lyric lines { //Check to see if the Sync Chunk has been reached if((unsigned long)ftell_err(inf) >= VL.textsize + 16) //The Text chunk size + the file and text header sizes is the position of the Sync chunk break; //Read lyric string temp=ReadUnicodeString(inf); ftell_result=ftell_err(inf); //If this string is empty if(temp[0] == '\0') { if(VL.textsize+16 - ftell_result <= 3) //This 0 word value ends within 3 bytes of the sync header (is padding) { free(temp); //Release string as it won't be used break; //text chunk has been read } else { printf("Error: Empty lyric string detected before file position 0x%lX\n",ftell_result); free(temp); if(validate) return 10; else { (void) puts("Aborting"); exit_wrapper(10); } } } if((unsigned long)ftell_result > VL.textsize + 16) //If reading this string caused the file position to cross into Sync chunk { (void) puts("Error: Lyric string overlapped into Sync chunk"); free(temp); if(validate) return 11; else { (void) puts("Aborting"); exit_wrapper(11); } } if(Lyrics.verbose) printf("\tLoading text piece #%lu: \"%s\"\n",VL.numlines,temp); //Allocate link ptr1=malloc_err(sizeof(struct VL_Text_entry)); //Allocate memory for new link //Build link and insert into list ptr1->text=temp; ptr1->next=NULL; if(VL.Lyrics == NULL) //This is the first lyric piece read from the input file VL.Lyrics=ptr1; else { assert_wrapper(curtext != NULL); curtext->next=ptr1; //The end of the list points forward to this new link } curtext=ptr1; //This link is now at the end of the list VL.numlines++; //one more lyric string has been parsed }//end while(1) if(Lyrics.verbose) printf("%lu text chunk entries loaded\n",VL.numlines); //Load the Sync points if(Lyrics.verbose) (void) puts("Loading sync chunk entries"); fseek_err(inf,VL.textsize+16+8,SEEK_SET); //Seek to first sync entry (8 bytes past start of sync header) while(ReadSyncEntry(&se,inf) == 0) //Read all entries { if(se.start_char > se.end_char) { (void) puts("Error: Invalid sync point offset is specified to start after end offset"); if(validate) return 12; else { (void) puts("Aborting"); exit_wrapper(12); } } if(se.lyric_number!=0xFFFF && se.start_char!=0xFFFF && se.start_time!=0xFFFFFFFF) { //This is a valid sync entry //Allocate link ptr2=malloc_err(sizeof(struct VL_Sync_entry)); //Build link and insert into list memcpy(ptr2,&se,sizeof(struct VL_Sync_entry)); //copy structure into newly allocated link if(VL.Syncs == NULL) //This is the first sync piece read from the input file VL.Syncs=ptr2; else //The end of the list points forward to this new link { assert_wrapper(cursync != NULL); cursync->next=ptr2; } cursync=ptr2; //This link is now at the end of the list VL.numsyncs++; //one more sync entry has been parsed } } if(Lyrics.verbose) (void) puts("VL_PreLoad completed"); return 0; }
struct _VLSTRUCT_ *VL_PreWrite(void) { struct _VLSTRUCT_ *OutVL=NULL; //Create a VL structure to build the exported VL format char *lyrline=NULL; //A pointer to an array large enough to store the largest line of lyrics char *temp=NULL; unsigned long maxlength=0; //The calculated length of the longest lyric line (excluding null terminator) unsigned long charcount=0; //The running sum of the length of all lyric pieces in a line unsigned long index=0; //The current index into the lyric line, stored with each sync entry unsigned long linenum=0; //The number of the currently-processed lyric line struct Lyric_Piece *curpiece=NULL; //Conductor for lyric piece linked list struct Lyric_Line *curline=NULL; //Conductor for lyric line linked list struct VL_Text_entry *curtext=NULL; //Text entry for current lyric piece struct VL_Sync_entry *cursync=NULL; //Sync entry for current lyric piece struct VL_Sync_entry *newsync=NULL; //Used to build new sync entries to insert into list struct VL_Text_entry *newtext=NULL; //Used to build new text entries to insert into list unsigned long lastendtime=0; //The end time for the last lyric piece. The next lyric's timestamp must be at least 1 more than this static const struct _VLSTRUCT_ empty_VLSTRUCT_; //Auto-initialize all members to 0/NULL if(Lyrics.verbose) (void) puts("Building VL structure"); //Allocate the Export_VL structure OutVL=malloc_err(sizeof(struct _VLSTRUCT_)); *OutVL=empty_VLSTRUCT_; //Reliably initialize all values to 0/NULL //Initialize the Export_VL structure OutVL->numlines=Lyrics.linecount; OutVL->numsyncs=Lyrics.piececount; //Find the length of the longest line of lyrics maxlength=0; curline=Lyrics.lines; //Conductor points to first line of lyrics while(curline != NULL) //For each line of lyrics { charcount=0; //reset count curpiece=curline->pieces; //Conductor points to first lyric in the line while(curpiece != NULL) //For each lyric piece in the line { if(curpiece->lyric != NULL) charcount+=strlen(curpiece->lyric); //Add the length of the lyric curpiece=curpiece->next; //Point to next lyric piece } if(charcount>maxlength) //If this line has more characters than any other so far maxlength=charcount; //store the number of characters curline=curline->next; //Point to next lyric line } //Initialize lyrline lyrline=malloc_err((size_t)(maxlength+1+Lyrics.piececount)); //Add piececount to allow for spacing between each word //Process lyric pieces curline=Lyrics.lines; //Conductor points to first line of lyrics lastendtime=0; linenum=0; //This will be used to index into the lyric array cursync=OutVL->Syncs; //Point conductor to first link in sync chunk list while(curline != NULL) //For each line of lyrics { lyrline[0]='\0'; //Empty the string buffer index=0; //Reset index to 0 curpiece=curline->pieces; //Conductor points to first lyric in the line while(curpiece != NULL) //For each lyric piece in this line { if(curpiece->lyric != NULL) //Only process if there is actual lyric text for this lyric piece { //Allocate a new sync list link newsync=malloc_err(sizeof(struct VL_Sync_entry)); //Build sync entry newsync->lyric_number=linenum; //Initialize lyric number, which should be the lyric line number it refers to newsync->start_char=index; //Initialize sync entry start index if(curpiece->next != NULL) //If there's another lyric piece in this line newsync->end_char=index+strlen(curpiece->lyric)-1; //Find ending offset of this sync entry else newsync->end_char=0xFFFF; //The lyric reaches the end of the line of lyrics newsync->start_time=curpiece->start/10; //VL stores timestamps in 10ms increments newsync->end_time=(curpiece->start+curpiece->duration)/10; if(newsync->end_time <= newsync->start_time) //If the duration of the lyric was less than 10ms (became 0 during the division) newsync->end_time+=1; //add the minimum duration of 10ms if((lastendtime != 0) && (newsync->start_time < lastendtime)) //Ensure that this doesn't overlap with last piece newsync->start_time=lastendtime+1; lastendtime=newsync->end_time; //Store this to prevent overlapping with next piece index=newsync->end_char+1; //Set lyric character index one higher than the end of this sync entry newsync->next=NULL; //This will be the last link in the list //Insert sync entry into linked list if(OutVL->Syncs == NULL) //This is the first sync entry in the list OutVL->Syncs=newsync; else //Last link points forward to this link cursync->next=newsync; cursync=newsync; //This becomes the new last link in the list //Append lyric piece to string and append a space if necessary strcat(lyrline,curpiece->lyric); if((curpiece->next != NULL) && (curpiece->groupswithnext == 0)) { //There is another lyric piece in this line and this piece does not group with it strcat(lyrline," "); index++; //Increment the index to preserve subsequent sync piece placement } } curpiece=curpiece->next; //Point to next lyric piece }//end while(curpiece != NULL) //Make a permanent copy of the combined lyric string and store it in the lyric array temp=DuplicateString(lyrline); //Copy completed lyric line into new string linenum++; //Iterate lyric line number //Allocate new text link newtext=malloc_err(sizeof(struct VL_Text_entry)); //Build new link and insert into list newtext->text=temp; newtext->next=NULL; if(OutVL->Lyrics == NULL) //This is the first text chunk entry OutVL->Lyrics=newtext; else //Last link points forward to this link { assert_wrapper(curtext != NULL); curtext->next=newtext; } curtext=newtext; //This becomes the last link in the list curline=curline->next; //Point to next lyric line if(Lyrics.verbose>=2) printf("\tStored text chunk entry \"%s\"\n",temp); }//end while(curline != NULL) free(lyrline); //No longer needed return OutVL; //Return completed structure }