Beispiel #1
0
long rpn_create_mem(char *name, short is_string)
{
  long i_mem;
  int32_t duplicate;
  MEMORY *newMem;
  
  if (is_func(name)!=-1 || find_udf(name)!=-1) {
    fprintf(stderr, "error: attempt to create rpn memory with reserved name \"%s\"\n", name);
    return -1;
  }
  
  if (Memory==NULL || n_memories>=max_n_memories) {
    Memory = trealloc(Memory, sizeof(*Memory)*(max_n_memories+=10));
    memoryData = trealloc(memoryData, sizeof(*memoryData)*max_n_memories);
    str_memoryData = trealloc(str_memoryData, sizeof(*str_memoryData)*max_n_memories);
  }
  
  newMem = tmalloc(sizeof(*newMem));
  newMem->name = name; /* temporary copy */
  
  i_mem = binaryInsert((void**)Memory, n_memories, (void*)newMem, compare_mem, &duplicate);
  if (duplicate) {
    free(newMem);
    return Memory[i_mem]->index;
  }
  
  cp_str(&newMem->name, name);
  newMem->index = n_memories;
  newMem->is_string = is_string;
  memoryData[n_memories] = 0;
  str_memoryData[n_memories] = NULL;
  n_memories++;
  memory_added = 1;
  return Memory[i_mem]->index;
}
Beispiel #2
0
void smoothData(double *data, long rows, long smoothPoints, long smoothPasses)
{
    long lower, upper, row, pass, smoothPoints2, terms;
    double sum;
    static double *smoothedData = NULL;

    smoothedData = trealloc(smoothedData, rows*sizeof(*smoothedData));

    smoothPoints2 = smoothPoints/2;

    for (pass=0; pass<smoothPasses; pass++) {
        for (row=sum=0; row<smoothPoints2; row++) 
            sum += data[row];
        
        terms = row;
        lower = -smoothPoints2;
        upper = smoothPoints2;
        for (row=0; row<rows; row++, lower++, upper++) {
            if (upper<rows) {
                sum += data[upper];
                terms += 1;
                }
            smoothedData[row] = sum/terms;
            if (lower>=0) {
                sum -= data[lower];
                terms -= 1;
                }
            }
        
        for (row=0; row<rows; row++) 
            data[row] = smoothedData[row];
        
        }
    }
Beispiel #3
0
void bl_do_chat_del_user (struct tgl_state *TLS, tgl_peer_id_t id, int version, int user) /* {{{ */ {
  tgl_peer_t *P = tgl_peer_get (TLS, id);
  if (!P || !(P->flags & TGLPF_CREATED)) { return; }

  struct tgl_chat *C = &P->chat;
  if (C->user_list_version >= version || !C->user_list_version) { return; }
  
  int i;
  for (i = 0; i < C->user_list_size; i++) {
    if (C->user_list[i].user_id == user) {
      struct tgl_chat_user t;
      t = C->user_list[i];
      C->user_list[i] = C->user_list[C->user_list_size - 1];
      C->user_list[C->user_list_size - 1] = t;
    }
  }
  if (C->user_list[C->user_list_size - 1].user_id != user) { return; }

  assert (C->user_list[C->user_list_size - 1].user_id == user);
  C->user_list_size --;
  C->user_list = trealloc (C->user_list, 12 * C->user_list_size + 12, 12 * C->user_list_size);
  C->user_list_version = version;
  
  if (TLS->callback.chat_update) {
    TLS->callback.chat_update (TLS, C, TGL_UPDATE_MEMBERS);
  }
}
Beispiel #4
0
void bl_do_chat_add_user (struct tgl_state *TLS, tgl_peer_id_t id, int version, int user, int inviter, int date) /* {{{ */ {
  tgl_peer_t *P = tgl_peer_get (TLS, id);
  if (!P || !(P->flags & TGLPF_CREATED)) { return; }

  struct tgl_chat *C = &P->chat;
  if (C->user_list_version >= version || !C->user_list_version) { return; }

  int i;
  for (i = 0; i < C->user_list_size; i++) {
    if (C->user_list[i].user_id == user) { 
      return;
    }
  }

  C->user_list_size ++;
  C->user_list = trealloc (C->user_list, 12 * C->user_list_size - 12, 12 * C->user_list_size);
  C->user_list[C->user_list_size - 1].user_id = user;
  C->user_list[C->user_list_size - 1].inviter_id = inviter;
  C->user_list[C->user_list_size - 1].date = date;
  C->user_list_version = version;
  
  if (TLS->callback.chat_update) {
    TLS->callback.chat_update (TLS, C, TGL_UPDATE_MEMBERS);
  }
}
Beispiel #5
0
static void increase_hashtab_size(cDict *dict)
{
    Int i, newsize, oldsize = sizeof(Int) * dict->hashtab_size;

    if (dict->hashtab_size > 4096)
        dict->hashtab_size += 4096;
    else
        dict->hashtab_size = dict->hashtab_size * 2 + MALLOC_DELTA;

    newsize = sizeof(Int) * dict->hashtab_size;
    dict->links   = trealloc(dict->links,   oldsize, newsize);
    dict->hashtab = trealloc(dict->hashtab, oldsize, newsize);
    memset(dict->links,   -1, newsize);
    memset(dict->hashtab, -1, newsize);
    for (i = 0; i < dict->keys->len; i++)
        insert_key(dict, i);
}
Beispiel #6
0
BOOL io_grow(io_struct *ps, uint32 extra_space)
{
	uint32 new_size;
	char *new_data;

	ps->grow_size = MAX(ps->grow_size, ps->data_offset + extra_space);

	if(ps->data_offset + extra_space <= ps->buffer_size)
		return True;

	/*
	 * We cannot grow the buffer if we're not reading
	 * into the io_struct, or if we don't own the memory.
	 */

	if(UNMARSHALLING(ps) || !ps->is_dynamic) {
		DEBUG(0,("io_grow: Buffer overflow - unable to expand buffer by %u bytes.\n",
				(unsigned int)extra_space));
		return False;
	}
	
	/*
	 * Decide how much extra space we really need.
	 */

	extra_space -= (ps->buffer_size - ps->data_offset);
	if(ps->buffer_size == 0) {
		/*
		 * Ensure we have at least a PDU's length, or extra_space, whichever
		 * is greater.
		 */

		new_size = MAX(IO_MAX_INITIAL_SPACE, extra_space);

		if((new_data = talloc(get_ctx(ps), new_size)) == NULL) {
			DEBUG(0,("io_grow: Malloc failure for size %u.\n", (unsigned int)new_size));
			return False;
		}
		memset(new_data, '\0', new_size );
	} else {
		/*
		 * If the current buffer size is bigger than the space needed, just 
		 * double it, else add extra_space.
		 */
		new_size = MAX(ps->buffer_size*2, ps->buffer_size + extra_space);		

		if ((new_data = trealloc(get_ctx(ps), ps->data_p, new_size)) == NULL) {
			DEBUG(0,("io_grow: Realloc failure for size %u.\n",
				(unsigned int)new_size));
			return False;
		}
	}
	ps->buffer_size = new_size;
	ps->data_p = new_data;

	return True;
}
Beispiel #7
0
static void insert_jp(jp_t rom_idx)
{
  jp = trealloc(jp, jp_t, jpN);
  if (cursor < jpN)
    memmove(jp+cursor+1, jp+cursor, sizeof(jp[0]) * (jpN - cursor));

  jp[cursor]=rom_idx;
  cursor++;
  jpN++;
}
Beispiel #8
0
static void request_avail(TBuf *tbuf, int len)
{
	int newlen = tbuf->size;
	int need = VARSIZE(tbuf->data) + len;
	if (need < newlen)
		return;
	while (need > newlen)
		newlen *= 2;
	tbuf->data = trealloc(tbuf->data, newlen);
	tbuf->size = newlen;
}
Beispiel #9
0
static void
state_push_result(struct State * state)
{
  if(state->res_max_len < state->res_counter){
    state->res_max_len = state->res_max_len * 2;
    state->res = (long *) trealloc(state->res, state->res_max_len);
  }
  memcpy(state->res + state->res_counter * state->length * sizeof(long),
	 state->mat,
	 state->height * state->n_bytes * sizeof(long));
  state->res_counter++;
}
Beispiel #10
0
static void save_page()
{
  if (!symsN)
    return;

  pages=trealloc(pages, PAGE, pagesN+1);
  pages[pagesN].syms = syms;
  pages[pagesN].symsN = symsN;
  pagesN++;
  syms = NULL;
  symsN = 0;
}
Beispiel #11
0
char *escape_quotes(char *s)
{
    char *ptr, *bptr;
    static char *buffer=NULL;
    
    if (!s)
        return(s);
    ptr = s;
    buffer = trealloc(buffer, sizeof(*buffer)*(4*(strlen(s)+1)));
    bptr = buffer;

    while (*ptr) {
        if (*ptr=='"' && (ptr==s || *(ptr-1)!='\\'))
            *bptr++ = '\\';
        *bptr++ = *ptr++;
        }
    *bptr = 0;
    strcpy_ss(s, buffer);
    return(s);
    }
Beispiel #12
0
void add_ch_time()
{
  int i;
  gint64 tim = current_time();
  gint64 tim_exp = tim - MAX_KEPT_TIME;

  for(i=0;i<ch_timeN;i++)
    if (ch_time[i] > tim_exp)
      break;

  if (i) {
    int leftN = ch_timeN - i;
    memmove(ch_time, ch_time+i, sizeof(gint64) * leftN);
    ch_timeN = leftN;
  }

  if (ch_timeN_a <= ch_timeN+1) {
    ch_timeN_a =ch_timeN+1;
    ch_time = trealloc(ch_time, gint64, ch_timeN_a);
  }

  ch_time[ch_timeN++]=tim;
}
Beispiel #13
0
char *JoinStrings(char **source, long n_items, long buflen_increment) {
  char *buffer;
  char *ptr;
  long buffer_size, bufferLeft, bufferUsed;
  long i, slen;
  char *sptr;
  
  buffer_size = buflen_increment;
  buffer = (char*)malloc(sizeof(char)*buffer_size);
  buffer[0]=0;
  ptr = buffer;
  bufferLeft = buffer_size-2;
  bufferUsed = 0;
  for (i=0; i<n_items; i++) {
    sptr = source[i];
    slen = strlen(sptr);
    while ((slen+5)>bufferLeft) {
      buffer = trealloc(buffer, sizeof(char)*(buffer_size+=buflen_increment));
      bufferLeft += buflen_increment;
      ptr = buffer+bufferUsed;
    }
    if (i) {
      slen++;
      *ptr++ = ' ';
    }
    *ptr++ = '"';
    while (*sptr)
      *ptr++ = *sptr++;
    *ptr++ = '"';
    *ptr = 0;
    bufferLeft -= slen+2;
    bufferUsed += slen+2;
  }
  
  return(buffer);
}
Beispiel #14
0
int main(void) {

    char *a = talloc(3243, NULL);
    char *b = talloc(3243, a);
    char *c = talloc(3243, a);
    char *d = talloc(3243, b);
    char *e = talloc(3243, d);
    char *f = talloc(3243, d);

    char *g = talloc(3243, NULL);
    char *h = talloc(3243, g);
    char *i = talloc(3243, h);
    char *j = talloc(3243, h);
    char *k = talloc(3243, j);

    c = trealloc(c, 12345);
    d = trealloc(d, 12345);
    e = trealloc(e, 12345);

    g = trealloc(g, 12345);
    j = trealloc(j, 12345);
    j = trealloc(j, 12345);
    i = trealloc(i, 12345);

    talloc_steal(h, g); /* same as talloc_steal( h, talloc_get_parent(h) ); */

    tfree(a);
    tfree(j);
    tfree(g);

    ((int*)h)[123] = 456;
    tfree(h);

    (void)f;
    (void)k;

    return 0;
}
Beispiel #15
0
void setup_chromaticity_correction(NAMELIST_TEXT *nltext, RUN *run, LINE_LIST *beamline, CHROM_CORRECTION *chrom)
{
    VMATRIX *M;
    ELEMENT_LIST *eptr, *elast;
#include "chrom.h"
    unsigned long unstable;
    
    log_entry("setup_chromaticity_correction");

    cp_str(&sextupoles, "sf sd");

    /* process namelist input */
    set_namelist_processing_flags(STICKY_NAMELIST_DEFAULTS);
    set_print_namelist_flags(0);
    if (processNamelist(&chromaticity, nltext)==NAMELIST_ERROR)
      bombElegant(NULL, NULL);
    str_toupper(sextupoles);
    if (echoNamelists) print_namelist(stdout, &chromaticity);

    if (run->default_order<2)
        bombElegant("default order must be >= 2 for chromaticity correction", NULL);

    if (chrom->name)
        tfree(chrom->name);
    chrom->name = tmalloc(sizeof(*chrom->name)*(chrom->n_families=1));
    while ((chrom->name[chrom->n_families-1]=get_token(sextupoles)))
        chrom->name = trealloc(chrom->name, sizeof(*chrom->name)*(chrom->n_families+=1));
    if ((--chrom->n_families)<1)
        bombElegant("too few sextupoles given for chromaticity correction", NULL);
    chrom->chromx = dnux_dp;
    chrom->chromy = dnuy_dp;
    chrom->n_iterations = n_iterations;
    chrom->correction_fraction = correction_fraction;
    alter_defined_values = change_defined_values;
    chrom->strengthLimit = strength_limit;
    chrom->use_perturbed_matrix = use_perturbed_matrix;
    chrom->sextupole_tweek = sextupole_tweek;
    chrom->tolerance = tolerance;
    verbosityLevel = verbosity;
    chrom->exit_on_failure = exit_on_failure;
    
    if (!use_perturbed_matrix) {
      if (!beamline->twiss0 || !beamline->matrix) {
        double beta_x, alpha_x, eta_x, etap_x;
        double beta_y, alpha_y, eta_y, etap_y;

        fprintf(stdout, "Computing periodic Twiss parameters.\n");
        fflush(stdout);

        if (!beamline->twiss0)
          beamline->twiss0 = tmalloc(sizeof(*beamline->twiss0));

        eptr = beamline->elem_twiss = &(beamline->elem);
        elast = eptr;
        while (eptr) {
          if (eptr->type==T_RECIRC)
            beamline->elem_twiss = beamline->elem_recirc = eptr;
          elast = eptr;
          eptr = eptr->succ;
        }
        if (beamline->links) {
          /* rebaseline_element_links(beamline->links, run, beamline); */
          if (assert_element_links(beamline->links, run, beamline, STATIC_LINK+DYNAMIC_LINK)) {
            beamline->flags &= ~BEAMLINE_CONCAT_CURRENT;
            beamline->flags &= ~BEAMLINE_TWISS_CURRENT;
            beamline->flags &= ~BEAMLINE_RADINT_CURRENT;
          }
        }
        
        M = beamline->matrix = compute_periodic_twiss(&beta_x, &alpha_x, &eta_x, &etap_x, beamline->tune,
                                                      &beta_y, &alpha_y, &eta_y, &etap_y, beamline->tune+1, 
                                                      beamline->elem_twiss, NULL, run, 
                                                      &unstable, NULL, NULL);
        beamline->twiss0->betax  = beta_x;
        beamline->twiss0->alphax = alpha_x;
        beamline->twiss0->phix   = 0;
        beamline->twiss0->etax   = eta_x;
        beamline->twiss0->etapx  = etap_x;
        beamline->twiss0->betay  = beta_y;
        beamline->twiss0->alphay = alpha_y;
        beamline->twiss0->phiy   = 0;
        beamline->twiss0->etay   = eta_y;
        beamline->twiss0->etapy  = etap_y;
        
        propagate_twiss_parameters(beamline->twiss0, beamline->tune, beamline->waists,
                                   NULL, beamline->elem_twiss, run, NULL,
				   beamline->couplingFactor);
      }

      if (!(M=beamline->matrix) || !M->C || !M->R || !M->T)
        bombElegant("something wrong with transfer map for beamline (setup_chromaticity_correction)", NULL);

      computeChromCorrectionMatrix(run, beamline, chrom);
    }
    
#if USE_MPI
    if (!writePermitted)
       strength_log = NULL;
#endif
    if (strength_log) {
        strength_log = compose_filename(strength_log, run->rootname);
        fp_sl = fopen_e(strength_log, "w", 0);
        fprintf(fp_sl, "SDDS1\n&column name=Step, type=long, description=\"Simulation step\" &end\n");
        fprintf(fp_sl, "&column name=K2, type=double, units=\"1/m$a2$n\" &end\n");
        fprintf(fp_sl, "&column name=SextupoleName, type=string  &end\n");
        fprintf(fp_sl, "&data mode=ascii, no_row_counts=1 &end\n");
        fflush(fp_sl);
        }

    log_exit("setup_chromaticity_correction");
    
}
Beispiel #16
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, points;
    char *input, *output, *name, *indep_var, *var_list_format;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    char buffer[BUFSIZE], buffer0[BUFSIZE], buffer1[BUFSIZE];
    char *ptr, *ptr1, *ptr2;
    char **data_name, *package_name, *data_format;
    long data_names, data_sets_seen, data_sets_expected, realIndex, imagIndex;
    double **real_data, **imag_data, *var_list;

    argc = scanargs(&scanned, argc, argv);
    if (argc<3)
        bomb(NULL, USAGE);

    input = output = package_name = data_format = indep_var = var_list_format = ptr = NULL;
    mpl_title = mpl_topline = descrip_text = descrip_contents = NULL;
    data_names = realIndex = imagIndex = 0;
    data_name = NULL;
    real_data = imag_data = NULL;
    var_list = NULL;
    data_sets_expected = data_sets_seen = 0;
    points = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            delete_chars(scanned[i_arg].list[0], "_");
            /* process options here */
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
              case SET_DESCRIPTION:
                if (scanned[i_arg].n_items!=3)
                    SDDS_Bomb("invalid -description syntax");
                descrip_text = scanned[i_arg].list[1];
                descrip_contents = scanned[i_arg].list[2];
                break;
              case SET_MPL_LABELS:
                if (scanned[i_arg].n_items!=3)
                    SDDS_Bomb("invalid -mpllabels syntax");
                mpl_title = scanned[i_arg].list[1];
                mpl_topline = scanned[i_arg].list[2];
                break;
              default:
                SDDS_Bomb("invalid option seen");
                break;
                }
            }
        else {
            if (!input)
                input = scanned[i_arg].list[0];
            else if (!output)
                output = scanned[i_arg].list[0];
            else
                SDDS_Bomb("too many filenames");
            }
        }
    if (!input)
        SDDS_Bomb("input file not seen");
    if (!output)
        SDDS_Bomb("output file not seen");

    fpi = fopen_e(input, "r", 0);
    if (!fgets(buffer, BUFSIZE, fpi) || strncmp(buffer, CITIFILE_TAG, strlen(CITIFILE_TAG))!=0 ||
        !(ptr=strchr(buffer, ' ')))
        SDDS_Bomb("valid CITIFILE version line not found");
    *ptr++ = 0;
    ptr[strlen(ptr)-1] = 0;
    if (strncmp(ptr, CITIFILE_VERSION, strlen(CITIFILE_VERSION))!=0)
        fprintf(stderr, "warning: the CITIFILE version is %s--this program is only designed for version %s\n",
                ptr, CITIFILE_VERSION);
    
    
    if (!SDDS_InitializeOutput(&SDDS_table, SDDS_BINARY, 0, descrip_text, descrip_contents,
                               output))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if ((mpl_title &&
        SDDS_DefineParameter(&SDDS_table, "mplTitle", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_title)<0) ||
        (mpl_topline &&
         SDDS_DefineParameter(&SDDS_table, "mplTopline", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_topline)<0))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    while (fgets(buffer, BUFSIZE, fpi)) {
#if DEBUG
        fputs(buffer, stderr);
#endif
        buffer[strlen(buffer)-1] = 0;
        strcpy(buffer0, buffer);
        ptr1 = NULL;
        if ((ptr1=strchr(buffer, ' '))) 
            *ptr1++ = 0;
        switch (match_string(buffer, citi_keyword, N_CITI_KEYWORDS, EXACT_MATCH)) {
          case CITI_NA_KEYWORD:
            name = buffer+1;
            if (!*ptr1 || !(ptr2=strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains an apparently invalid #NA keyword:\n%s\n",
                        buffer0);
                exit(1);
                }
            *(ptr1-1) = '_';
            *ptr2++ = 0;
            if (SDDS_DefineParameter(&SDDS_table, name, NULL, NULL, NULL, NULL, SDDS_STRING, ptr2)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for #NA keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_NAME_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "NAME: %s\n", ptr1);
#endif
            cp_str(&package_name, ptr1);
            if (SDDS_DefineParameter(&SDDS_table, "CITIPackageName", NULL, NULL, NULL, NULL, SDDS_STRING,
                                      package_name)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for NAME keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_VAR_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "VAR: %s\n", ptr1);
#endif
            if (!(indep_var=get_token(ptr1)) || !(var_list_format=get_token(ptr1)) || !get_long(&points, ptr1) ||
                points<=0) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
            if (SDDS_DefineColumn(&SDDS_table, indep_var, NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating column for data element in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_CONSTANT_KEYWORD:
            if (!ptr1 || !(ptr2=strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "CONSTANT: %s\n", ptr1);
#endif
            *ptr2++ = 0;
            if (SDDS_DefineParameter(&SDDS_table, ptr1, NULL, NULL, NULL, NULL, SDDS_STRING, ptr2)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for CONSTANT keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_COMMENT_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "COMMENT: %s\n", ptr1);
#endif
            break;
          case CITI_DATA_KEYWORD:
            if (!ptr1 || !(ptr2 = strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "DATA: %s\n", ptr1);
#endif
            *ptr2++ = 0;
            cp_str(&data_format, ptr2);
            data_name = trealloc(data_name, sizeof(*data_name)*(data_names+1));
            cp_str(data_name+data_names, ptr1);
            alter_data_name(data_name[data_names]);
            real_data = trealloc(real_data, sizeof(*real_data)*(data_names+1));
            imag_data = trealloc(imag_data, sizeof(*imag_data)*(data_names+1));
	    sprintf(buffer, "%sReal", data_name[data_names]);
	    sprintf(buffer1, "%sImag", data_name[data_names]);
            if ((realIndex=SDDS_DefineColumn(&SDDS_table, buffer, 
                                  NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0))<0 ||
                (imagIndex=SDDS_DefineColumn(&SDDS_table, buffer1, 
                                  NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0))<0 ) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating column for data element in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            data_names++;
            break;
          case CITI_VAR_LIST_KEYWORD:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "VAR_LIST_BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("VAR_LIST_BEGIN statement seen without prior VAR statement");
            var_list = tmalloc(sizeof(*var_list)*points);
            if (!read_CITI_var_list(fpi, var_list, points))
                SDDS_Bomb("unable to read VAR_LIST");
            break;
          case CITI_BEGIN_KEYWORD:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("BEGIN statement seen without prior VAR statement");
            real_data[data_sets_seen] = tmalloc(sizeof(**real_data)*points);
            imag_data[data_sets_seen] = tmalloc(sizeof(**imag_data)*points);
            if (!read_CITI_data(fpi, real_data[data_sets_seen], imag_data[data_sets_seen], points))
                SDDS_Bomb("problem reading data section");
            data_sets_seen++;
            break;
          case CITI_SEG_LIST_BEGIN:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "SEG_LIST_BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("SEG_LIST_BEGIN statement seen without prior SEG statement");
            var_list = tmalloc(sizeof(*var_list)*points);
            if (!read_CITI_seg_list(fpi, var_list, points))
                SDDS_Bomb("unable to read SEG_LIST");
            break;
          default:
            fprintf(stderr, "unidentifiable line in file--not CITI format:\n\"%s\"\n",
                    buffer0);
            exit(1);
            break;
            }
        }
    if (!points)
        SDDS_Bomb("no data in file");
    if (data_sets_seen!=(data_sets_expected=data_names))
        SDDS_Bomb("fewer data sets than expected were actually present");
    if (!var_list) {
        fprintf(stderr, "warning: no independent variable data---supplying index\n");
        var_list = tmalloc(sizeof(*var_list)*points);
        for (i=0; i<points; i++)
            var_list[i] = i;
        }
    if (!SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, points))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, (void*)var_list, points, indep_var))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    for (i=0; i<data_sets_expected; i++) {
         if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_INDEX, (void*)real_data[i], points, 
                             realIndex) ||
             !SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_INDEX, (void*)imag_data[i], points, 
                             imagIndex)) {
             fprintf(stderr, "problem setting data for column(s) %s\n", data_name[i]);
             SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
             }
         }
    if (!SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
Beispiel #17
0
int
B2noise (int mode, int operation, GENmodel *genmodel, CKTcircuit *ckt, 
           Ndata *data, double *OnDens)
{
    B2model *firstModel = (B2model *) genmodel;
    B2model *model;
    B2instance *inst;
    char name[N_MXVLNTH];
    double tempOnoise;
    double tempInoise;
    double noizDens[B2NSRCS];
    double lnNdens[B2NSRCS];
    int i;

    /* define the names of the noise sources */

    static char *B2nNames[B2NSRCS] = {       /* Note that we have to keep the order */
	"_rd",              /* noise due to rd */        /* consistent with thestrchr definitions */
	"_rs",              /* noise due to rs */        /* in bsim1defs.h */
	"_id",              /* noise due to id */
	"_1overf",          /* flicker (1/f) noise */
	""                  /* total transistor noise */
    };

    for (model=firstModel; model != NULL; model=model->B2nextModel) {
	for (inst=model->B2instances; inst != NULL; inst=inst->B2nextInstance) {
	    if (inst->B2owner != ARCHme) continue;
        
	    switch (operation) {

	    case N_OPEN:

		/* see if we have to to produce a summary report */
		/* if so, name all the noise generators */

		if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
		    switch (mode) {

		    case N_DENS:
			for (i=0; i < B2NSRCS; i++) {
			    (void)sprintf(name,"onoise_%s%s",inst->B2name,B2nNames[i]);


data->namelist = (IFuid *)trealloc((char *)data->namelist,(data->numPlots + 1)*sizeof(IFuid));
if (!data->namelist) return(E_NOMEM);
		(*(SPfrontEnd->IFnewUid))(ckt,
			&(data->namelist[data->numPlots++]),
			(IFuid)NULL,name,UID_OTHER,(void **)NULL);
				/* we've added one more plot */


			}
			break;

		    case INT_NOIZ:
			for (i=0; i < B2NSRCS; i++) {
			    (void)sprintf(name,"onoise_total_%s%s",inst->B2name,B2nNames[i]);


data->namelist = (IFuid *)trealloc((char *)data->namelist,(data->numPlots + 1)*sizeof(IFuid));
if (!data->namelist) return(E_NOMEM);
		(*(SPfrontEnd->IFnewUid))(ckt,
			&(data->namelist[data->numPlots++]),
			(IFuid)NULL,name,UID_OTHER,(void **)NULL);
				/* we've added one more plot */


			    (void)sprintf(name,"inoise_total_%s%s",inst->B2name,B2nNames[i]);


data->namelist = (IFuid *)trealloc((char *)data->namelist,(data->numPlots + 1)*sizeof(IFuid));
if (!data->namelist) return(E_NOMEM);
		(*(SPfrontEnd->IFnewUid))(ckt,
			&(data->namelist[data->numPlots++]),
			(IFuid)NULL,name,UID_OTHER,(void **)NULL);
				/* we've added one more plot */



			}
			break;
		    }
		}
		break;

	    case N_CALC:
		switch (mode) {

		case N_DENS:
		    NevalSrc(&noizDens[B2RDNOIZ],&lnNdens[B2RDNOIZ],
				 ckt,THERMNOISE,inst->B2dNodePrime,inst->B2dNode,
				 inst->B2drainConductance * inst->B2m);

		    NevalSrc(&noizDens[B2RSNOIZ],&lnNdens[B2RSNOIZ],
				 ckt,THERMNOISE,inst->B2sNodePrime,inst->B2sNode,
				 inst->B2sourceConductance * inst->B2m);

		    NevalSrc(&noizDens[B2IDNOIZ],&lnNdens[B2IDNOIZ],
				 ckt,THERMNOISE,inst->B2dNodePrime,inst->B2sNodePrime,
                                 (2.0/3.0 * fabs(inst->B2gm * inst->B2m)));

		    NevalSrc(&noizDens[B2FLNOIZ],(double*)NULL,ckt,
				 N_GAIN,inst->B2dNodePrime, inst->B2sNodePrime,
				 (double)0.0);
		    noizDens[B2FLNOIZ] *= model->B2fNcoef * inst->B2m *
				 exp(model->B2fNexp *
				 log(MAX(fabs(inst->B2cd),N_MINLOG))) /
				 (data->freq *
				 (inst->B2w - model->B2deltaW * 1e-6) *
				 (inst->B2l - model->B2deltaL * 1e-6) *
				 model->B2Cox * model->B2Cox);
		    lnNdens[B2FLNOIZ] = 
				 log(MAX(noizDens[B2FLNOIZ],N_MINLOG));

		    noizDens[B2TOTNOIZ] = noizDens[B2RDNOIZ] +
						     noizDens[B2RSNOIZ] +
						     noizDens[B2IDNOIZ] +
						     noizDens[B2FLNOIZ];
		    lnNdens[B2TOTNOIZ] = 
				 log(MAX(noizDens[B2TOTNOIZ], N_MINLOG));

		    *OnDens += noizDens[B2TOTNOIZ];

		    if (data->delFreq == 0.0) { 

			/* if we haven't done any previous integration, we need to */
			/* initialize our "history" variables                      */

			for (i=0; i < B2NSRCS; i++) {
			    inst->B2nVar[LNLSTDENS][i] = lnNdens[i];
			}

			/* clear out our integration variables if it's the first pass */

			if (data->freq == ((NOISEAN*)ckt->CKTcurJob)->NstartFreq) {
			    for (i=0; i < B2NSRCS; i++) {
				inst->B2nVar[OUTNOIZ][i] = 0.0;
				inst->B2nVar[INNOIZ][i] = 0.0;
			    }
			}
		    } else {   /* data->delFreq != 0.0 (we have to integrate) */
			for (i=0; i < B2NSRCS; i++) {
			    if (i != B2TOTNOIZ) {
				tempOnoise = Nintegrate(noizDens[i], lnNdens[i],
				      inst->B2nVar[LNLSTDENS][i], data);
				tempInoise = Nintegrate(noizDens[i] * data->GainSqInv ,
				      lnNdens[i] + data->lnGainInv,
				      inst->B2nVar[LNLSTDENS][i] + data->lnGainInv,
				      data);
				inst->B2nVar[LNLSTDENS][i] = lnNdens[i];
				data->outNoiz += tempOnoise;
				data->inNoise += tempInoise;
				if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
				    inst->B2nVar[OUTNOIZ][i] += tempOnoise;
				    inst->B2nVar[OUTNOIZ][B2TOTNOIZ] += tempOnoise;
				    inst->B2nVar[INNOIZ][i] += tempInoise;
				    inst->B2nVar[INNOIZ][B2TOTNOIZ] += tempInoise;
                                }
			    }
			}
		    }
		    if (data->prtSummary) {
			for (i=0; i < B2NSRCS; i++) {     /* print a summary report */
			    data->outpVector[data->outNumber++] = noizDens[i];
			}
		    }
		    break;

		case INT_NOIZ:        /* already calculated, just output */
		    if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
			for (i=0; i < B2NSRCS; i++) {
			    data->outpVector[data->outNumber++] = inst->B2nVar[OUTNOIZ][i];
			    data->outpVector[data->outNumber++] = inst->B2nVar[INNOIZ][i];
			}
		    }    /* if */
		    break;
		}    /* switch (mode) */
		break;

	    case N_CLOSE:
		return (OK);         /* do nothing, the main calling routine will close */
		break;               /* the plots */
	    }    /* switch (operation) */
	}    /* for inst */
    }    /* for model */

return(OK);
}
Beispiel #18
0
int HSM2noise (
     int mode, int operation,
     GENmodel *inModel,
     CKTcircuit *ckt,
     Ndata *data,
     double *OnDens)
{
  HSM2model *model = (HSM2model *)inModel;
  HSM2instance *here;
  char name[N_MXVLNTH];
  double tempOnoise;
  double tempInoise;
  double noizDens[HSM2NSRCS];
  double lnNdens[HSM2NSRCS];
  int i;
  double G = 0.0 ;
  double TTEMP = 0.0 ;
 
  /* for induced gate noise calculation: */
  double omega = ckt->CKTomega;
  double sid, ci, sigrat, Qdrat;
  double realXds, imagXds, realXgs, imagXgs ;

  /* define the names of the noise sources */
  static char * HSM2nNames[HSM2NSRCS] = {
    /* Note that we have to keep the order
       consistent with the index definitions 
       in hsm2defs.h */
    ".rd",              /* noise due to rd */
    ".rs",              /* noise due to rs */
    ".id",              /* noise due to id */
    ".1ovf",            /* flicker (1/f) noise */
    ".igs",             /* shot noise due to Igs */
    ".igd",             /* shot noise due to Igd */
    ".igb",             /* shot noise due to Igb */
    ".ign",             /* induced gate noise component at the drain node */
    ""                  /* total transistor noise */
  };
  
  for ( ;model != NULL; model = model->HSM2nextModel ) {
    for ( here = model->HSM2instances; here != NULL;
	  here = here->HSM2nextInstance ) {
      switch (operation) {
      case N_OPEN:
	/* see if we have to to produce a summary report */
	/* if so, name all the noise generators */
	  
	if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
	  switch (mode) {
	  case N_DENS:
	    for ( i = 0; i < HSM2NSRCS; i++ ) { 
	      (void) sprintf(name, "onoise.%s%s", 
			     (char *)here->HSM2name, HSM2nNames[i]);
	      data->namelist = 
		(IFuid *) trealloc((char *) data->namelist,
				   ((long unsigned int)data->numPlots + 1) * sizeof(IFuid));
	      if (!data->namelist)
		return(E_NOMEM);
	      (*(SPfrontEnd->IFnewUid)) 
		(ckt, &(data->namelist[data->numPlots++]),
		 (IFuid) NULL, name, UID_OTHER, NULL);
	    }
	    break;
	  case INT_NOIZ:
	    for ( i = 0; i < HSM2NSRCS; i++ ) {
	      (void) sprintf(name, "onoise_total.%s%s", 
			     (char *)here->HSM2name, HSM2nNames[i]);
	      data->namelist = 
		(IFuid *) trealloc((char *) data->namelist,
				   ((long unsigned int)data->numPlots + 1) * sizeof(IFuid));
	      if (!data->namelist)
		return(E_NOMEM);
	      (*(SPfrontEnd->IFnewUid)) 
		(ckt, &(data->namelist[data->numPlots++]),
		 (IFuid) NULL, name, UID_OTHER, NULL);
	      
	      (void) sprintf(name, "inoise_total.%s%s", 
			     (char *)here->HSM2name, HSM2nNames[i]);
	      data->namelist = 
		(IFuid *) trealloc((char *) data->namelist,
				   ((long unsigned int)data->numPlots + 1) * sizeof(IFuid));
	      if (!data->namelist)
		return(E_NOMEM);
	      (*(SPfrontEnd->IFnewUid)) 
		(ckt, &(data->namelist[data->numPlots++]),
		 (IFuid) NULL, name, UID_OTHER, NULL);
	    }
	    break;
	  }
	}
	break;
      case N_CALC:
	switch (mode) {
	case N_DENS:

	  /* temperature */
	  TTEMP = ckt->CKTtemp ;
	  if ( here->HSM2_temp_Given ) TTEMP = here->HSM2_ktemp ;
	  if ( here->HSM2_dtemp_Given ) {
	    TTEMP = TTEMP + here->HSM2_dtemp ;
	  }

         /* rs/rd thermal noise */
         if ( model->HSM2_corsrd < 0 ) {
           NevalSrc(&noizDens[HSM2RDNOIZ], (double*) NULL,
                    ckt, N_GAIN,
                    here->HSM2dNodePrime, here->HSM2dNode,
                    (double) 0.0);
           noizDens[HSM2RDNOIZ] *= 4 * CONSTboltz * TTEMP * here->HSM2drainConductance ;
	   lnNdens[HSM2RDNOIZ] = log( MAX(noizDens[HSM2RDNOIZ],N_MINLOG) ) ;

           NevalSrc(&noizDens[HSM2RSNOIZ], (double*) NULL,
                    ckt, N_GAIN,
                    here->HSM2sNodePrime, here->HSM2sNode,
                    (double) 0.0);
           noizDens[HSM2RSNOIZ] *= 4 * CONSTboltz * TTEMP * here->HSM2sourceConductance ;
	   lnNdens[HSM2RSNOIZ] = log( MAX(noizDens[HSM2RSNOIZ],N_MINLOG) ) ;

           /*
           NevalSrc(&noizDens[HSM2RDNOIZ], &lnNdens[HSM2RDNOIZ],
		     ckt, THERMNOISE,
		     here->HSM2dNodePrime, here->HSM2dNode,
		     here->HSM2_weff / model->HSM2_rsh);
	    
	    NevalSrc(&noizDens[HSM2RSNOIZ], &lnNdens[HSM2RSNOIZ], 
		     ckt, THERMNOISE,
		     here->HSM2sNodePrime, here->HSM2sNode,
		     here->HSM2_weff / model->HSM2_rsh);
	    */
	  } else {
	    noizDens[HSM2RDNOIZ] = 0e0 ;
	    lnNdens[HSM2RDNOIZ] = N_MINLOG ;
	    noizDens[HSM2RSNOIZ] = 0e0 ;
	    lnNdens[HSM2RSNOIZ] = N_MINLOG ;
	  }

	  /* channel thermal noise */
	  switch( model->HSM2_noise ) {
	  case 1:
           /* HiSIM2 model */
         if ( model->HSM2_corsrd <= 0 || here->HSM2internalGd <= 0.0 ) {
           G = here->HSM2_noithrml ;
         } else {
           if ( here->HSM2_noithrml * here->HSM2internalGd * here->HSM2internalGs > 0.0 ) {
              G = here->HSM2_noithrml * here->HSM2internalGd * here->HSM2internalGs
              / ( here->HSM2_noithrml * here->HSM2internalGd
                + here->HSM2internalGd * here->HSM2internalGs
                + here->HSM2_noithrml * here->HSM2internalGs );
           } else {
              G = 0.0;
           }
         }
           NevalSrc(&noizDens[HSM2IDNOIZ], (double*) NULL,
                    ckt, N_GAIN,
                    here->HSM2dNodePrime, here->HSM2sNodePrime,
                    (double) 0.0);
           noizDens[HSM2IDNOIZ] *= 4 * CONSTboltz * TTEMP * G ;
           lnNdens[HSM2IDNOIZ] = log( MAX(noizDens[HSM2IDNOIZ],N_MINLOG) );
           break;
         }

         /* flicker noise */
         NevalSrc(&noizDens[HSM2FLNOIZ], (double*) NULL,
                  ckt, N_GAIN,
                  here->HSM2dNodePrime, here->HSM2sNodePrime,
                  (double) 0.0);
         switch ( model->HSM2_noise ) {
         case 1:
           /* HiSIM model */
           noizDens[HSM2FLNOIZ] *= here->HSM2_noiflick / pow(data->freq, model->HSM2_falph) ;
           break;
         }
         lnNdens[HSM2FLNOIZ] = log(MAX(noizDens[HSM2FLNOIZ], N_MINLOG));

         /* shot noise */
	 NevalSrc(&noizDens[HSM2IGSNOIZ],
		  &lnNdens[HSM2IGSNOIZ], ckt, SHOTNOISE,
		  here->HSM2gNodePrime, here->HSM2sNodePrime,
		  here->HSM2_igs);
	 NevalSrc(&noizDens[HSM2IGDNOIZ],
		  &lnNdens[HSM2IGDNOIZ], ckt, SHOTNOISE,
		  here->HSM2gNodePrime, here->HSM2dNodePrime,
		  here->HSM2_igd);
	 NevalSrc(&noizDens[HSM2IGBNOIZ],
		  &lnNdens[HSM2IGBNOIZ], ckt, SHOTNOISE,
		  here->HSM2gNodePrime, here->HSM2bNodePrime,
		  here->HSM2_igb);

	  /* induced gate noise */
	  switch ( model->HSM2_noise ) {
	  case 1:
	    /* HiSIM model */
            sid = 4.0 * CONSTboltz * TTEMP * here->HSM2_noithrml ;
            ci  = here->HSM2_noicross ;
            sigrat = (sid > 0.0 && here->HSM2_noiigate > 0.0) ? sqrt(here->HSM2_noiigate/sid) : 0.0 ;
            Qdrat  = here->HSM2_Qdrat ;

            realXds = *(ckt->CKTrhs +here->HSM2dNodePrime) - *(ckt->CKTrhs +here->HSM2sNodePrime);
            imagXds = *(ckt->CKTirhs+here->HSM2dNodePrime) - *(ckt->CKTirhs+here->HSM2sNodePrime);
            realXgs = *(ckt->CKTrhs +here->HSM2gNodePrime) - *(ckt->CKTrhs +here->HSM2sNodePrime);
            imagXgs = *(ckt->CKTirhs+here->HSM2gNodePrime) - *(ckt->CKTirhs+here->HSM2sNodePrime);

            noizDens[HSM2IGNOIZ] = 2.0 * omega * ci * sigrat * sid * ( realXgs*imagXds - realXds*imagXgs ) 
                                  + omega*omega * sigrat*sigrat * sid * ( (realXgs-Qdrat*realXds) * (realXgs-Qdrat*realXds)
                                                                         +(imagXgs-Qdrat*imagXds) * (imagXgs-Qdrat*imagXds) ) ;
	    lnNdens[HSM2IGNOIZ] = log(MAX(noizDens[HSM2IGNOIZ], N_MINLOG));
	    break;
	  }

	  /* total */
	  noizDens[HSM2TOTNOIZ] = noizDens[HSM2RDNOIZ] + noizDens[HSM2RSNOIZ]
	    + noizDens[HSM2IDNOIZ] + noizDens[HSM2FLNOIZ]
	    + noizDens[HSM2IGSNOIZ] + noizDens[HSM2IGDNOIZ] + noizDens[HSM2IGBNOIZ]
	    + noizDens[HSM2IGNOIZ];
	  lnNdens[HSM2TOTNOIZ] = log(MAX(noizDens[HSM2TOTNOIZ], N_MINLOG));
/*       printf("f %e Sid %.16e Srd %.16e Srs %.16e Sflick %.16e Stherm %.16e Sign %.16e\n", */
/*              data->freq,noizDens[HSM2TOTNOIZ],noizDens[HSM2RDNOIZ],noizDens[HSM2RSNOIZ],noizDens[HSM2FLNOIZ],noizDens[HSM2IDNOIZ],noizDens[HSM2IGNOIZ]); */
	  
	  *OnDens += noizDens[HSM2TOTNOIZ];
	  
	  if ( data->delFreq == 0.0 ) {
	    /* if we haven't done any previous 
	       integration, we need to initialize our
	       "history" variables.
	    */
	    
	    for ( i = 0; i < HSM2NSRCS; i++ ) 
	      here->HSM2nVar[LNLSTDENS][i] = lnNdens[i];
	    
	    /* clear out our integration variables
	       if it's the first pass
	    */
	    if (data->freq == ((NOISEAN*) ckt->CKTcurJob)->NstartFreq) {
	      for (i = 0; i < HSM2NSRCS; i++) {
		here->HSM2nVar[OUTNOIZ][i] = 0.0;
		here->HSM2nVar[INNOIZ][i] = 0.0;
	      }
	    }
	  }
	  else {
	    /* data->delFreq != 0.0,
	       we have to integrate.
	    */
	    for ( i = 0; i < HSM2NSRCS; i++ ) {
	      if ( i != HSM2TOTNOIZ ) {
		tempOnoise = 
		  Nintegrate(noizDens[i], lnNdens[i],
			     here->HSM2nVar[LNLSTDENS][i], data);
		tempInoise = 
		  Nintegrate(noizDens[i] * data->GainSqInv, 
			     lnNdens[i] + data->lnGainInv,
			     here->HSM2nVar[LNLSTDENS][i] + data->lnGainInv,
			     data);
		here->HSM2nVar[LNLSTDENS][i] = lnNdens[i];
		data->outNoiz += tempOnoise;
		data->inNoise += tempInoise;
		if ( ((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0 ) {
		  here->HSM2nVar[OUTNOIZ][i] += tempOnoise;
		  here->HSM2nVar[OUTNOIZ][HSM2TOTNOIZ] += tempOnoise;
		  here->HSM2nVar[INNOIZ][i] += tempInoise;
		  here->HSM2nVar[INNOIZ][HSM2TOTNOIZ] += tempInoise;
		}
	      }
	    }
	  }
	  if ( data->prtSummary ) {
	    for (i = 0; i < HSM2NSRCS; i++) {
	      /* print a summary report */
	      data->outpVector[data->outNumber++] = noizDens[i];
	    }
	  }
	  break;
	case INT_NOIZ:
	  /* already calculated, just output */
	  if ( ((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0 ) {
	    for ( i = 0; i < HSM2NSRCS; i++ ) {
	      data->outpVector[data->outNumber++] = here->HSM2nVar[OUTNOIZ][i];
	      data->outpVector[data->outNumber++] = here->HSM2nVar[INNOIZ][i];
	    }
	  }
	  break;
	}
	break;
      case N_CLOSE:
	/* do nothing, the main calling routine will close */
	return (OK);
	break;   /* the plots */
      }       /* switch (operation) */
    }    /* for here */
  }    /* for model */
  
  return(OK);
}
Beispiel #19
0
static gboolean read_syms()
{
  FILE *fp;
  static char symbol_table[] = "symbol-table";
  static time_t file_modify_time;

  if ((fp=watch_fopen(symbol_table, &file_modify_time))==NULL)
    return FALSE;

  skip_utf8_sigature(fp);

  int pg;
  for(pg=0; pg < pagesN; pg++) {
    syms = pages[pg].syms;
    symsN = pages[pg].symsN;

    int i;
    for(i=0; i < symsN; i++) {
      int j;
      for(j=0; j < syms[i].symN; j++)
        if (syms[i].sym[j])
          free(syms[i].sym[j]);
    }
    free(syms);
  }
  pagesN = 0; pages = NULL;
  syms = NULL; symsN = 0;


  while (!feof(fp)) {
    char tt[1024];

    bzero(tt, sizeof(tt));
    myfgets(tt, sizeof(tt), fp);
//    dbg("%d] %s\n",strlen(tt), tt);
    int len=strlen(tt);

#if 0
    if (!len)
      continue;

    if (tt[len-1]=='\n') {
      tt[len-1]=0;
    }
#endif

    if (tt[0]==0)
      save_page();

    if (tt[0]=='#')
      continue;

    char *p=tt;

    syms=trealloc(syms, SYM_ROW, symsN+1);
    SYM_ROW *psym = &syms[symsN++];
    bzero(psym, sizeof(SYM_ROW));


    while (*p) {
      char *n = p;

      while (*n && *n!='\t')
        n++;

      *n = 0;

      psym->sym=trealloc(psym->sym, char *, psym->symN+1);
      psym->sym[psym->symN++] = strdup(p);

      p = n + 1;
    }

    if (!psym->symN) {
      free(syms);
      syms=NULL;
      symsN=0;
    }
  }

  if (symsN)
    save_page();

  fclose(fp);

  idx = 0;
  syms = pages[idx].syms;
  symsN = pages[idx].symsN;

  return TRUE;
}
Beispiel #20
0
long scan_namelist(NAMELIST_TEXT *nl, char *line)
{
    register char *ptr, *ptr_e;
    char *ptr_p, *ptr_to_free ;
    long n_entities, i, j, length_values, length;
    char *values;
    static char *buffer = NULL;
    static long bufsize = 0;
#define BIGBUFSIZE 16384
#define INDEX_LIMIT 16380
#if !defined(vxWorks)
    long k, m, n, len, insideCommand;
    char psBuffer[16384], tempptr[16384], command[16384];
    FILE *fID;
#ifdef CONDOR_COMPILE
    char tmpName[1024];
#endif
#endif

    values = NULL;
    length_values = 0;
    if (!buffer)
        buffer = tmalloc(sizeof(*buffer)*(bufsize = 128));

    nl->n_entities = 0;
    nl->group_name = NULL;
    nl->entity   = NULL;
    nl->value    = NULL;
    nl->n_values = nl->n_subscripts = NULL;
    nl->subscript = nl->repeat = NULL;

#ifdef DEBUG
    printf("scan_namelist: line = <%s>\n", line);
#endif
    cp_str(&ptr_to_free, line);
    ptr = ptr_to_free;

    /* Find group name--it's a token starting with '$' or '&'. */
#if DOLLARSIGN_TOO
    if (!(ptr_p=next_unquoted_char(ptr, '$', '"')) &&
        !(ptr_p=next_unquoted_char(ptr, '&', '"')) ) {
        free(ptr_to_free);
        fprintf(stderr, "error: namelist scanning problem---missing group name:\n%s\n", ptr);
        return(-1);
        }
#else
    if (!(ptr_p=next_unquoted_char(ptr, '&', '"'))) {
        free(ptr_to_free);
        fprintf(stderr, "error: namelist scanning problem---missing group name:\n%s\n", ptr);
        return(-1);
        }
#endif
    ptr_p++;
    if ((nl->group_name=get_token(ptr_p))==NULL) {
        free(ptr_to_free);
        fprintf(stderr, "error: namelist scanning problem---missing group name:\n%s\n", ptr);
        return(-1);
        }
#ifdef DEBUG
    printf("scan_namelist: nl->group_name = <%s>\n", nl->group_name);
#endif

    /* Count entities--each entity is associated with an equals sign,
     * since these are all assignments. */
#if DOLLARSIGN_TOO
    n_entities = count_occurences(ptr_p, '=', "$&");
#else
    n_entities = count_occurences(ptr_p, '=', "&");
#endif
    if (n_entities==0) {
        free(ptr_to_free);
        return(nl->n_entities=0);
        }
#ifdef DEBUG
    printf("scan_namelist: n_entities = %ld\n", n_entities);
#endif

    /* allocate memory for parallel arrays representing the namelist:
     *   nl->entity is an array of entity names
     *   nl->value is an array of arrays of values assigned
     *   nl->repeat is an array of arrays of repeat factors applied to values
     *   nl->n_values is an array of numbers of values
     *   nl->n_subscripts is an array of numbers of subscripts
     *   nl->subscript is an array of arrays of subscripts
     */
    nl->entity   = tmalloc(sizeof(*(nl->entity  ))*n_entities);
    nl->value    = tmalloc(sizeof(*(nl->value   ))*n_entities);
    nl->repeat   = tmalloc(sizeof(*(nl->repeat  ))*n_entities);
    nl->n_values = tmalloc(sizeof(*(nl->n_values))*n_entities);
    nl->n_subscripts = tmalloc(sizeof(*(nl->n_subscripts))*n_entities);
    nl->subscript    = tmalloc(sizeof(*(nl->subscript))*n_entities);

#ifdef DEBUG
    printf("scan_namelist: allocation successful\n");
#endif

    /* scan individual items--look for entity names and successively extract
     * strings containing assignments for single entities.  For each string,
     * extract a list of values and repeat factors.
     */
    for (i=0; i<n_entities; i++) {
        /* Find next entity name, which terminates with '='.  ptr_p
         * points to the section of the string being parsed.  I.e., everything
         * before ptr_p has been parsed already. */
        if (!(ptr_e = next_unquoted_char(ptr_p, '=', '"'))) {
            fprintf(stderr, "scan_namelist: no '=' in string >%s<\n", ptr_p);
            exit(1);
            }

        ptr = ptr_e;
        while (isspace(*(ptr-1)))
            ptr--;
        *ptr = 0;                /* end entity name string at '=' or space */

        while (isspace(*ptr_p))    /* advance to start of name      */
            ptr_p++;
        cp_str(nl->entity+i, ptr_p);   /* copy the entity name */
        nl->n_subscripts[i] = extract_subscripts(nl->entity[i], nl->subscript+i);

#ifdef DEBUG
        printf("scan_namelist: nl->entity[%ld] = <%s>\n", i, nl->entity[i]);
        printf("remainder: <%s>\n", ptr_e+1);
#endif

        /* Set ptr to point to start of values list, which follows the '='
         * that was just found and deleted. */
        ptr = ptr_e + 1;

        /* Find next entity name, if there is one, and insert a 0 before it
         * to mark end of current values list. */
        if ((ptr_e = next_unquoted_char(ptr, '=', '"'))) {
            /* set ptr_e to point to end of values list for current entity,
             * which is at the comma or space preceeding the next entity name
             */
#ifdef DEBUG
            printf("scan_namelist: next list is <%s>\n", ptr_e);
#endif
            /* Skip whitespace and get to the entity name. */
            ptr_e--;
            while (isspace(*ptr_e) && ptr_e!=ptr)
                ptr_e--;
            /* Skip over the entity name. */
            while (*ptr_e==')' || *ptr_e=='}') {
                ptr_e--;
                while (*ptr_e!='(' && *ptr_e!='{' && ptr_e!=ptr)
                    ptr_e--;
                }
            while (!(isspace(*ptr_e) || *ptr_e==',') && ptr_e!=ptr)
                ptr_e--;
            ptr_p = ptr_e+1;      /* Save start of next entity. */
            /* Skip trailing whitespace and commas in the values list. */
            while ((isspace(*ptr_e) || *ptr_e==',') && ptr_e!=ptr)
                ptr_e--;
            /* If there's nothing left, there was no value given. */
            if (++ptr_e==ptr)
                bomb("missing value in namelist", NULL);
            /* Mark end of values with a NUL, and set ptr_p to the point
             * where processing begins for the next entity. */
            *ptr_e = 0;
            }
        else {
            /* There is no following entity, so there should be a '$end'
             * '&end', or just '$' or '&'.   */
            /* set ptr_e to $end of string, check for error */
#ifdef DEBUG
            printf("scan_namelist: last item is <%s>\n", ptr);
#endif
#if DOLLARSIGN_TOO
            if (!(ptr_e=next_unquoted_char(ptr, '&', '"')) && !(ptr_e=next_unquoted_char(ptr, '$', '"')) ) {
                fprintf(stderr, "error: namelist improperly terminated\n");
                return(-1);
                }
#else
            if (!(ptr_e=next_unquoted_char(ptr, '&', '"'))) {
                fprintf(stderr, "error: namelist improperly terminated\n");
                return(-1);
                }
#endif
            *ptr_e = 0;           /* Delete the symbol. */

            /* If the number of entities doesn't match what was counted before,
             * something is really goofy. */
            if (i!=n_entities-1) {
#ifdef DEBUG
                printf("scan_namelist: fatal error: n_entites=%ld, i=%ld\n", n_entities,
                      i);
#endif
                return(-1);
                }

            /* Scan backwards to the first token. Make sure there are some
             * values listed. */
            ptr_e--;
            while ((isspace(*ptr_e) || *ptr_e==',') && ptr_e!=ptr)
                ptr_e--;
            if (++ptr_e==ptr) {
#ifdef DEBUG
            printf("scan_namelist: fatal error: ptr_e = ptr\n");
            printf("scan_namelist: ptr = <%s>\n", ptr);
#endif
                fprintf(stderr, "error: no values listed for namelist field %s\n",
                        nl->entity[i]);
                return(-1);     /* No values listed. */
                }
            *ptr_e = 0;
            ptr_p = ptr_e;
            }
        /* ptr now points to the beginning of the values list, which is
         * NUL terminated.  ptr_p points to the beginning of the rest of
         * what remains to be parsed. */
#ifdef DEBUG
        printf("scan_namelist: values list = <%s>\n", ptr);
        printf("scan_namelist: remainder = <%s>\n", ptr_p);
#endif
#if !defined(vxWorks)
	length = strlen(ptr);
	if (length == 0) {
            fprintf(stderr, "error: missing values for namelist field %s\n",
                    nl->entity[i]);
            return -1;
	}
	n = 0;
	j = 0;
	k = 0;
	insideCommand = 0;
	while (n<length) {
	  if (j>INDEX_LIMIT) {
	      fprintf(stderr, "error: values for namelist field %s is too long\n",
		      nl->entity[i]);
	      return -1;
	  }
	  if (ptr[n]=='\\') {
            if (ptr[n+1]!='}' && ptr[n+1]!='{')
              tempptr[j++] = ptr[n++];
            else
              n++;
	    if (n<length) {
	      if (insideCommand) {
		command[k] = ptr[n];
		k++;
		n++;		
	      } else {
		tempptr[j] = ptr[n];
		j++;
		n++;
	      }
	    }
	  } else if (ptr[n]=='{') {
	    if (insideCommand) {
	      fprintf(stderr, "error: values for namelist field %s has invalid command brackets\n",
		      nl->entity[i]);
	      return -1;
	    }
	    insideCommand = 1;
	    k = 0;
	    n++;
	  } else if (ptr[n]=='}') {
	    if (!insideCommand) {
	      fprintf(stderr, "error: values for namelist field %s has invalid command brackets\n",
		      nl->entity[i]);
	      return -1;
	    }
	    insideCommand = 0;
	    command[k] = 0;
	    n++;
#ifndef CONDOR_COMPILE
	    if ((fID = popen(command, "r")) == NULL) {
	      fprintf(stderr, "error: invalid command for namelist field %s\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
	    }
	    if (feof(fID)) {
	      fprintf(stderr, "error: command for namelist field %s returns EOF\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
	    }
	    if (fgets(psBuffer, 128, fID) == NULL) {
	      fprintf(stderr, "error: command for namelist field %s returns NULL\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
	    }
            pclose(fID);
#else
            tmpnam(tmpName);
            sprintf(psBuffer, "%s > %s", command, tmpName);
            system(psBuffer);
            if (!(fID = fopen(tmpName, "r"))) {
	      fprintf(stderr, "error: command for namelist field %s failed\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
            }
            if (fgets(psBuffer, 128, fID) == NULL) {
	      fprintf(stderr, "error: command for namelist field %s returns NULL\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
            }
            fclose(fID);
            remove(tmpName);
 #endif
	    len = strlen(psBuffer)-1;
	    if ((len > 0) && (psBuffer[len] == '\n')) {
	      psBuffer[len] = 0;
	    }
	    m = 0;
	    len = strlen(psBuffer);
	    if (j+len>INDEX_LIMIT) {
	      fprintf(stderr, "error: values for namelist field %s is too long\n",
		      nl->entity[i]);
	      return -1;
	    }
	    while (m < len) {
	      tempptr[j] = psBuffer[m];
	      j++;
	      m++;
	    } 
	  } else {
	    if (insideCommand) {
	      command[k] = ptr[n];
	      n++;
	      k++;
	    } else {
	      tempptr[j] = ptr[n];
	      n++;
	      j++;
	    }
	  }
	}
	tempptr[j] = 0;
	
	ptr = tempptr;
#endif
        /* Process string of values.  Values must be separated by commas. */
        length = strlen(ptr)+1;
        if (length==1) {
            fprintf(stderr, "error: missing values for namelist field %s\n",
                    nl->entity[i]);
            return -1;
            }
        if (values==NULL) {
            values = tmalloc(length*sizeof(*values));
            length_values = length;
            }
        else if (length>length_values) {
            tfree(values);
            values = tmalloc(length*sizeof(*values));
            }
        strcpy_ss(values, ptr);
        nl->n_values[i] = count_occurences(values, ',', "")+1;
        nl->value[i]    = tmalloc(sizeof(*(nl->value[i]))*nl->n_values[i]);
        nl->repeat[i]   = tmalloc(sizeof(*(nl->repeat[i]))*nl->n_values[i]);
#ifdef DEBUG
        printf("scan_namelist: allocation successful--nl->n_values[%ld]=%ld\n",
            i, nl->n_values[i]);
#endif

        for (j=0; j<nl->n_values[i]; j++) {
#ifdef DEBUG
          printf("scan_namelist: scanning tokens from >%s<\n",
                 values);
#endif
            ptr = nl->value[i][j] =
                    get_token_tq(values, ", ", ", ", "\"'", "\"'");
#ifdef DEBUG
            printf("scan_namelist: looping over values--j=%ld\n", j);
            printf("scan_namelist: token is <%s>\n", ptr);
#endif 
            if (!ptr) {
                fprintf(stderr, "error: missing values for namelist field %s\n",
                        nl->entity[i]);
                return -1;
                }
            if (!isdigit(*ptr)) {
                nl->repeat[i][j] = 1;
                un_quote(ptr);
                }
            else {
                ptr_e = ptr;
                while (isdigit(*ptr))
                    ptr++;
                if (*ptr!='*') {
                    nl->repeat[i][j] = 1;
                    continue;
                    }
                *ptr = 0;
                if ((length=strlen(ptr_e))-1>bufsize)
                    buffer = trealloc(buffer, sizeof(*buffer)*(bufsize=length+1024));
                strcpy_ss(buffer, ptr_e);
                strcpy_ss(nl->value[i][j], ptr+1);
                un_quote(nl->value[i][j]);
#ifdef DEBUG
                printf("doing repeat scan: ptr_e = <%s>  ptr+1 = <%s>\nbuffer = <%s>\n",
                    ptr_e, ptr+1, buffer);
#endif
                if (sscanf(buffer, "%ld", nl->repeat[i]+j)!=1)
                    bomb("bad repeat specifier in namelist", NULL);
                }
#ifdef DEBUG
            printf("scan_namelist: nl->value[%ld][%ld] = %ld*<%s>\n",
                i, j, nl->repeat[i][j], nl->value[i][j]);
            printf("remainder: <%s>\n\n", values);
#endif
            }
        }

    free(values);
    free(ptr_to_free);
#ifdef DEBUG
    nl->n_entities = n_entities;
    show_namelist(stdout, nl);
#endif
    return(nl->n_entities=n_entities);
    }
Beispiel #21
0
int
RESnoise (int mode, int operation, GENmodel *genmodel, CKTcircuit *ckt, 
          Ndata *data, double *OnDens)
{
    RESmodel *firstModel = (RESmodel *) genmodel;
    RESmodel *model;
    RESinstance *inst;
    char name[N_MXVLNTH];
    double tempOutNoise;
    double tempInNoise;
    double noizDens[RESNSRCS];
    double lnNdens[RESNSRCS];
    int i;

     /* define the names of the noise sources */

    static char *RESnNames[RESNSRCS] = {
	/* Note that we have to keep the order consistent with the
	 * strchr definitions in RESdefs.h */
	"_thermal",         /* Thermal noise */
	"_1overf",          /* flicker (1/f) noise */
	""                  /* total resistor noise */
    };

    
    for (model = firstModel; model != NULL; model = model->RESnextModel) {
	for (inst = model->RESinstances; inst != NULL; 
	        inst = inst->RESnextInstance) {
	    
	    if (inst->RESowner != ARCHme) continue;
            
	    if(!inst->RESnoisy) continue; /* Quiet resistors are skipped */
	    
	    switch (operation) {

	    case N_OPEN:

		/* 
		 * See if we have to to produce a summary report
		 * if so, name the noise generator 
		 */

		if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
		    switch (mode) {

		    case N_DENS:
		        for (i=0; i < RESNSRCS; i++) {
			(void)sprintf(name,"onoise_%s%s",
			              inst->RESname, RESnNames[i]);

			data->namelist = (IFuid *)
			        trealloc((char *)data->namelist,
			        (data->numPlots + 1)*sizeof(IFuid));
			if (!data->namelist) return(E_NOMEM);
		        (*(SPfrontEnd->IFnewUid))(ckt,
			    &(data->namelist[data->numPlots++]),
			    (IFuid)NULL,name,UID_OTHER,(void **)NULL);
				/* we've added one more plot */
                        }
			break;

		    case INT_NOIZ:
		        for (i=0; i < RESNSRCS; i++) {
			    (void)sprintf(name,"onoise_total_%s%s",
			                  inst->RESname, RESnNames[i]);


			    data->namelist = (IFuid *)
			             trealloc((char *)data->namelist,
				     (data->numPlots + 1)*sizeof(IFuid));
                            if (!data->namelist) return(E_NOMEM);
		            (*(SPfrontEnd->IFnewUid))(ckt,
			        &(data->namelist[data->numPlots++]),
			        (IFuid)NULL,name,UID_OTHER,(void **)NULL);
				/* we've added one more plot */


			    (void)sprintf(name,"inoise_total_%s%s",
			        inst->RESname,RESnNames[i]);


			    data->namelist = (IFuid *)
			            trealloc((char *)data->namelist,
			            (data->numPlots + 1)*sizeof(IFuid));
                            if (!data->namelist) return(E_NOMEM);
		            (*(SPfrontEnd->IFnewUid))(ckt,
			        &(data->namelist[data->numPlots++]),
			        (IFuid)NULL,name,UID_OTHER,(void **)NULL);
				/* we've added one more plot */

                        }
			break;
		    }
		}
		break;

	    case N_CALC:
		switch (mode) {

		case N_DENS:
		
		       NevalSrc2(&noizDens[RESTHNOIZ],&lnNdens[RESTHNOIZ],
		                ckt,THERMNOISE, inst->RESposNode,inst->RESnegNode,
			        inst->RESconduct * inst->RESm, inst->RESdtemp); 

                       NevalSrc2(&noizDens[RESFLNOIZ],(double*)NULL, ckt,
			        N_GAIN,inst->RESposNode, inst->RESnegNode,
				(double)0.0, (double)0.0);
				
#if 0
                       printf("DC current in resistor %s: %e\n",inst->RESname, inst->REScurrent);
#endif
	       	
		       noizDens[RESFLNOIZ] *= inst->RESm * model->RESfNcoef * exp(model->RESfNexp *
				              log(MAX(fabs(inst->REScurrent),
					      N_MINLOG))) / data->freq;
                       lnNdens[RESFLNOIZ]   = log(MAX(noizDens[RESFLNOIZ],N_MINLOG));

                       noizDens[RESTOTNOIZ] = noizDens[RESTHNOIZ] + noizDens[RESFLNOIZ];
		       lnNdens[RESTOTNOIZ]  = log(noizDens[RESTOTNOIZ]);		 

		    *OnDens += noizDens[RESTOTNOIZ];

		    if (data->delFreq == 0.0) { 

			/* if we haven't done any previous integration, we need to */
			/* initialize our "history" variables                      */

                        for (i=0; i < RESNSRCS; i++) {
			     inst->RESnVar[LNLSTDENS][i] = lnNdens[i];
                        }
			
			/* clear out our integration variable if it's the first pass */

			if (data->freq == ((NOISEAN*)ckt->CKTcurJob)->NstartFreq) {
			    for (i=0; i < RESNSRCS; i++) {
			    inst->RESnVar[OUTNOIZ][i] = 0.0; /* Clear output noise */
			    inst->RESnVar[INNOIZ][i] = 0.0;  /* Clear input noise */ 
			    }
			}
		    } else {   /* data->delFreq != 0.0 (we have to integrate) */
		    
/* In order to get the best curve fit, we have to integrate each component separately */

  			   for (i = 0; i < RESNSRCS; i++) {
			       if (i != RESTOTNOIZ) {		    
			           tempOutNoise = Nintegrate(noizDens[i], lnNdens[i],
			                          inst->RESnVar[LNLSTDENS][i], data);
			           tempInNoise = Nintegrate(noizDens[i] * 
			                                    data->GainSqInv ,lnNdens[i] 
					   		    + data->lnGainInv,
			                                    inst->RESnVar[LNLSTDENS][i] 
							    + data->lnGainInv,
			                                    data);
				   inst->RESnVar[LNLSTDENS][i] = lnNdens[i];
				   data->outNoiz += tempOutNoise;
			           data->inNoise += tempInNoise;			 
			           if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
				       inst->RESnVar[OUTNOIZ][i] += tempOutNoise;
				       inst->RESnVar[OUTNOIZ][RESTOTNOIZ] += tempOutNoise;
				       inst->RESnVar[INNOIZ][i] += tempInNoise;
				       inst->RESnVar[INNOIZ][RESTOTNOIZ] += tempInNoise;
                                }
			}
		}
			        
	}
	            if (data->prtSummary) {
			for (i=0; i < RESNSRCS; i++) {     /* print a summary report */
			    data->outpVector[data->outNumber++] = noizDens[i];
			}
		    }
		    break;

		case INT_NOIZ:        /* already calculated, just output */
		    if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
		        for (i=0; i < RESNSRCS; i++) {
			    data->outpVector[data->outNumber++] = inst->RESnVar[OUTNOIZ][i];
			    data->outpVector[data->outNumber++] = inst->RESnVar[INNOIZ][i];
			}
		    }    /* if */
		    break;
		}    /* switch (mode) */
		break;

	    case N_CLOSE:
		return (OK);         /* do nothing, the main calling routine will close */
		break;               /* the plots */
	    }    /* switch (operation) */
	}    /* for inst */
    }    /* for model */

return(OK);
}
Beispiel #22
0
void track_through_ztransverse(double **part, long np, ZTRANSVERSE *ztransverse, double Po,
                               RUN *run, long i_pass, CHARGE *charge
                               )
{
  static double *posItime[2] = {NULL, NULL};     /* array for particle density times x, y*/
  static double *posIfreq;                       /* array for FFT of particle density times x or y*/
  static double *Vtime = NULL;           /* array for voltage acting on each bin */
  static long max_n_bins = 0;
  static long *pbin = NULL;              /* array to record which bin each particle is in */
  static double *time = NULL;            /* array to record arrival time of each particle */
  static double *pz = NULL;
  static long max_np = 0;
  double *Vfreq, *iZ;
#if USE_MPI
  long i;
#endif
  long ib, nb, n_binned, nfreq, iReal, iImag, plane, first;
  double factor, tmin, tmax, tmean, dt, userFactor[2], rampFactor=1;
  static long not_first_call = -1;
  long ip, ip1, ip2, bunches, bunch, npb, i_pass0;
  long bucketEnd[MAX_BUCKETS];
#if USE_MPI
  float *buffer_send, *buffer_recv;
#endif
#if defined(DEBUG)
  FILE *fp;
#endif
  i_pass0 = i_pass;
  if ((i_pass -= ztransverse->startOnPass)<0)
    return;
  
  if (i_pass>=(ztransverse->rampPasses-1))
    rampFactor = 1;
  else
    rampFactor = (i_pass+1.0)/ztransverse->rampPasses;
  
  not_first_call += 1;

#if (!USE_MPI)
  if (np>max_np) {
    pbin = trealloc(pbin, sizeof(*pbin)*(max_np=np));
    time = trealloc(time, sizeof(*time)*max_np);
    pz = trealloc(pz, sizeof(*pz)*max_np);
  }
#else
    if (USE_MPI) {
      long np_total;
      if (isSlave) {
	MPI_Allreduce(&np, &np_total, 1, MPI_LONG, MPI_SUM, workers);
	if (np_total>max_np) { 
	  /* if the total number of particles is increased, we do reallocation for every CPU */
	  pbin = trealloc(pbin, sizeof(*pbin)*(max_np=np));
	  time = trealloc(time, sizeof(*time)*max_np);
	  pz = trealloc(pz, sizeof(*pz)*max_np);
	  max_np = np_total; /* max_np should be the sum across all the processors */
	}
      }
    } 
#endif
  
  if ((part[0][6]-floor(part[0][6]))!=0) {
    /* This is a kludgey way to determine that particles have been assigned to buckets */
    printf("Bunched beam detected\n"); fflush(stdout);
#if USE_MPI
    if (n_processors!=1) {
      printf("Error (ZTRANSVERSE): must have bunch_frequency=0 for parallel mode.\n");
      MPI_Barrier(MPI_COMM_WORLD); /* Make sure the information can be printed before aborting */
      MPI_Abort(MPI_COMM_WORLD, 2);
    }
#endif
    /* Start by sorting in bucket order */
    qsort(part[0], np, COORDINATES_PER_PARTICLE*sizeof(double), comp_BucketNumbers);
    /* Find the end of the buckets in the particle list */
    bunches = 0;
    for (ip=1; ip<np; ip++) {
      if ((part[ip-1][6]-floor(part[ip-1][6]))!=(part[ip][6]-floor(part[ip][6]))) {
        /* printf("Bucket %ld ends with ip=%ld\n", bunches, ip-1); fflush(stdout); */
        bucketEnd[bunches++] = ip-1;
        if (bunches>=MAX_BUCKETS) {
            bombElegant("Error (wake): maximum number of buckets was exceeded", NULL);
          }
      }
    }
    bucketEnd[bunches++] = np-1;
  } else {
    bunches = 1;
    bucketEnd[0] = np-1;
  }
  /* printf("Bucket %ld ends with ip=%ld\n", bunches, bucketEnd[bunches-1]); fflush(stdout); */

  ip2 = -1;
  for (bunch=0; bunch<bunches; bunch++) {
    ip1 = ip2+1;
    ip2 = bucketEnd[bunch];
    npb = ip2-ip1+1;
    /* printf("Processing bunch %ld with %ld particles\n", bunch, npb); fflush(stdout); */
    /* Compute time coordinate of each particle */
    tmean = computeTimeCoordinates(time+ip1, Po, part+ip1, npb);
    find_min_max(&tmin, &tmax, time+ip1, npb);
#if USE_MPI
    find_global_min_max(&tmin, &tmax, np, workers);      
#endif
    if (bunch==0) {
      /* use np here since we need to compute the macroparticle charge */
      set_up_ztransverse(ztransverse, run, i_pass, np, charge, tmax-tmin);
    }
    nb = ztransverse->n_bins;
    dt = ztransverse->bin_size;
    tmin -= dt;
    tmax -= dt;
    if ((tmax-tmin)*2>nb*dt) {
      TRACKING_CONTEXT tcontext;
      getTrackingContext(&tcontext);
      fprintf(stderr, "%s %s: Time span of bunch (%le s) is more than half the total time span (%le s).\n",
              entity_name[tcontext.elementType],
              tcontext.elementName,
              tmax-tmin, nb*dt);
      fprintf(stderr, "If using broad-band impedance, you should increase the number of bins and rerun.\n");
      fprintf(stderr, "If using file-based impedance, you should increase the number of data points or decrease the frequency resolution.\n");
      exitElegant(1);
    }

    if (nb>max_n_bins) {
      posItime[0] = trealloc(posItime[0], 2*sizeof(**posItime)*(max_n_bins=nb));
      posItime[1] = trealloc(posItime[1], 2*sizeof(**posItime)*(max_n_bins=nb));
      posIfreq = trealloc(posIfreq, 2*sizeof(*posIfreq)*(max_n_bins=nb));
      Vtime = trealloc(Vtime, 2*sizeof(*Vtime)*(max_n_bins+1));
    }

    for (ib=0; ib<nb; ib++)
      posItime[0][2*ib] = posItime[0][2*ib+1] = 
        posItime[1][2*ib] = posItime[1][2*ib+1] = 0;

    /* make arrays of I(t)*x and I(t)*y */
    n_binned = binTransverseTimeDistribution(posItime, pz, pbin, tmin, dt, nb, 
                                             time+ip1, part+ip1, Po, npb,
                                             ztransverse->dx, ztransverse->dy,
                                             ztransverse->xDriveExponent, ztransverse->yDriveExponent);
#if (!USE_MPI)
    if (n_binned!=npb) {
      fprintf(stdout, "Warning: only %ld of %ld particles were binned (ZTRANSVERSE)!\n", n_binned, npb);
      if (!not_first_call) {
        fprintf(stdout, "*** This may produce unphysical results.  Your wake needs smaller frequency\n");
        fprintf(stdout, "    spacing to cover a longer time span.\n");
      }
      fflush(stdout);
    }  
#else
    if (USE_MPI) {
      int all_binned, result = 1;
      if (isSlave)
        result = ((n_binned==np) ? 1 : 0);
      
      MPI_Allreduce(&result, &all_binned, 1, MPI_INT, MPI_LAND, workers);
      if (!all_binned) {
	if (myid==1) {  
	  /* This warning will be given only if the flag MPI_DEBUG is defined for the Pelegant */ 
	  fprintf(stdout, "warning: Not all of %ld particles were binned (WAKE)\n", np);
	  fprintf(stdout, "consider setting n_bins=0 in WAKE definition to invoke autoscaling\n");
	  fflush(stdout); 
	}
      }
    }
#endif

    userFactor[0] = ztransverse->factor*ztransverse->xfactor*rampFactor;
    userFactor[1] = ztransverse->factor*ztransverse->yfactor*rampFactor;

    first = 1;
    for (plane=0; plane<2; plane++) {
#if USE_MPI
      /* This could be good for some advanced network structures */
      /*
        if (isSlave) {
        double buffer[nb];
        MPI_Allreduce(posItime[plane], buffer, nb, MPI_DOUBLE, MPI_SUM, workers);
        memcpy(posItime[plane], buffer, sizeof(double)*nb);
        }
        */
      if (isSlave) {
        buffer_send = malloc(sizeof(float) * nb);
        buffer_recv = malloc(sizeof(float) * nb);
        for (i=0; i<nb; i++)
          buffer_send[i] = posItime[plane][i];
        MPI_Reduce(buffer_send, buffer_recv, nb, MPI_FLOAT, MPI_SUM, 1, workers);
        MPI_Bcast(buffer_recv, nb, MPI_FLOAT, 1, workers);
        for (i=0; i<nb; i++)
          posItime[plane][i] = buffer_recv[i];
        free(buffer_send);
        free(buffer_recv);
      }

#endif
      if (userFactor[plane]==0) {
        for (ib=0; ib<nb; ib++)
          Vtime[ib] = 0;
      } else {
        if (ztransverse->smoothing)
          SavitzyGolaySmooth(posItime[plane], nb, ztransverse->SGOrder,
                             ztransverse->SGHalfWidth, ztransverse->SGHalfWidth, 0);
        
        /* Take the FFT of (x*I)(t) to get (x*I)(f) */
        memcpy(posIfreq, posItime[plane], 2*nb*sizeof(*posIfreq));
        realFFT(posIfreq, nb, 0);
        
        /* Compute V(f) = i*Z(f)*(x*I)(f), putting in a factor 
         * to normalize the current waveform
         */
        Vfreq = Vtime;
        factor = ztransverse->macroParticleCharge*particleRelSign/dt*userFactor[plane];
        iZ = ztransverse->iZ[plane];
        Vfreq[0] = posIfreq[0]*iZ[0]*factor;
        nfreq = nb/2 + 1;
        if (nb%2==0)
          /* Nyquist term */
          Vfreq[nb-1] = posIfreq[nb-1]*iZ[nb-1]*factor;
        for (ib=1; ib<nfreq-1; ib++) {
          iImag = (iReal = 2*ib-1)+1;
          /* The signs are chosen here to get agreement with TRFMODE.
             In particular, test particles following closely behind the 
             drive particle get defocused.
             */
          Vfreq[iReal] =  (posIfreq[iReal]*iZ[iImag] + posIfreq[iImag]*iZ[iReal])*factor; 
          Vfreq[iImag] = -(posIfreq[iReal]*iZ[iReal] - posIfreq[iImag]*iZ[iImag])*factor;
        }
        
        /* Compute inverse FFT of V(f) to get V(t) */
        realFFT(Vfreq, nb, INVERSE_FFT);
        Vtime = Vfreq;
        
        /* change particle transverse momenta to reflect voltage in relevant bin */
        applyTransverseWakeKicks(part+ip1, time+ip1, pz, pbin, npb, 
                                 Po, plane, 
                                 Vtime, nb, tmin, dt, ztransverse->interpolate,
                                 plane==0?ztransverse->xProbeExponent:ztransverse->yProbeExponent);
      }

      if (ztransverse->SDDS_wake_initialized && ztransverse->wakes) {
        /* wake potential output */
        factor = ztransverse->macroParticleCharge*particleRelSign/dt;
        if ((ztransverse->wake_interval<=0 || ((i_pass0-ztransverse->wake_start)%ztransverse->wake_interval)==0) &&
            i_pass0>=ztransverse->wake_start && i_pass0<=ztransverse->wake_end) {
          if (first && !SDDS_StartTable(&ztransverse->SDDS_wake, nb)) {
            SDDS_SetError("Problem starting SDDS table for wake output (track_through_ztransverse)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          for (ib=0; ib<nb; ib++) {
            if (!SDDS_SetRowValues(&ztransverse->SDDS_wake, SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE, ib,
                                   0, ib*dt, 
                                   1+plane*2, posItime[plane][ib]*factor,  
                                   2+plane*2, Vtime[ib], -1)) {
              SDDS_SetError("Problem setting rows of SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (!SDDS_SetParameters(&ztransverse->SDDS_wake, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                                  "Pass", i_pass0, "q", ztransverse->macroParticleCharge*particleRelSign*np, NULL)) {
            SDDS_SetError("Problem setting parameters of SDDS table for wake output (track_through_ztransverse)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (ztransverse->broad_band) {
            if (!SDDS_SetParameters(&ztransverse->SDDS_wake, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                                    "Rs", ztransverse->Rs, "fo", ztransverse->freq, 
                                    "Deltaf", ztransverse->bin_size, NULL)) {
              SDDS_SetError("Problem setting parameters of SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (!first) {
            if (!SDDS_WriteTable(&ztransverse->SDDS_wake)) {
              SDDS_SetError("Problem writing SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
            if (!inhibitFileSync)
              SDDS_DoFSync(&ztransverse->SDDS_wake);
          }
        }
      }
      first = 0;
    }
  }
  
#if defined(MIMIMIZE_MEMORY)
  free(posItime[0]);
  free(posItime[1]);
  free(posIfreq);
  free(Vtime);
  free(pbin);
  free(time);
  free(pz);
  posItime[0] = posItime[1] = Vtime = time = pz = posIfreq = NULL;
  pbin = NULL;
  max_n_bins = max_np = 0 ;
#endif

}
Beispiel #23
0
int main(int argc, char **argv)
{
    double tolerance, result;
    long nEval;
    int32_t nEvalMax = 5000, nPassMax = 25;
    double a[4], da[4];
    double alo[4], ahi[4];
    long n_dimen = 4, zeroes;
    SDDS_DATASET InputTable, OutputTable;
    SCANNED_ARG *s_arg;
    long i_arg, i, clue, fullOutput;
    char *input, *output, *xName, *yName;
    int32_t xIndex, yIndex, fitIndex, residualIndex;
    long retval;
    double *fitData, *residualData, rmsResidual;
    unsigned long guessFlags, dummyFlags, pipeFlags;
    double constantGuess, factorGuess, freqGuess, phaseGuess;
    double firstZero, lastZero;
    unsigned long simplexFlags = 0;
    
    SDDS_RegisterProgramName(argv[0]);
    argc = scanargs(&s_arg, argc, argv);
    if (argc<2 || argc>(2+N_OPTIONS))
        bomb(NULL, USAGE);

    input = output = NULL;
    tolerance = 1e-6;
    verbosity = fullOutput = 0;
    clue = -1;
    xName = yName = NULL;
    guessFlags = 0;
    pipeFlags = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (s_arg[i_arg].arg_type==OPTION) {
            switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
              case SET_TOLERANCE:
                if (s_arg[i_arg].n_items!=2 || sscanf(s_arg[i_arg].list[1], "%lf", &tolerance)!=1)
                    SDDS_Bomb("incorrect -tolerance syntax");
                break;
              case SET_VERBOSITY:
                if (s_arg[i_arg].n_items!=2 || sscanf(s_arg[i_arg].list[1], "%ld", &verbosity)!=1)
                    SDDS_Bomb("incorrect -verbosity syntax");
                break;
              case SET_GUESS:
                if (s_arg[i_arg].n_items<2)
                    SDDS_Bomb("incorrect -guess syntax");
                s_arg[i_arg].n_items -= 1;
                if (!scanItemList(&guessFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0,
                                    "constant", SDDS_DOUBLE, &constantGuess, 1, GUESS_CONSTANT_GIVEN,
                                    "factor", SDDS_DOUBLE, &factorGuess, 1, GUESS_FACTOR_GIVEN,
                                    "frequency", SDDS_DOUBLE, &freqGuess, 1, GUESS_FREQ_GIVEN,
                                    "phase", SDDS_DOUBLE, &phaseGuess, 1, GUESS_PHASE_GIVEN,
                                    NULL))
                    SDDS_Bomb("invalid -guess syntax");
                break;
              case SET_COLUMNS:
                if (s_arg[i_arg].n_items!=3)
                    SDDS_Bomb("invalid -columns syntax");
                xName = s_arg[i_arg].list[1];
                yName = s_arg[i_arg].list[2];
                break;
              case SET_FULLOUTPUT:
                fullOutput = 1;
                break;
              case SET_LIMITS:
                if (s_arg[i_arg].n_items<2)
                    SDDS_Bomb("incorrect -limits syntax");
                s_arg[i_arg].n_items -= 1;
                if (!scanItemList(&dummyFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0,
                                    "evaluations", SDDS_LONG, &nEvalMax, 1, 0,
                                    "passes", SDDS_LONG, &nPassMax, 1, 0,
                                    NULL) ||
                    nEvalMax<=0 || nPassMax<=0)
                    SDDS_Bomb("invalid -limits syntax");
                break;
              case SET_PIPE:
                if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags))
                    SDDS_Bomb("invalid -pipe syntax");
                break;
              default:
                fprintf(stderr, "error: unknown/ambiguous option: %s\n", s_arg[i_arg].list[0]);
                exit(1);
                break;
                }
            }
        else {
            if (input==NULL) 
                input = s_arg[i_arg].list[0];
            else if (output==NULL)
                output = s_arg[i_arg].list[0];
            else
                SDDS_Bomb("too many filenames");
            }
        }

    processFilenames("sddssinefit", &input, &output, pipeFlags, 0, NULL);

    if (!xName || !yName)
        SDDS_Bomb("-columns option must be given");

    if (!SDDS_InitializeInput(&InputTable, input) ||
        SDDS_GetColumnIndex(&InputTable, xName)<0 || SDDS_GetColumnIndex(&InputTable, yName)<0)
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

    setupOutputFile(&OutputTable, &xIndex, &yIndex, &fitIndex, &residualIndex, output, fullOutput,
                    &InputTable, xName, yName);

    fitData = residualData = NULL;

    alo[0] = - (ahi[0] = DBL_MAX);
    alo[1] = alo[2] = 0;
    ahi[1] = ahi[2] = DBL_MAX;
    alo[3] = - (ahi[3] = PIx2);
    firstZero = lastZero = 0;
    while ((retval=SDDS_ReadPage(&InputTable))>0) {
        if (!(xData = SDDS_GetColumnInDoubles(&InputTable, xName)) ||
            !(yData = SDDS_GetColumnInDoubles(&InputTable, yName)))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        if ((nData = SDDS_CountRowsOfInterest(&InputTable))<4)
            continue;

        find_min_max(&yMin, &yMax, yData, nData);
        find_min_max(&xMin, &xMax, xData, nData);
        zeroes = 0;
        for (i=1; i<nData; i++)
          if (yData[i]*yData[i-1]<=0) {
            i++;
            if (!zeroes)
              firstZero = (xData[i]+xData[i-1])/2;
            else 
              lastZero = (xData[i]+xData[i-1])/2;
            zeroes ++;
          }
        a[0] = (yMin+yMax)/2;
        a[1] = (yMax-yMin)/2;
        if (!zeroes)
            a[2] = 2/fabs(xMax-xMin);
        else
            a[2] = zeroes/(2*fabs(lastZero-firstZero));
        a[3] = 0;

        if (guessFlags&GUESS_CONSTANT_GIVEN)
            a[0] = constantGuess;
        if (guessFlags&GUESS_FACTOR_GIVEN)
            a[1] = factorGuess;
        if (guessFlags&GUESS_FREQ_GIVEN)
            a[2] = freqGuess;
        if (guessFlags&GUESS_PHASE_GIVEN)
            a[3] = phaseGuess;

        alo[1] = a[1]/2;
        if (!(da[0] = a[0]*0.1))
          da[0] = 0.01;
        if (!(da[1] = a[1]*0.1))
          da[1] = 0.01;
        da[2] = a[2]*0.25;
        da[3] = 0.01;

        nEval = simplexMin(&result, a, da, alo, ahi, NULL, n_dimen, -DBL_MAX, tolerance, fitFunction, 
                            (verbosity>0?report:NULL), nEvalMax, nPassMax,
                           12, 3, 1.0, simplexFlags);
        
        fitData = trealloc(fitData, sizeof(*fitData)*nData);
        residualData = trealloc(residualData, sizeof(*residualData)*nData);
        for (i=result=0; i<nData; i++)
            result += sqr(residualData[i] = yData[i]-(fitData[i]=a[0]+a[1]*sin(PIx2*a[2]*xData[i]+a[3])));
        rmsResidual = sqrt(result/nData);
        if (verbosity>1) {
            fprintf(stderr, "RMS deviation: %.15e\n", rmsResidual);
            fprintf(stderr, "(RMS deviation)/(largest value): %.15e\n", rmsResidual/MAX(fabs(yMin), fabs(yMax)));
            }
        if (verbosity>0) {
            fprintf(stderr, "coefficients of fit to the form y = a0 + a1*sin(2*PI*a2*x+a3), a = \n");
            for (i=0; i<4; i++)
                fprintf(stderr, "%.8e ", a[i]);
            fprintf(stderr, "\n");
            }

        if (!SDDS_StartPage(&OutputTable, nData) ||
            !SDDS_SetColumn(&OutputTable, SDDS_SET_BY_INDEX, xData, nData, xIndex) ||
            !SDDS_SetColumn(&OutputTable, SDDS_SET_BY_INDEX, fitData, nData, fitIndex) ||
            !SDDS_SetParameters(&OutputTable, SDDS_PASS_BY_VALUE|SDDS_SET_BY_NAME,
                                "sinefitConstant", a[0], "sinefitFactor", a[1], "sinefitFrequency", a[2], 
                                "sinefitPhase", a[3], "sinefitRmsResidual", rmsResidual, NULL) ||
            (fullOutput && 
             (!SDDS_SetColumn(&OutputTable, SDDS_SET_BY_INDEX, yData, nData, yIndex) ||
              !SDDS_SetColumn(&OutputTable, SDDS_SET_BY_INDEX, residualData, nData, residualIndex) )) ||
            !SDDS_WritePage(&OutputTable))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
    return 0;
    }
Beispiel #24
0
void add_error_element(ERRORVAL *errcon, NAMELIST_TEXT *nltext, LINE_LIST *beamline)
{
    long n_items, n_added, i_start, firstIndexInGroup;
    ELEMENT_LIST *context;
    double sMin = -DBL_MAX, sMax = DBL_MAX;
    
    log_entry("add_error_element");

    if ((n_items = errcon->n_items)==0) {
        if (errcon->new_data_read)
            bombElegant("improper sequencing of error specifications and tracking", NULL);
        errcon->new_data_read = 1;
        }

    /* process namelist text */
    set_namelist_processing_flags(STICKY_NAMELIST_DEFAULTS);
    set_print_namelist_flags(0);
    if (processNamelist(&error, nltext)==NAMELIST_ERROR)
      bombElegant(NULL, NULL);
    if (name==NULL) {
      if (!element_type)
        bombElegant("element name missing in error namelist", NULL);
      SDDS_CopyString(&name, "*");
    }
    if (echoNamelists) print_namelist(stdout, &error);

    /* check for valid input and copy to errcon arrays */
    if (item==NULL)
        bombElegant("item name missing in error namelist", NULL);
    if (match_string(type, known_error_type, N_ERROR_TYPES, 0)<0)
        bombElegant("unknown error type specified", NULL);
    if (bind_number<0)
        bombElegant("bind_number < 0", NULL);
    if (!additive && fractional)
        bombElegant("fractional errors must be additive", NULL);

    context = NULL;
    n_added = 0;
    i_start = n_items;

    context = NULL;
    if (after && strlen(after)) {
      if (!(context=find_element(after, &context, &(beamline->elem)))) {
        fprintf(stdout, "Element %s not found in beamline.\n", after);
        exitElegant(1);
      }
      sMin = context->end_pos;
      if (find_element(after, &context, &(beamline->elem))) {
        fprintf(stdout, "Element %s found in beamline more than once.\n", after);
        exitElegant(1);
      }
      fprintf(stdout, "%s found at s = %le m\n", after, sMin);
      fflush(stdout);
    }
    context = NULL;
    if (before && strlen(before)) {
      if (!(context=find_element(before, &context, &(beamline->elem)))) {
        fprintf(stdout, "Element %s not found in beamline.\n", before);
        exitElegant(1);
      }
      sMax = context->end_pos;
      if (find_element(before, &context, &(beamline->elem))) {
        fprintf(stdout, "Element %s found in beamline more than once.\n", after);
        exitElegant(1);
      }
      fprintf(stdout, "%s found at s = %le m\n", before, sMax);
      fflush(stdout);
    }
    if (after && before && sMin>sMax) {
      fprintf(stdout, "Element %s is not upstream of %s!\n",
              before, after);
      exitElegant(1);
    }
    if (element_type && has_wildcards(element_type) && strchr(element_type, '-'))
      element_type = expand_ranges(element_type);
    if (has_wildcards(name)) {
        if (strchr(name, '-'))
            name = expand_ranges(name);
        str_toupper(name);
        firstIndexInGroup = -1;
        while ((context=wfind_element(name, &context, &(beamline->elem)))) {
            if (element_type && 
                !wild_match(entity_name[context->type], element_type))
              continue;
            if (exclude &&
                wild_match(context->name, exclude))
              continue;
            if (i_start!=n_items && duplicate_name(errcon->name+i_start, n_items-i_start, context->name))
                continue;
            if ((sMin>=0 && context->end_pos<sMin) ||
                (sMax>=0 && context->end_pos>sMax)) 
              continue;
            errcon->name              = trealloc(errcon->name, sizeof(*errcon->name)*(n_items+1));
            errcon->item              = trealloc(errcon->item, sizeof(*errcon->item)*(n_items+1));
            errcon->quan_name         = trealloc(errcon->quan_name, sizeof(*errcon->quan_name)*(n_items+1));
            errcon->quan_final_index  
              = trealloc(errcon->quan_final_index, sizeof(*errcon->quan_final_index)*(n_items+1));
            errcon->quan_unit         = trealloc(errcon->quan_unit, sizeof(*errcon->quan_unit)*(n_items+1));
            errcon->error_level       = trealloc(errcon->error_level, sizeof(*errcon->error_level)*(n_items+1));
            errcon->error_cutoff      = trealloc(errcon->error_cutoff, sizeof(*errcon->error_cutoff)*(n_items+1));
            errcon->error_type        = trealloc(errcon->error_type, sizeof(*errcon->error_type)*(n_items+1));
            errcon->elem_type         = trealloc(errcon->elem_type, sizeof(*errcon->elem_type)*(n_items+1));
            errcon->error_value       = trealloc(errcon->error_value, sizeof(*errcon->error_value)*(n_items+1));
            errcon->unperturbed_value = trealloc(errcon->unperturbed_value, sizeof(*errcon->unperturbed_value)*(n_items+1));
            errcon->param_number      = trealloc(errcon->param_number, sizeof(*errcon->param_number)*(n_items+1));
            errcon->bind_number       = trealloc(errcon->bind_number, sizeof(*errcon->bind_number)*(n_items+1));
            errcon->flags             = trealloc(errcon->flags, sizeof(*errcon->flags)*(n_items+1));
            errcon->sMin             = trealloc(errcon->sMin, sizeof(*errcon->sMin)*(n_items+1));
            errcon->sMax             = trealloc(errcon->sMax, sizeof(*errcon->sMax)*(n_items+1));
            errcon->boundTo          = trealloc(errcon->boundTo, sizeof(*errcon->boundTo)*(n_items+1));

            cp_str(errcon->item+n_items, str_toupper(item));
            cp_str(errcon->name+n_items, context->name);
            errcon->error_level[n_items] = amplitude*error_factor;
            errcon->error_cutoff[n_items] = cutoff;
            errcon->error_type[n_items] = match_string(type, known_error_type, N_ERROR_TYPES, 0);
            errcon->quan_name[n_items] = tmalloc(sizeof(char*)*(strlen(context->name)+strlen(item)+4));
            errcon->quan_final_index[n_items] = -1;
            sprintf(errcon->quan_name[n_items], "d%s.%s", context->name, item);
            errcon->flags[n_items]  = (fractional?FRACTIONAL_ERRORS:0);
            errcon->flags[n_items] += (bind==0?0:(bind==-1?ANTIBIND_ERRORS:BIND_ERRORS));
            errcon->flags[n_items] += (post_correction?POST_CORRECTION:PRE_CORRECTION);
            errcon->flags[n_items] += (additive?0:NONADDITIVE_ERRORS);
            errcon->bind_number[n_items] = bind_number;
            /* boundTo must be -1 when there is no cross-name binding or when this element is the
             * first of a series 
             */
            errcon->boundTo[n_items] = bind_across_names?firstIndexInGroup:-1;
/*
            if (errcon->boundTo[n_items]!=-1)
              fprintf(stdout, "%s bound to %s\n", 
                      errcon->name[n_items], errcon->name[errcon->boundTo[n_items]]);
*/
            errcon->sMin[n_items] = sMin;
            errcon->sMax[n_items] = sMax;
            errcon->elem_type[n_items] = context->type;

            if ((errcon->param_number[n_items] = confirm_parameter(item, context->type))<0) {
                fprintf(stdout, "error: cannot vary %s--no such parameter for %s (wildcard name: %s)\n",item, context->name, name);
                fflush(stdout);
                exitElegant(1);
                }
            cp_str(&errcon->quan_unit[n_items], 
                errcon->flags[n_items]&FRACTIONAL_ERRORS?"fr":
                entity_description[errcon->elem_type[n_items]].parameter[errcon->param_number[n_items]].unit
                );
            errcon->unperturbed_value[n_items] 
                = parameter_value(errcon->name[n_items], errcon->elem_type[n_items], errcon->param_number[n_items],
                            beamline);
            if (errcon->unperturbed_value[n_items]==0 && errcon->flags[n_items]&FRACTIONAL_ERRORS)
                fprintf(stdout, "***\7\7\7 warning: you've specified fractional errors for %s.%s, but the unperturbed value is zero.\nThis may be an error.\n", 
                    errcon->name[n_items], errcon->item[n_items]);
                fflush(stdout);
            if (duplicate_name(errcon->quan_name, n_items, errcon->quan_name[n_items]))
                fprintf(stdout, "***\7\7\7 warning: you've specified errors for %s.%s more than once!\n",
                    errcon->name[n_items], errcon->item[n_items]);
                fflush(stdout);
            errcon->n_items = ++n_items;
            n_added++;
            if (firstIndexInGroup==-1)
              firstIndexInGroup = n_items-1;
            }
        }
    else {
        str_toupper(name);
        if (!(context=find_element(name, &context, &(beamline->elem)))) {
            fprintf(stdout, "error: cannot add errors to element %s--not in beamline\n", name);
            fflush(stdout);
            exitElegant(1);
            }
        errcon->name              = trealloc(errcon->name, sizeof(*errcon->name)*(n_items+1));
        errcon->item              = trealloc(errcon->item, sizeof(*errcon->item)*(n_items+1));
        errcon->quan_name         = trealloc(errcon->quan_name, sizeof(*errcon->quan_name)*(n_items+1));
        errcon->quan_final_index  
          = trealloc(errcon->quan_final_index, sizeof(*errcon->quan_final_index)*(n_items+1));
        errcon->quan_unit         = trealloc(errcon->quan_unit, sizeof(*errcon->quan_unit)*(n_items+1));
        errcon->error_level       = trealloc(errcon->error_level, sizeof(*errcon->error_level)*(n_items+1));
        errcon->error_cutoff      = trealloc(errcon->error_cutoff, sizeof(*errcon->error_cutoff)*(n_items+1));
        errcon->error_type        = trealloc(errcon->error_type, sizeof(*errcon->error_type)*(n_items+1));
        errcon->elem_type         = trealloc(errcon->elem_type, sizeof(*errcon->elem_type)*(n_items+1));
        errcon->error_value       = trealloc(errcon->error_value, sizeof(*errcon->error_value)*(n_items+1));
        errcon->unperturbed_value = trealloc(errcon->unperturbed_value, sizeof(*errcon->unperturbed_value)*(n_items+1));
        errcon->param_number      = trealloc(errcon->param_number, sizeof(*errcon->param_number)*(n_items+1));
        errcon->bind_number       = trealloc(errcon->bind_number, sizeof(*errcon->bind_number)*(n_items+1));
        errcon->flags             = trealloc(errcon->flags, sizeof(*errcon->flags)*(n_items+1));
        errcon->sMin             = trealloc(errcon->sMin, sizeof(*errcon->sMin)*(n_items+1));
        errcon->sMax             = trealloc(errcon->sMax, sizeof(*errcon->sMax)*(n_items+1));
        errcon->boundTo          = trealloc(errcon->boundTo, sizeof(*errcon->boundTo)*(n_items+1));

        cp_str(errcon->item+n_items, str_toupper(item));
        cp_str(errcon->name+n_items, context->name);
        errcon->error_level[n_items] = amplitude;
        errcon->error_cutoff[n_items] = cutoff;
        errcon->error_type[n_items] = match_string(type, known_error_type, N_ERROR_TYPES, 0);
        errcon->quan_name[n_items] = tmalloc(sizeof(char*)*(strlen(context->name)+strlen(item)+4));
        sprintf(errcon->quan_name[n_items], "d%s.%s", context->name, item);
        errcon->flags[n_items]  = (fractional?FRACTIONAL_ERRORS:0);
        errcon->flags[n_items] += (bind==0?0:(bind==-1?ANTIBIND_ERRORS:BIND_ERRORS));
        errcon->flags[n_items] += (post_correction?POST_CORRECTION:PRE_CORRECTION);
        errcon->flags[n_items] += (additive?0:NONADDITIVE_ERRORS);
        errcon->bind_number[n_items] = bind_number;
        errcon->sMin[n_items] = sMin;
        errcon->sMax[n_items] = sMax;
        errcon->boundTo[n_items] = -1;  /* not used when there are no wildcards */

        errcon->elem_type[n_items] = context->type;
        if ((errcon->param_number[n_items] = confirm_parameter(item, context->type))<0) {
            fprintf(stdout, "error: cannot vary %s--no such parameter for %s\n",item, name);
            fflush(stdout);
            exitElegant(1);
            }
        cp_str(&errcon->quan_unit[n_items], 
            errcon->flags[n_items]&FRACTIONAL_ERRORS?"fr":
            entity_description[errcon->elem_type[n_items]].parameter[errcon->param_number[n_items]].unit
            );
        errcon->unperturbed_value[n_items] 
            = parameter_value(errcon->name[n_items], errcon->elem_type[n_items], errcon->param_number[n_items],
                        beamline);
        if (errcon->unperturbed_value[n_items]==0 && errcon->flags[n_items]&FRACTIONAL_ERRORS)
            fprintf(stdout, "***\7\7\7 warning: you've specified fractional errors for %s.%s, but the unperturbed value is zero.\nThis may be an error.\n", 
                errcon->name[n_items], errcon->item[n_items]);
            fflush(stdout);

        if (duplicate_name(errcon->quan_name, n_items, errcon->quan_name[n_items]))
            fprintf(stdout, "***\7\7\7 warning: you've specified errors for %s.%s more than once!\n",
                errcon->name[n_items], errcon->item[n_items]);
            fflush(stdout);
        errcon->n_items = ++n_items;
        n_added++;
        }

    if (!n_added && !allow_missing_elements) {
        fprintf(stdout, "error: no match for name %s\n", name);
        fflush(stdout);
        exitElegant(1);
        }
    log_exit("add_error_element");
    }
Beispiel #25
0
int main(int argc, char **argv)
{
  int iArg;
  char *indepQuantity, **depenQuantity, *fileValuesQuantity, *fileValuesFile, **exclude;
  long depenQuantities, monotonicity, excludes;
  char *input, *output;
  long i, j, rows, readCode, order, valuesReadCode, fillIn, row;
  long sequencePoints, combineDuplicates, branch;
  int32_t *rowFlag;
  double sequenceStart, sequenceEnd;
  double sequenceSpacing;
  unsigned long flags, interpCode, printFlags, forceMonotonic;
  SCANNED_ARG *scanned;
  SDDS_DATASET SDDSin, SDDSout, SDDSvalues;
  OUTRANGE_CONTROL aboveRange, belowRange;
  double *atValue;
  long atValues, interpPoints, doNotRead, parallelPages;
  double *indepValue, **depenValue, *interpPoint, **outputData;
  unsigned long pipeFlags;
  FILE *fpPrint;
  short interpShort=0, interpShortOrder=-1, *shortValue=NULL;
  long nextPos;

  SDDS_RegisterProgramName(argv[0]);
  argc = scanargs(&scanned, argc, argv); 
  if (argc<3 || argc>(3+CLO_OPTIONS)) 
    bomb(NULL, USAGE);

  atValue = NULL;
  atValues = fillIn = 0;
  output = input = NULL;
  combineDuplicates = branch = sequencePoints = parallelPages = 0;
  indepQuantity = NULL;
  depenQuantity = exclude = NULL;
  depenQuantities = excludes = 0;
  aboveRange.flags = belowRange.flags = OUTRANGE_SATURATE;
  order = 1;
  readCode = interpPoints = 0;
  fileValuesFile = fileValuesQuantity = NULL;
  sequenceStart = sequenceEnd = sequenceSpacing = 0;
  printFlags = pipeFlags = 0;
  forceMonotonic = 0;
  indepValue = interpPoint = NULL;
  depenValue = outputData = NULL;

  for (iArg=1; iArg<argc; iArg++) {
    if (scanned[iArg].arg_type==OPTION) {
      /* process options here */
      switch (match_string(scanned[iArg].list[0], option, CLO_OPTIONS, 0)) {
      case CLO_ORDER:
        if (scanned[iArg].n_items!=2 || sscanf(scanned[iArg].list[1], "%ld", &order)!=1 ||
            order<1)
          SDDS_Bomb("invalid -order syntax/value");
        break;
      case CLO_ATVALUES:
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -atValues syntax");
        if (atValue)
          SDDS_Bomb("give -atValues only once");
        atValue = tmalloc(sizeof(*atValue)*(atValues=scanned[iArg].n_items-1));
        for (i=0; i<atValues; i++)
          if (sscanf(scanned[iArg].list[i+1], "%lf", &atValue[i])!=1)
            SDDS_Bomb("invalid -atValues value");
        break;
      case CLO_INTERP_SHORT:
        if (scanned[iArg].n_items==2) {
          if (sscanf(scanned[iArg].list[1], "%hd", &interpShortOrder)!=1)
            SDDS_Bomb("invalid -interpShort value");
        }
        interpShort = 1;
        break;
      case CLO_SEQUENCE:
        if ((scanned[iArg].n_items!=2 && scanned[iArg].n_items!=4) ||
            sscanf(scanned[iArg].list[1], "%ld", &sequencePoints)!=1 || sequencePoints<2)
          SDDS_Bomb("invalid -sequence syntax/value");
        if (scanned[iArg].n_items==4 &&
            (sscanf(scanned[iArg].list[2], "%lf", &sequenceStart)!=1 ||
             sscanf(scanned[iArg].list[3], "%lf", &sequenceEnd)!=1))
          SDDS_Bomb("invalid -sequence syntax/value");
        if (sequenceSpacing)
          SDDS_Bomb("give only one of -sequence and -equispaced");
        break;
      case CLO_EQUISPACED:
        if ((scanned[iArg].n_items!=2 && scanned[iArg].n_items!=4) ||
            sscanf(scanned[iArg].list[1], "%lf", &sequenceSpacing)!=1 || sequenceSpacing<=0)
          SDDS_Bomb("invalid -equispaced syntax/value");
        if (scanned[iArg].n_items==4 &&
            (sscanf(scanned[iArg].list[2], "%lf", &sequenceStart)!=1 ||
             sscanf(scanned[iArg].list[3], "%lf", &sequenceEnd)!=1))
          SDDS_Bomb("invalid -equispaced syntax/values");
        if (sequencePoints)
          SDDS_Bomb("give only one of -sequence and -equispaced");
        break;
      case CLO_COLUMNS:
        if (indepQuantity)
          SDDS_Bomb("only one -columns option may be given");
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -columns syntax");
        indepQuantity = scanned[iArg].list[1];
        if (scanned[iArg].n_items>=2) {
          depenQuantity = tmalloc(sizeof(*depenQuantity)*(depenQuantities=scanned[iArg].n_items-2));
          for (i=0; i<depenQuantities; i++)
            depenQuantity[i] = scanned[iArg].list[i+2];
        }
        break;
      case CLO_PRINTOUT:
        if ((scanned[iArg].n_items-=1)>=1) {
          if (!scanItemList(&printFlags, scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                            "bare", -1, NULL, 0, BARE_PRINTOUT,
                            "stdout", -1, NULL, 0, STDOUT_PRINTOUT,
                            NULL)) 
            SDDS_Bomb("invalid -printout syntax");
        }
        if (!(printFlags&BARE_PRINTOUT))
          printFlags |= NORMAL_PRINTOUT;
        break;
      case CLO_FILEVALUES:
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -fileValues syntax");
        fileValuesFile = scanned[iArg].list[1];
        scanned[iArg].n_items -= 2;
        if (!scanItemList(&flags, scanned[iArg].list+2, &scanned[iArg].n_items, 0,
                          "column", SDDS_STRING, &fileValuesQuantity, 1, 0,
                          "parallelpages", -1, NULL, 0, FILEVALUES_PARALLEL_PAGES,
                          NULL))
          SDDS_Bomb("invalid -fileValues syntax");
        if (flags&FILEVALUES_PARALLEL_PAGES)
          parallelPages = 1;
        break;
      case CLO_COMBINEDUPLICATES:
        SDDS_Bomb("-combineDuplicates option not implemented yet--send email to [email protected]");
        combineDuplicates = 1;
        break;
      case CLO_BRANCH:
        SDDS_Bomb("-branch option not implemented yet--send email to [email protected]");
        if (scanned[iArg].n_items!=2 || sscanf(scanned[iArg].list[1], "%ld", &branch)!=1 ||
            branch<1)
          SDDS_Bomb("invalid -branch syntax/value");
        break;
      case CLO_BELOWRANGE:
        if ((scanned[iArg].n_items-=1)<1 ||
            !scanItemList(&belowRange.flags, scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                          "value", SDDS_DOUBLE, &belowRange.value, 1, OUTRANGE_VALUE,
                          "skip", -1, NULL, 0, OUTRANGE_SKIP,
                          "saturate", -1, NULL, 0, OUTRANGE_SATURATE,
                          "extrapolate", -1, NULL, 0, OUTRANGE_EXTRAPOLATE,
                          "wrap", -1, NULL, 0, OUTRANGE_WRAP,
                          "abort", -1, NULL, 0, OUTRANGE_ABORT,
                          "warn", -1, NULL, 0, OUTRANGE_WARN,
                          NULL))
          SDDS_Bomb("invalid -belowRange syntax/value");
        if ((i=bitsSet(belowRange.flags&
                       (OUTRANGE_VALUE|OUTRANGE_SKIP|OUTRANGE_SATURATE|OUTRANGE_EXTRAPOLATE|OUTRANGE_WRAP|OUTRANGE_ABORT)))>1)
          SDDS_Bomb("incompatible keywords given for -belowRange");
        if (i!=1)
          belowRange.flags |= OUTRANGE_SATURATE;
        break;
      case CLO_ABOVERANGE:
        if ((scanned[iArg].n_items-=1)<1 ||
            !scanItemList(&aboveRange.flags, scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                          "value", SDDS_DOUBLE, &aboveRange.value, 1, OUTRANGE_VALUE,
                          "skip", -1, NULL, 0, OUTRANGE_SKIP,
                          "saturate", -1, NULL, 0, OUTRANGE_SATURATE,
                          "extrapolate", -1, NULL, 0, OUTRANGE_EXTRAPOLATE,
                          "wrap", -1, NULL, 0, OUTRANGE_WRAP,
                          "abort", -1, NULL, 0, OUTRANGE_ABORT,
                          "warn", -1, NULL, 0, OUTRANGE_WARN,
                          NULL))
          SDDS_Bomb("invalid -aboveRange syntax/value");
        if ((i=bitsSet(aboveRange.flags&
                       (OUTRANGE_VALUE|OUTRANGE_SKIP|OUTRANGE_SATURATE|OUTRANGE_EXTRAPOLATE|OUTRANGE_WRAP|OUTRANGE_ABORT)))>1)
          SDDS_Bomb("incompatible keywords given for -aboveRange");
        if (i!=1)
          aboveRange.flags |= OUTRANGE_SATURATE;
        break;
      case CLO_PIPE:
        if (!processPipeOption(scanned[iArg].list+1, scanned[iArg].n_items-1, &pipeFlags))
          SDDS_Bomb("invalid -pipe syntax");
        break;
      case CLO_EXCLUDE:
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -exclude syntax");
        moveToStringArray(&exclude, &excludes, scanned[iArg].list+1, scanned[iArg].n_items-1);
        break;
      case CLO_FORCEMONOTONIC:
        if ((scanned[iArg].n_items-=1)>0) {
          if (!scanItemList(&forceMonotonic, scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                            "increasing", -1, NULL, 0, FORCE_INCREASING,
                            "decreasing", -1, NULL, 0, FORCE_DECREASING,
                            NULL) || bitsSet(forceMonotonic)!=1)
            SDDS_Bomb("invalid -forceMonotonic syntax/value");
        }
        else 
          forceMonotonic = FORCE_MONOTONIC;
        break;
      case CLO_FILLIN:
        fillIn = 1;
        break;
      default:
        fprintf(stderr, "error: unknown/ambiguous option: %s\n", 
                scanned[iArg].list[0]);
        exit(1);
        break;
      }
    }
    else {
      if (!input)
        input = scanned[iArg].list[0];
      else if (!output)
        output = scanned[iArg].list[0];
      else
        SDDS_Bomb("too many filenames seen");
    }
  }

  processFilenames("sddsinterp", &input, &output, pipeFlags, 0, NULL);

  fpPrint = stderr;
  if (printFlags&STDOUT_PRINTOUT)
    fpPrint = stdout;

  if (!indepQuantity)
    SDDS_Bomb("supply the independent quantity name with the -columns option");

  if ((atValues?1:0)+(fileValuesFile?1:0)+(sequencePoints?1:0)+fillIn+(sequenceSpacing>0?1:0) != 1)
    SDDS_Bomb("you must give one and only one of -atValues, -fileValues, -sequence, -equispaced, and -fillIn");

  if (!SDDS_InitializeInput(&SDDSin, input))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  excludes = appendToStringArray(&exclude, excludes, indepQuantity);
  if (!depenQuantities)
    depenQuantities = appendToStringArray(&depenQuantity, depenQuantities, "*"); 

  if ((depenQuantities=expandColumnPairNames(&SDDSin, &depenQuantity, NULL, depenQuantities, 
                                             exclude, excludes, FIND_NUMERIC_TYPE, 0))<=0) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    SDDS_Bomb("no dependent quantities selected for interpolation");
  }

  if (fileValuesFile && !SDDS_InitializeInput(&SDDSvalues, fileValuesFile))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  if (!SDDS_InitializeOutput(&SDDSout, SDDS_BINARY, 0, NULL, "sddsinterp output", output))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  if (!SDDS_TransferColumnDefinition(&SDDSout, &SDDSin, indepQuantity, NULL))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  /*
    if (fileValuesQuantity && strcmp(fileValuesQuantity, indepQuantity)!=0 &&
    !SDDS_TransferColumnDefinition(&SDDSout, &SDDSvalues, fileValuesQuantity, NULL)) {
    fprintf(stderr, "problem creating -fileValues column %s\n", fileValuesQuantity);
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    */
  if (SDDS_DefineParameter(&SDDSout, "InterpDataPage", NULL, NULL, 
                           "Page of interpolation data file used to create this page",
                           NULL, SDDS_LONG, NULL)<0 ||
      SDDS_DefineParameter(&SDDSout, "InterpPointsPage", NULL, NULL, 
                           "Page of interpolation points file used to create this page",
                           NULL, SDDS_LONG, NULL)<0)
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  for (i=0; i<depenQuantities; i++) 
    if (!SDDS_TransferColumnDefinition(&SDDSout, &SDDSin, depenQuantity[i], NULL)) {
      fprintf(stderr, "problem creating interpolated-output column %s\n", depenQuantity[i]);
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
  if (!SDDS_TransferAllParameterDefinitions(&SDDSout, &SDDSin, SDDS_TRANSFER_KEEPOLD) ||
      !SDDS_WriteLayout(&SDDSout))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  doNotRead = 0;
  interpPoint = NULL;
  outputData = tmalloc(sizeof(*outputData)*(depenQuantities));
  depenValue = tmalloc(sizeof(*depenValue)*(depenQuantities));
  rowFlag = NULL;
  valuesReadCode = 0;

  while (doNotRead || (readCode=SDDS_ReadPage(&SDDSin))>0) {
    rows = SDDS_CountRowsOfInterest(&SDDSin);
    if (!(indepValue = SDDS_GetColumnInDoubles(&SDDSin, indepQuantity)))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (atValues) {
      interpPoint = atValue;
      interpPoints = atValues;
    }
    else if (fileValuesFile) {
      if (interpPoint)
        free(interpPoint);
      if ((valuesReadCode=SDDS_ReadPage(&SDDSvalues))==0)
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      else if (valuesReadCode==-1) {
        if (parallelPages) {
          fprintf(stderr, "warning: file %s ends before file %s\n", fileValuesFile, input);
          break;
        }
        else {
          /* "rewind" the values file */
          if (!SDDS_Terminate(&SDDSvalues) ||
              !SDDS_InitializeInput(&SDDSvalues, fileValuesFile))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          if ((valuesReadCode=SDDS_ReadPage(&SDDSvalues))<1) {
            fprintf(stderr, "error: unable to (re)read file %s\n", fileValuesFile);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
            exit(1);
          }
          /* read the next page of the interpolation data file */
          if ((readCode=SDDS_ReadPage(&SDDSin))<1) {
            if (readCode==-1)
              break;
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          rows = SDDS_CountRowsOfInterest(&SDDSin);
          if (indepValue)
            free(indepValue);
          if (!(indepValue = SDDS_GetColumnInDoubles(&SDDSin, indepQuantity)))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }
      
      if (!parallelPages)
        doNotRead = 1;
      interpPoints = SDDS_CountRowsOfInterest(&SDDSvalues);
      interpPoint = SDDS_GetColumnInDoubles(&SDDSvalues, fileValuesQuantity);
      if (SDDS_NumberOfErrors())
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    else if (sequencePoints || sequenceSpacing) {
      if (interpPoint)
        free(interpPoint);
      interpPoints = sequencePoints;
      if (!(interpPoint = makeSequence(&interpPoints, sequenceStart, sequenceEnd, sequenceSpacing, 
                                       indepValue, rows)))
        exit(1);
    } else {
      /* fillIn interpolation */
      if (interpPoint)
        free(interpPoint);
      if (!(interpPoint = makeFillInSequence(indepValue, rows, &interpPoints)))
        exit(1);
    }
    
    for (i=0; i<depenQuantities; i++)
      outputData[i] = tmalloc(sizeof(*outputData[i])*interpPoints);
    rowFlag = trealloc(rowFlag, sizeof(*rowFlag)*interpPoints);
    for (j=0; j<interpPoints; j++)
      rowFlag[j] = 1;
    for (i=0; i<depenQuantities; i++) {
      if (!(depenValue[i] = SDDS_GetColumnInDoubles(&SDDSin, depenQuantity[i])))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    if (forceMonotonic)
      rows = forceMonotonicity(indepValue, depenValue, depenQuantities, rows, forceMonotonic);
    else if (combineDuplicates)
      rows = combineDuplicatePoints(indepValue, depenValue, depenQuantities, rows, 0.0);
    if ((monotonicity=checkMonotonicity(indepValue, rows))==0)
      SDDS_Bomb("independent data values do not change monotonically or repeated independent values exist");
    if (interpShort)
      shortValue = malloc(sizeof(*shortValue)*rows);
    
    for (i=0; i<depenQuantities; i++) {
      if (interpShort) {
        for (row=0; row<rows; row++) {
          shortValue[row] = (short)depenValue[i][row];
        }
      }
      for (j=0; j<interpPoints; j++) {
        if (!interpShort) {
          outputData[i][j] = interpolate(depenValue[i], indepValue, rows, interpPoint[j], &belowRange,
                                         &aboveRange, order, &interpCode, monotonicity);
        } else {
          outputData[i][j] = (double)interp_short(shortValue, indepValue, rows, interpPoint[j], 0, -1,
                                                  &interpCode, &nextPos);
        }
        if (interpCode) {
          if (interpCode&OUTRANGE_ABORT) {
            fprintf(stderr, "error: value %e is out of range for column %s\n",
                    interpPoint[j], depenQuantity[i]);
            exit(1);
          }
          if (interpCode&OUTRANGE_WARN)
            fprintf(stderr, "warning: value %e is out of range for column %s\n",
                    interpPoint[j], depenQuantity[i]);
          if (interpCode&OUTRANGE_SKIP) 
            rowFlag[j] = 0;
        }
      }
    }
    if (interpShort)
      free(shortValue);
    if (!SDDS_StartPage(&SDDSout, interpPoints) || 
        !SDDS_SetColumnFromDoubles(&SDDSout, SDDS_SET_BY_NAME, interpPoint, interpPoints, indepQuantity))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (!SDDS_SetParameters(&SDDSout, SDDS_BY_NAME|SDDS_PASS_BY_VALUE,
                            "InterpDataPage", readCode,
                            "InterpPointsPage", valuesReadCode, NULL) ||
        !SDDS_CopyParameters(&SDDSout, &SDDSin))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    for (i=0; i<depenQuantities; i++)
      if (!SDDS_SetColumnFromDoubles(&SDDSout, SDDS_SET_BY_NAME, outputData[i], interpPoints, depenQuantity[i]))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (!SDDS_AssertRowFlags(&SDDSout, SDDS_FLAG_ARRAY, rowFlag, rows) || !SDDS_WritePage(&SDDSout))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (printFlags&BARE_PRINTOUT) {
      for (j=0; j<interpPoints; j++)
        if (rowFlag[j]) {
          fprintf(fpPrint, "%21.15e ", interpPoint[j]);
          for (i=0; i<depenQuantities; i++)
            fprintf(fpPrint, "%21.15e ", outputData[i][j]);
          fputc('\n', fpPrint);
        }
    }
    else if (printFlags&NORMAL_PRINTOUT) {
      for (j=0; j<interpPoints; j++)
        if (rowFlag[j]) {
          fprintf(fpPrint, "%s=%21.15e ", indepQuantity, interpPoint[j]);
          for (i=0; i<depenQuantities; i++)
            fprintf(fpPrint, "%s=%21.15e ", depenQuantity[i], outputData[i][j]);
          fputc('\n', fpPrint);
        }
    }
    if (indepValue) free(indepValue);
    indepValue = NULL;
    for (i=0; i<depenQuantities; i++) {
      if (outputData[i]) free(outputData[i]);
      outputData[i] = NULL;
      if (depenValue[i]) free(depenValue[i]);
      depenValue[i] = NULL;
    }
    if (fileValuesFile) {
      if (interpPoint) free(interpPoint);
      interpPoint = NULL;
    }
    if (rowFlag) free(rowFlag);
    rowFlag = NULL;
  }

  if (!SDDS_Terminate(&SDDSin)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }
  if (!SDDS_Terminate(&SDDSout)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }
  if (fileValuesFile) {
    if (!SDDS_Terminate(&SDDSvalues)) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exit(1);
    }
  }

  return 0;
}
Beispiel #26
0
void add_element_links(ELEMENT_LINKS *links, NAMELIST_TEXT *nltext, LINE_LIST *beamline)
{
    long n_links, src_position_code=0, n_targets, n_sources, mode_code=0;
    long targets, iTarget, j;
    char **targetList;
    ELEMENT_LIST *t_context, *s_context, **eptr, *eptr1;
    double dz_min, dz;
#if DEBUG
    long i;
#endif

    log_entry("add_element_links");

    /* set namelist variables to defaults */
    target = item = source = equation = exclude = NULL;
    /* must initialize these hear rather than in the .nl file
     * to avoid problems with str_tolower() and other operations
     */
    cp_str(&source_position, "before");
    cp_str(&mode, "dynamic");

    /* process namelist text */
    if (processNamelist(&link_elements, nltext)==NAMELIST_ERROR)
      bombElegant(NULL, NULL);
    if (target)          str_toupper(target);
    if (exclude)         str_toupper(exclude);
    if (item)            str_toupper(item);
    if (source)          str_toupper(source);
    if (source_position) 
      str_tolower(source_position);
    else
      cp_str(&source_position, "nearest");
    if (mode) 
      str_tolower(mode);
    else
      cp_str(&mode, "dynamic");
    if (echoNamelists) print_namelist(stdout, &link_elements);

    /* check for valid input */
    if (!target)
        bombElegant("link target not named", NULL);
    if (!item)
        bombElegant("link item not named", NULL);
    if (!source)
        bombElegant("link source not named", NULL);
    if (!equation)
        bombElegant("link equation not given", NULL);
    if (!source_position || (src_position_code=match_string(source_position, src_position_name, N_SRC_POSITIONS, 0))<0)
        bombElegant("source_position not given/unknown", NULL);
    if (!mode || (mode_code=match_string(mode, link_mode, N_LINK_MODES, 0))<0)
        bombElegant("link mode not known", NULL);
    if (minimum>maximum)
      bombElegant("minimum>maximum", NULL);
    
    t_context = s_context = NULL;

    if (has_wildcards(target) && strchr(target, '-'))
      target = expand_ranges(target);
    if (exclude && strlen(exclude) && has_wildcards(exclude) && strchr(exclude, '-'))
      exclude = expand_ranges(exclude);
    
    if (!(t_context=wfind_element(target, &t_context, &(beamline->elem)))) {
      fprintf(stdout, "error: cannot make link with target element %s--not in beamline\n", target);
      fflush(stdout);
      exitElegant(1);
    }
    if (!(s_context=find_element(source, &s_context, &(beamline->elem)))) {
      fprintf(stdout, "error: cannot make link with source element %s--not in beamline\n", source);
      fflush(stdout);
      exitElegant(1);
    }

    targets = 0;
    targetList = NULL;
    /* make a list of all the unique element names that match this (possibly wildcard) target */
    do {
      int32_t duplic;
      if (!exclude || !strlen(exclude) || !wild_match(t_context->name, exclude)) {
        targetList = SDDS_Realloc(targetList, sizeof(*targetList)*(targets+1));
        binaryInsert((void**)targetList, targets, t_context->name, strcmp, &duplic);
        if (!duplic)
          targets++;
      }
    } while ((t_context=wfind_element(target, &t_context, &(beamline->elem))));
    if (!targets)
      bombElegant("cannot make link--no targets found\n", NULL);
      
    /* note that targets==1 if all the targets have the same name ! */
    for (iTarget=0; iTarget<targets; iTarget++) {
      n_links = links->n_links;
      target = targetList[iTarget];
      t_context = NULL;
      t_context = find_element(target, &t_context, &(beamline->elem));

      /* expand the arrays */
      links->target_name     = trealloc(links->target_name, sizeof(*links->target_name)*(n_links+1));
      links->target_elem     = trealloc(links->target_elem, sizeof(*links->target_elem)*(n_links+1));
      links->item            = trealloc(links->item, sizeof(*links->item)*(n_links+1));
      links->target_param    = trealloc(links->target_param, sizeof(*links->target_param)*(n_links+1));
      links->source_name     = trealloc(links->source_name, sizeof(*links->source_name)*(n_links+1));
      links->source_position = trealloc(links->source_position, sizeof(*links->source_position)*(n_links+1));
      links->flags           = trealloc(links->flags, sizeof(*links->flags)*(n_links+1));
      links->source_elem     = trealloc(links->source_elem, sizeof(*links->source_elem)*(n_links+1));
      links->equation        = trealloc(links->equation, sizeof(*links->equation)*(n_links+1));
      links->n_targets       = trealloc(links->n_targets, sizeof(*links->n_targets)*(n_links+1));
      links->initial_value   = trealloc(links->initial_value, sizeof(*links->initial_value)*(n_links+1));
      links->baseline_value  = trealloc(links->baseline_value, sizeof(*links->baseline_value)*(n_links+1));
      links->minimum   = trealloc(links->minimum, sizeof(*links->minimum)*(n_links+1));
      links->maximum   = trealloc(links->maximum, sizeof(*links->maximum)*(n_links+1));

      /* copy the basic data */
      cp_str(links->target_name+n_links, target);
      cp_str(links->item+n_links, item);
      cp_str(links->source_name+n_links, source);
      cp_str(links->equation+n_links, equation);
      links->source_position[n_links] = src_position_code;
      links->flags[n_links] = link_mode_flag[mode_code];
      links->minimum[n_links] = minimum;
      links->maximum[n_links] = maximum;
      
      /* make the list of pointers to targets */
      eptr = tmalloc(sizeof(*eptr));
      eptr[0] = t_context;
      if ((links->target_param[n_links] = confirm_parameter(item, t_context->type))<0) {
        fprintf(stdout, "error: element %s does not have a parameter %s\n", target, item);
        fflush(stdout);
        exitElegant(1);
      }
      n_targets = 1;
      while ((t_context=find_element(target, &t_context, &(beamline->elem)))) {
        eptr = trealloc(eptr, sizeof(*eptr)*(n_targets+1));
        eptr[n_targets] = t_context;
        n_targets++;
      }
      links->baseline_value[n_links] = tmalloc(sizeof(*links->baseline_value[n_links])*n_targets);
      links->n_targets[n_links] = n_targets;
      links->target_elem[n_links] = eptr;
      t_context = links->target_elem[n_links][0];
      switch (entity_description[eptr[0]->type].parameter[links->target_param[n_links]].type) {
      case IS_DOUBLE:
        links->initial_value[n_links] = 
          *((double*)(eptr[0]->p_elem+entity_description[eptr[0]->type].parameter[links->target_param[n_links]].offset));
        break;
      case IS_LONG:
        links->initial_value[n_links] = 
          *((long*)(eptr[0]->p_elem+entity_description[eptr[0]->type].parameter[links->target_param[n_links]].offset));
        break;
      default:
        bombElegant("invalid type of item for target of link", NULL);
        break;
      }
      for (j=0; j<n_targets; j++)
        links->baseline_value[n_links][j] = links->initial_value[n_links];

      /* make the list of pointers to sources */
      if (iTarget) {
        s_context = NULL;
        if (!(s_context=find_element(source, &s_context, &(beamline->elem)))) {
          fprintf(stdout, "error: cannot make link with source element %s--not in beamline\n", source);
          fflush(stdout);
          exitElegant(1);
        }
      }
      eptr = tmalloc(sizeof(*eptr)*(n_targets));
      if (src_position_code==SRC_POSITION_SAME_OCCURENCE) {
        n_sources = 0;
        while (n_sources<n_targets) {
          eptr1 = NULL;
          s_context = NULL;
          while (find_element(source, &s_context, &(beamline->elem))) {
            if (s_context->occurence==links->target_elem[n_links][n_sources]->occurence) {
              eptr1 = s_context;
              break;
            }
          }
          if (!eptr1) {
            fprintf(stdout, "error: no %s element is found with the same occurence number as the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = eptr1;
        }
      }
      else if (src_position_code==SRC_POSITION_NEAREST) {
        n_sources = 0;
        while (n_sources<n_targets) {
          dz_min = DBL_MAX;
          eptr1 = NULL;
          s_context = NULL;
          while (find_element(source, &s_context, &(beamline->elem))) {
            if ((dz = fabs(s_context->end_pos-links->target_elem[n_links][n_sources]->end_pos))<dz_min) {
              eptr1 = s_context;
              dz_min = dz;
            }
          }
          if (!eptr1) {
            fprintf(stdout, "error: no %s element is found near the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = eptr1;
        }
      }
      else if (src_position_code==SRC_POSITION_ADJACENT) {
        n_sources = 0;
        while (n_sources<n_targets) {
          eptr1 = NULL;
          if ((eptr1=links->target_elem[n_links][n_sources]->pred)) {
            if (strcmp(eptr1->name, source)!=0)
              eptr1 = NULL;
          }
          if (!eptr1 && (eptr1=links->target_elem[n_links][n_sources]->succ)) {
            if (strcmp(eptr1->name, source)!=0)
              eptr1 = NULL;
          }
          if (!eptr1) {
            fprintf(stdout, "error: no %s element is found adjacent to the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = eptr1;
        }
      }
      else if (src_position_code==SRC_POSITION_BEFORE) {
        if (links->target_elem[n_links][0]->end_pos<s_context->end_pos) {
          fprintf(stdout, "error: there is no %s element before the first %s element--can't link as requested\n",
                  source, target);
          fflush(stdout);
          exitElegant(1);
        }
        eptr[0] = s_context;
        n_sources = 0;
        while (n_sources<n_targets) {
          eptr1 = NULL;
          do {
            if (s_context->end_pos<links->target_elem[n_links][n_sources]->end_pos)
              eptr1 = s_context;
            else if (s_context->end_pos==links->target_elem[n_links][n_sources]->end_pos) {
              eptr1 = s_context;
              break;
            }
            else
              break;
          } while (find_element(source, &s_context, &(beamline->elem)));
          if (!eptr1) {
            fprintf(stdout, "error: no %s element is found before the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = eptr1;
          s_context = eptr[n_sources-1];
        }
      }
      else if (src_position_code==SRC_POSITION_AFTER) {
        if (links->target_elem[n_links][0]->end_pos>=s_context->end_pos) {
          /* search for first source element after first target element */
          while (find_element(source, &s_context, &(beamline->elem))) {
            if (links->target_elem[n_links][0]->end_pos<s_context->end_pos)
              break;
          }
          if (!s_context) {
            fprintf(stdout, "error: no %s element after the first %s element--can't link as requested\n",
                    source, target);
            fflush(stdout);
            exitElegant(1);
          }
        }
        eptr[0] = s_context;
        n_sources = 1;
        while (n_sources<n_targets) {
          s_context = links->target_elem[n_links][n_sources-1];
          while (find_element(source, &s_context, &(beamline->elem))) {
            if (s_context->end_pos>links->target_elem[n_links][n_sources]->end_pos)
              break;
          }
          if (!s_context) {
            fprintf(stdout, "error: no %s element is found after the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = s_context;
        }
      }

      links->source_elem[n_links] = eptr;

#if DEBUG
      fprintf(stdout, "list of targets and sources:\n");
      fflush(stdout);
      for (i=0; i<n_targets; i++)
        fprintf(stdout, "%s at z=%em linked to %s at z=%em\n", 
                links->target_elem[n_links][i]->name, links->target_elem[n_links][i]->end_pos,
                links->source_elem[n_links][i]->name, links->source_elem[n_links][i]->end_pos);
      fflush(stdout);
#endif

      links->n_links += 1;
    }
    
    log_exit("add_element_links");
    }
Beispiel #27
0
int
CKTnoise (CKTcircuit *ckt, int mode, int operation, Ndata *data)
{
    double outNdens;
    int i;
    extern SPICEdev **DEVices;
    IFvalue outData;    /* output variable (points to list of outputs)*/
    IFvalue refVal; /* reference variable (always 0)*/
    int error;

    outNdens = 0.0;

    /* let each device decide how many and what type of noise sources it has */

    for (i=0; i < DEVmaxnum; i++) {
        if ( DEVices[i] && ((*DEVices[i]).DEVnoise != NULL) && (ckt->CKThead[i] != NULL) ) {
            error = (*((*DEVices[i]).DEVnoise))(mode,operation,ckt->CKThead[i],
                                                ckt,data, &outNdens);
            if (error) return (error);
        }
    }

    switch (operation) {

    case N_OPEN:

        /* take care of the noise for the circuit as a whole */

        switch (mode) {

        case N_DENS:

            data->namelist = (IFuid *)trealloc((char *)data->namelist,
                                               (data->numPlots + 1)*sizeof(IFuid));

            (*(SPfrontEnd->IFnewUid))(ckt, &(data->namelist[data->numPlots++]),
                                      (IFuid)NULL,"onoise_spectrum",UID_OTHER,(void **)NULL);

            data->namelist = (IFuid *)trealloc((char *)data->namelist,
                                               (data->numPlots + 1)*sizeof(IFuid));

            (*(SPfrontEnd->IFnewUid))(ckt, &(data->namelist[data->numPlots++]),
                                      (IFuid)NULL,"inoise_spectrum",UID_OTHER,(void **)NULL);

            /* we've added two more plots */

            data->outpVector =
                (double *)MALLOC(data->numPlots * sizeof(double));
            break;

        case INT_NOIZ:

            data->namelist = (IFuid *)trealloc((char *)data->namelist,
                                               (data->numPlots + 1)*sizeof(IFuid));
            (*(SPfrontEnd->IFnewUid))(ckt, &(data->namelist[data->numPlots++]),
                                      (IFuid)NULL,"onoise_total",UID_OTHER,(void **)NULL);

            data->namelist = (IFuid *)trealloc((char *)data->namelist,
                                               (data->numPlots + 1)*sizeof(IFuid));
            (*(SPfrontEnd->IFnewUid))(ckt, &(data->namelist[data->numPlots++]),
                                      (IFuid)NULL,"inoise_total",UID_OTHER,(void **)NULL);
            /* we've added two more plots */

            data->outpVector =
                (double *) MALLOC(data->numPlots * sizeof(double));
            break;

        default:
            return (E_INTERN);
        }

        break;

    case N_CALC:

        switch (mode) {

        case N_DENS:
            if ((((NOISEAN*)ckt->CKTcurJob)->NStpsSm == 0)
                    || data->prtSummary)
            {
                data->outpVector[data->outNumber++] = outNdens;
                data->outpVector[data->outNumber++] =
                    (outNdens * data->GainSqInv);

                refVal.rValue = data->freq; /* the reference is the freq */
                outData.v.numValue = data->outNumber; /* vector number */
                outData.v.vec.rVec = data->outpVector; /* vector of outputs */
                (*(SPfrontEnd->OUTpData))(data->NplotPtr,&refVal,&outData);
            }
            break;

        case INT_NOIZ:
            data->outpVector[data->outNumber++] =  data->outNoiz;
            data->outpVector[data->outNumber++] =  data->inNoise;
            outData.v.vec.rVec = data->outpVector; /* vector of outputs */
            outData.v.numValue = data->outNumber; /* vector number */
            (*(SPfrontEnd->OUTpData))(data->NplotPtr,&refVal,&outData);
            break;

        default:
            return (E_INTERN);
        }
        break;

    case N_CLOSE:
        (*(SPfrontEnd->OUTendPlot))(data->NplotPtr);
        FREE(data->namelist);
        FREE(data->outpVector);
        break;

    default:
        return (E_INTERN);
    }
    return (OK);
}
Beispiel #28
0
int
BSIM3v0noise (int mode, int operation, GENmodel *inModel, CKTcircuit *ckt, 
              Ndata *data, double *OnDens)
{
BSIM3v0model *model = (BSIM3v0model *)inModel;
BSIM3v0instance *here;
struct bsim3v0SizeDependParam *pParam;
char name[N_MXVLNTH];
double tempOnoise;
double tempInoise;
double noizDens[BSIM3v0NSRCS];
double lnNdens[BSIM3v0NSRCS];

double vgs, vds, Slimit;
double T1, T10, T11;
double Ssi, Swi;

int i;

    /* define the names of the noise sources */
    static char *BSIM3v0nNames[BSIM3v0NSRCS] =
    {   /* Note that we have to keep the order */
	".rd",              /* noise due to rd */
			    /* consistent with the index definitions */
	".rs",              /* noise due to rs */
			    /* in BSIM3v0defs.h */
	".id",              /* noise due to id */
	".1overf",          /* flicker (1/f) noise */
	""                  /* total transistor noise */
    };

    for (; model != NULL; model = model->BSIM3v0nextModel)
    {    for (here = model->BSIM3v0instances; here != NULL;
	      here = here->BSIM3v0nextInstance)
	 {    
	 
              if (here->BSIM3v0owner != ARCHme)
                      continue;

	      pParam = here->pParam;
	      switch (operation)
	      {  case N_OPEN:
		     /* see if we have to to produce a summary report */
		     /* if so, name all the noise generators */

		      if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0)
		      {   switch (mode)
			  {  case N_DENS:
			          for (i = 0; i < BSIM3v0NSRCS; i++)
				  {    (void) sprintf(name, "onoise.%s%s",
					              here->BSIM3v0name,
						      BSIM3v0nNames[i]);
                                       data->namelist = (IFuid *) trealloc(
					     (char *) data->namelist,
					     (data->numPlots + 1)
					     * sizeof(IFuid));
                                       if (!data->namelist)
					   return(E_NOMEM);
		                       (*(SPfrontEnd->IFnewUid)) (ckt,
			                  &(data->namelist[data->numPlots++]),
			                  (IFuid) NULL, name, UID_OTHER,
					  (void **) NULL);
				       /* we've added one more plot */
			          }
			          break;
		             case INT_NOIZ:
			          for (i = 0; i < BSIM3v0NSRCS; i++)
				  {    (void) sprintf(name, "onoise_total.%s%s",
						      here->BSIM3v0name,
						      BSIM3v0nNames[i]);
                                       data->namelist = (IFuid *) trealloc(
					     (char *) data->namelist,
					     (data->numPlots + 1)
					     * sizeof(IFuid));
                                       if (!data->namelist)
					   return(E_NOMEM);
		                       (*(SPfrontEnd->IFnewUid)) (ckt,
			                  &(data->namelist[data->numPlots++]),
			                  (IFuid) NULL, name, UID_OTHER,
					  (void **) NULL);
				       /* we've added one more plot */

			               (void) sprintf(name, "inoise_total.%s%s",
						      here->BSIM3v0name,
						      BSIM3v0nNames[i]);
                                       data->namelist = (IFuid *) trealloc(
					     (char *) data->namelist,
					     (data->numPlots + 1)
					     * sizeof(IFuid));
                                       if (!data->namelist)
					   return(E_NOMEM);
		                       (*(SPfrontEnd->IFnewUid)) (ckt,
			                  &(data->namelist[data->numPlots++]),
			                  (IFuid) NULL, name, UID_OTHER,
					  (void **)NULL);
				       /* we've added one more plot */
			          }
			          break;
		          }
		      }
		      break;
	         case N_CALC:
		      switch (mode)
		      {  case N_DENS:
		              NevalSrc(&noizDens[BSIM3v0RDNOIZ],
				       &lnNdens[BSIM3v0RDNOIZ], ckt, THERMNOISE,
				       here->BSIM3v0dNodePrime, here->BSIM3v0dNode,
				       here->BSIM3v0drainConductance * here->BSIM3v0m);

		              NevalSrc(&noizDens[BSIM3v0RSNOIZ],
				       &lnNdens[BSIM3v0RSNOIZ], ckt, THERMNOISE,
				       here->BSIM3v0sNodePrime, here->BSIM3v0sNode,
				       here->BSIM3v0sourceConductance * here->BSIM3v0m);

                              if (model->BSIM3v0noiMod == 2)
		              {   NevalSrc(&noizDens[BSIM3v0IDNOIZ],
				         &lnNdens[BSIM3v0IDNOIZ], ckt, THERMNOISE,
				         here->BSIM3v0dNodePrime,
                                         here->BSIM3v0sNodePrime, (here->BSIM3v0ueff
					 * fabs((here->BSIM3v0qinv * here->BSIM3v0m)
					 / (pParam->BSIM3v0leff
					 *  pParam->BSIM3v0leff))));
		              }
                              else
			      {   NevalSrc(&noizDens[BSIM3v0IDNOIZ],
				       &lnNdens[BSIM3v0IDNOIZ], ckt, THERMNOISE,
				       here->BSIM3v0dNodePrime,
				       here->BSIM3v0sNodePrime,
                                       (2.0 / 3.0 * fabs(here->BSIM3v0gm
				       + here->BSIM3v0gds) * here->BSIM3v0m));

			      }
		              NevalSrc(&noizDens[BSIM3v0FLNOIZ], (double*) NULL,
				       ckt, N_GAIN, here->BSIM3v0dNodePrime,
				       here->BSIM3v0sNodePrime, (double) 0.0);

                              if (model->BSIM3v0noiMod == 2)
			      {   vgs = *(ckt->CKTstates[0] + here->BSIM3v0vgs);
		                  vds = *(ckt->CKTstates[0] + here->BSIM3v0vds);
			          if (vds < 0.0)
			          {   vds = -vds;
				      vgs = vgs + vds;
			          }
                                  if (vgs >= here->BSIM3v0von + 0.1)
			          {   Ssi = StrongInversionNoiseEval(vgs, vds,
					    model, here, data->freq,
					    ckt->CKTtemp);
                                      noizDens[BSIM3v0FLNOIZ] *= Ssi;
			          }
                                  else 
			          {   pParam = here->pParam;
				      T10 = model->BSIM3v0oxideTrapDensityA
					  * 8.62e-5 * (ckt->CKTtemp + CONSTCtoK);
		                      T11 = pParam->BSIM3v0weff * here->BSIM3v0m * pParam->BSIM3v0leff
				          * pow(data->freq, model->BSIM3v0ef)
				          * 4.0e36;
		                      Swi = T10 / T11 * here->BSIM3v0cd * here->BSIM3v0m
				          * here->BSIM3v0cd * here->BSIM3v0m;
                                      Slimit = StrongInversionNoiseEval(
				           here->BSIM3v0von + 0.1,
				           vds, model, here,
				           data->freq, ckt->CKTtemp);
				      T1 = Swi + Slimit;
				      if (T1 > 0.0)
                                          noizDens[BSIM3v0FLNOIZ] *= (Slimit * Swi)
							        / T1; 
				      else
                                          noizDens[BSIM3v0FLNOIZ] *= 0.0;
			          }
		              }
                              else
			      {    noizDens[BSIM3v0FLNOIZ] *= model->BSIM3v0kf * 
				            exp(model->BSIM3v0af
					    * log(MAX(fabs(here->BSIM3v0cd * here->BSIM3v0m),
					    N_MINLOG)))
					    / (pow(data->freq, model->BSIM3v0ef)
					    * pParam->BSIM3v0leff
				            * pParam->BSIM3v0leff
					    * model->BSIM3v0cox);
			      }

		              lnNdens[BSIM3v0FLNOIZ] =
				     log(MAX(noizDens[BSIM3v0FLNOIZ], N_MINLOG));

		              noizDens[BSIM3v0TOTNOIZ] = noizDens[BSIM3v0RDNOIZ]
						     + noizDens[BSIM3v0RSNOIZ]
						     + noizDens[BSIM3v0IDNOIZ]
						     + noizDens[BSIM3v0FLNOIZ];
		              lnNdens[BSIM3v0TOTNOIZ] = 
				     log(MAX(noizDens[BSIM3v0TOTNOIZ], N_MINLOG));

		              *OnDens += noizDens[BSIM3v0TOTNOIZ];

		              if (data->delFreq == 0.0)
			      {   /* if we haven't done any previous 
				     integration, we need to initialize our
				     "history" variables.
				    */

			          for (i = 0; i < BSIM3v0NSRCS; i++)
				  {    here->BSIM3v0nVar[LNLSTDENS][i] =
					     lnNdens[i];
			          }

			          /* clear out our integration variables
				     if it's the first pass
				   */
			          if (data->freq ==
				      ((NOISEAN*) ckt->CKTcurJob)->NstartFreq)
				  {   for (i = 0; i < BSIM3v0NSRCS; i++)
				      {    here->BSIM3v0nVar[OUTNOIZ][i] = 0.0;
				           here->BSIM3v0nVar[INNOIZ][i] = 0.0;
			              }
			          }
		              }
			      else
			      {   /* data->delFreq != 0.0,
				     we have to integrate.
				   */
			          for (i = 0; i < BSIM3v0NSRCS; i++)
				  {    if (i != BSIM3v0TOTNOIZ)
				       {   tempOnoise = Nintegrate(noizDens[i],
						lnNdens[i],
				                here->BSIM3v0nVar[LNLSTDENS][i],
						data);
				           tempInoise = Nintegrate(noizDens[i]
						* data->GainSqInv, lnNdens[i]
						+ data->lnGainInv,
				                here->BSIM3v0nVar[LNLSTDENS][i]
						+ data->lnGainInv, data);
				           here->BSIM3v0nVar[LNLSTDENS][i] =
						lnNdens[i];
				           data->outNoiz += tempOnoise;
				           data->inNoise += tempInoise;
				           if (((NOISEAN*)
					       ckt->CKTcurJob)->NStpsSm != 0)
					   {   here->BSIM3v0nVar[OUTNOIZ][i]
						     += tempOnoise;
				               here->BSIM3v0nVar[OUTNOIZ][BSIM3v0TOTNOIZ]
						     += tempOnoise;
				               here->BSIM3v0nVar[INNOIZ][i]
						     += tempInoise;
				               here->BSIM3v0nVar[INNOIZ][BSIM3v0TOTNOIZ]
						     += tempInoise;
                                           }
			               }
			          }
		              }
		              if (data->prtSummary)
			      {   for (i = 0; i < BSIM3v0NSRCS; i++)
				  {    /* print a summary report */
			               data->outpVector[data->outNumber++]
					     = noizDens[i];
			          }
		              }
		              break;
		         case INT_NOIZ:
			      /* already calculated, just output */
		              if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0)
			      {   for (i = 0; i < BSIM3v0NSRCS; i++)
				  {    data->outpVector[data->outNumber++]
					     = here->BSIM3v0nVar[OUTNOIZ][i];
			               data->outpVector[data->outNumber++]
					     = here->BSIM3v0nVar[INNOIZ][i];
			          }
		              }
		              break;
		      }
		      break;
	         case N_CLOSE:
		      /* do nothing, the main calling routine will close */
		      return (OK);
		      break;   /* the plots */
	      }       /* switch (operation) */
	 }    /* for here */
    }    /* for model */

    return(OK);
}
Beispiel #29
0
int main(int argc, char **argv)
{
  FILE *fileID;
  COLUMN_DATA_STRUCTURES *columnValues;
  PARAMETER_DATA_STRUCTURES *parameterValues;

  SDDS_DATASET SDDS_dataset;
  SCANNED_ARG *s_arg;
  long i, j, k, n, i_arg;
  int32_t rows;
  int32_t maxRows=10000, initRows=10000, row;
  long par, col, page, size, readline=1, fillin=0;
  int32_t ptrSize=0;
  char *input, *output, s[1024], *ptr, *ptr2, data[10240],temp[10240];
  unsigned long pipeFlags=0,majorOrderFlag;
  long noWarnings=0, tmpfile_used=0, columnOrder=0, whitespace=1;
  short shortValue;
  int32_t longValue;
  float floatValue;
  double doubleValue;
  char stringValue[SDDS_MAXLINE];
  char characterValue;
  char buffer[124], buffer2[124];
  long *parameterIndex, *columnIndex;

  long binary=0, noRowCount=0, inputBinary=0, count=0;
  char separator;
  char commentCharacters[20];
  short checkComment=0;
  short commentFound;
  long parameters=0, columns=0;
  long skiplines=0;
  short abort=0, recover=1, columnMajorOrder=0;

  input = output = NULL;
  separator = ' ';
  columnValues = NULL;
  parameterValues = NULL;

  parameterIndex = columnIndex = NULL;

  SDDS_RegisterProgramName(argv[0]);
  argc = scanargs(&s_arg, argc, argv);
  if (argc<3) 
    bomb(NULL, USAGE);
  
  for (i_arg=1; i_arg<argc; i_arg++) {
    if (s_arg[i_arg].arg_type==OPTION) {
      switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
      case SET_MAJOR_ORDER:
        majorOrderFlag=0;
        s_arg[i_arg].n_items -=1;
        if (s_arg[i_arg].n_items>0 &&
            (!scanItemList(&majorOrderFlag, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0,
                           "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER,
                           "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER,
                            NULL)))
          SDDS_Bomb("invalid -majorOrder syntax/values");
        if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER)
          columnMajorOrder=1;
        else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER)
          columnMajorOrder=0;
        break;
      case SET_OUTPUTMODE:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -outputMode syntax");
	switch (match_string(s_arg[i_arg].list[1], mode_name, MODES, 0)) {
	case ASCII_MODE:
	  binary = 0;
	  break;
	case BINARY_MODE:
	  binary = 1;
	  break;
	default:
	  SDDS_Bomb("invalid -outputMode syntax");
	  break;
	}
	break;
      case SET_INPUTMODE:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -inputMode syntax");
	switch (match_string(s_arg[i_arg].list[1], mode_name, MODES, 0)) {
	case ASCII_MODE:
	  inputBinary = 0;
	  break;
	case BINARY_MODE:
	  inputBinary = 1;
	  break;
	default:
	  SDDS_Bomb("invalid -inputMode syntax");
	  break;
	}
	break;
      case SET_SEPARATOR:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -separator syntax");
	separator = s_arg[i_arg].list[1][0];
        whitespace = 0;
	break;
      case SET_COMMENT:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -commentCharacters syntax");
	sprintf(commentCharacters, "%s", s_arg[i_arg].list[1]);
        checkComment=1;
	break;
      case SET_FILLIN:
        fillin=1;
        break;
      case SET_NOROWCOUNT:
	if (s_arg[i_arg].n_items!=1)
	  SDDS_Bomb("invalid -noRowCount syntax");
	noRowCount = 1;
	break;
      case SET_ORDER:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -order syntax");
	switch (match_string(s_arg[i_arg].list[1], order_names, ORDERS, 0)) {
	case ROW_ORDER:
	  columnOrder = 0;
	  break;
	case COLUMN_ORDER:
	  columnOrder = 1;
	  break;
	default:
	  SDDS_Bomb("invalid -order syntax");
	  break;
	}
	break;
      case SET_PARAMETER:
	if (s_arg[i_arg].n_items<3)
	  SDDS_Bomb("invalid -parameter syntax");
        count=1;
	parameters++;
	parameterValues = trealloc(parameterValues, sizeof(*parameterValues)*(parameters));
        SDDS_CopyString(&parameterValues[parameters-1].name, s_arg[i_arg].list[1]);
	parameterValues[parameters-1].units = NULL;
	parameterValues[parameters-1].description = NULL;
	parameterValues[parameters-1].symbol = NULL;
	switch (match_string(s_arg[i_arg].list[2], type_name, DATATYPES, 0)) {
	case TYPE_SHORT:
	  parameterValues[parameters-1].type = SDDS_SHORT;
	  break;
	case TYPE_LONG:
	  parameterValues[parameters-1].type = SDDS_LONG;
	  break;
	case TYPE_FLOAT:
	  parameterValues[parameters-1].type = SDDS_FLOAT;
	  break;
	case TYPE_DOUBLE:
	  parameterValues[parameters-1].type = SDDS_DOUBLE;
	  break;
	case TYPE_STRING:
	  parameterValues[parameters-1].type = SDDS_STRING;
	  break;
	case TYPE_CHARACTER:
	  parameterValues[parameters-1].type = SDDS_CHARACTER;
	  break;
	default:
	  SDDS_Bomb("invalid -parameter type");
	  break;
	}
	for (i=3;i<s_arg[i_arg].n_items;i++) {
	  if (!(ptr=strchr(s_arg[i_arg].list[i], '=')))
	    SDDS_Bomb("invalid -parameter syntax");
	  *ptr++ = 0;	
	  switch (match_string(s_arg[i_arg].list[i], header_elements, HEADERELEMENTS, 0)) {
	  case HEADER_UNITS:
            SDDS_CopyString(&parameterValues[parameters-1].units, ptr);
	    break;
	  case HEADER_DESCRIPTION:
            SDDS_CopyString(&parameterValues[parameters-1].description, ptr);
	    break;
	  case HEADER_SYMBOL:
            SDDS_CopyString(&parameterValues[parameters-1].symbol, ptr);
	    break;
	  case HEADER_COUNT:
	    if (sscanf(ptr, "%ld", &count)!=1 ||
                count<=0)
              SDDS_Bomb("invalid parameter count value");
            sprintf(buffer, "%s", parameterValues[parameters-1].name);
            sprintf(buffer2, "%s1", buffer);
            free(parameterValues[parameters-1].name);
            SDDS_CopyString(&parameterValues[parameters-1].name, buffer2);
	    break;
	  default:
	    SDDS_Bomb("invalid -parameter syntax");
	    break;
	  } 
	}
        
        for (i=2;i<=count;i++) {
          parameters++;
          parameterValues = trealloc(parameterValues, sizeof(*parameterValues)*(parameters));
          sprintf(buffer2, "%s%ld", buffer, i);
          SDDS_CopyString(&parameterValues[parameters-1].name, buffer2);
          parameterValues[parameters-1].units = NULL;
          parameterValues[parameters-1].description = NULL;
          parameterValues[parameters-1].symbol = NULL;
          parameterValues[parameters-1].type = parameterValues[parameters-2].type;
          if (parameterValues[parameters-2].units)
            SDDS_CopyString(&parameterValues[parameters-1].units, parameterValues[parameters-2].units);
          if (parameterValues[parameters-2].description)
            SDDS_CopyString(&parameterValues[parameters-1].description, parameterValues[parameters-2].description);
          if (parameterValues[parameters-2].symbol)
            SDDS_CopyString(&parameterValues[parameters-1].symbol, parameterValues[parameters-2].symbol);
        }
        
	break;
      case SET_COLUMN:
	if (s_arg[i_arg].n_items<3)
	  SDDS_Bomb("invalid -column syntax");
        count=1;
	columns++;
	columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns));
        SDDS_CopyString(&columnValues[columns-1].name, s_arg[i_arg].list[1]);
	columnValues[columns-1].elements = 0;
	columnValues[columns-1].values = NULL;
	columnValues[columns-1].stringValues = NULL;
	columnValues[columns-1].units = NULL;
	columnValues[columns-1].description = NULL;
	columnValues[columns-1].symbol = NULL;
	columnValues[columns-1].skip = 0;

	switch (match_string(s_arg[i_arg].list[2], type_name, DATATYPES, 0)) {
	case TYPE_SHORT:
	  columnValues[columns-1].type = SDDS_SHORT;
	  break;
	case TYPE_LONG:
	  columnValues[columns-1].type = SDDS_LONG;
	  break;
	case TYPE_FLOAT:
	  columnValues[columns-1].type = SDDS_FLOAT;
	  break;
	case TYPE_DOUBLE:
	  columnValues[columns-1].type = SDDS_DOUBLE;
	  break;
	case TYPE_STRING:
	  columnValues[columns-1].type = SDDS_STRING;
	  break;
	case TYPE_CHARACTER:
	  columnValues[columns-1].type = SDDS_CHARACTER;
	  break;
	default:
	  SDDS_Bomb("invalid -column type");
	  break;
	}
	for (i=3;i<s_arg[i_arg].n_items;i++) {
	  if (!(ptr=strchr(s_arg[i_arg].list[i], '=')))
	    SDDS_Bomb("invalid -column syntax");
	  *ptr++ = 0;	
	  switch (match_string(s_arg[i_arg].list[i], header_elements, HEADERELEMENTS, 0)) {
	  case HEADER_UNITS:
            SDDS_CopyString(&columnValues[columns-1].units, ptr);
	    break;
	  case HEADER_DESCRIPTION:
            SDDS_CopyString(&columnValues[columns-1].description, ptr);
	    break;
	  case HEADER_SYMBOL:
            SDDS_CopyString(&columnValues[columns-1].symbol, ptr);
	    break;
	  case HEADER_COUNT:
	    if (sscanf(ptr, "%ld", &count)!=1 ||
                count<=0)
              SDDS_Bomb("invalid column count value");
            sprintf(buffer, "%s", columnValues[columns-1].name);
            sprintf(buffer2, "%s1", buffer);
            free(columnValues[columns-1].name);
            SDDS_CopyString(&columnValues[columns-1].name, buffer2);
	    break;
	  default:
	    SDDS_Bomb("invalid -column syntax");
	    break;
	  }
	}
        
        for (i=2;i<=count;i++) {
          columns++;
          columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns));
          sprintf(buffer2, "%s%ld", buffer, i);
          SDDS_CopyString(&columnValues[columns-1].name, buffer2);
          columnValues[columns-1].elements = 0;
          columnValues[columns-1].values = NULL;
          columnValues[columns-1].stringValues = NULL;
          columnValues[columns-1].units = NULL;
          columnValues[columns-1].description = NULL;
          columnValues[columns-1].symbol = NULL;
          columnValues[columns-1].type = columnValues[columns-2].type;
          if (columnValues[columns-2].units)
            SDDS_CopyString(&columnValues[columns-1].units, columnValues[columns-2].units);
          if (columnValues[columns-2].description)
            SDDS_CopyString(&columnValues[columns-1].description, columnValues[columns-2].description);
          if (columnValues[columns-2].symbol)
            SDDS_CopyString(&columnValues[columns-1].symbol, columnValues[columns-2].symbol);
        }
        
	break;
      case SET_SKIPCOLUMN:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -skipcolumn syntax");
        count=1;
	columns++;
	columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns));
        columnValues[columns-1].name = NULL;
	columnValues[columns-1].elements = 0;
	columnValues[columns-1].values = NULL;
	columnValues[columns-1].stringValues = NULL;
	columnValues[columns-1].units = NULL;
	columnValues[columns-1].description = NULL;
	columnValues[columns-1].symbol = NULL;
	columnValues[columns-1].skip = 1;

	switch (match_string(s_arg[i_arg].list[1], type_name, DATATYPES, 0)) {
	case TYPE_SHORT:
	  columnValues[columns-1].type = SDDS_SHORT;
	  break;
	case TYPE_LONG:
	  columnValues[columns-1].type = SDDS_LONG;
	  break;
	case TYPE_FLOAT:
	  columnValues[columns-1].type = SDDS_FLOAT;
	  break;
	case TYPE_DOUBLE:
	  columnValues[columns-1].type = SDDS_DOUBLE;
	  break;
	case TYPE_STRING:
	  columnValues[columns-1].type = SDDS_STRING;
	  break;
	case TYPE_CHARACTER:
	  columnValues[columns-1].type = SDDS_CHARACTER;
	  break;
	default:
	  SDDS_Bomb("invalid -skipcolumn type");
	  break;
	}        
	break;
      case SET_PIPE:
	if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags))
	  SDDS_Bomb("invalid -pipe syntax");
	break;
      case SET_NOWARNINGS:
	if (s_arg[i_arg].n_items!=1)
	  SDDS_Bomb("invalid -nowarnings syntax");
	noWarnings = 1;
	break;
      case SET_SKIPLINES:
	if (s_arg[i_arg].n_items!=2 ||
	    sscanf(s_arg[i_arg].list[1], "%ld", &skiplines)!=1 ||
	    skiplines<=0)
	  SDDS_Bomb("invalid -skiplines syntax");
	break;
      default:
	fprintf(stderr, "error: unknown switch: %s\n", s_arg[i_arg].list[0]);
	exit(1);
	break;
      }
    } else {
      if (input == NULL) {
	input = s_arg[i_arg].list[0];
      } else if (output == NULL) {
	output = s_arg[i_arg].list[0];
      } else {
	fprintf(stderr, "too many filenames");
	exit(1);
      }
    }
  }
  
  processFilenames("plaindata2sdds", &input, &output, pipeFlags, noWarnings, &tmpfile_used);

  if (!columns && !parameters)
    SDDS_Bomb("you must specify one of the -column or the -parameter options");

  if (skiplines && inputBinary)
    SDDS_Bomb("-skiplines does not work with binary input files");
  
  if (!input) {
    if (inputBinary) {
#if defined(_WIN32)
      if (_setmode(_fileno(stdin), _O_BINARY) == -1) {
	fprintf(stderr, "error: unable to set stdin to binary mode\n");
	exit(1);
      }      
#endif
    }
    fileID = stdin;
  } else {
    if (!fexists(input)) {
      fprintf(stderr, "input file not found\n");
      exit(1);
    }
    if (inputBinary) {
      fileID = fopen(input, "rb");
    } else {
      fileID = fopen(input, "r");
    }
  }
  if (fileID == NULL) {
    fprintf(stderr, "unable to open input file for reading\n");
    exit(1);
  }
  
  if (!SDDS_InitializeOutput(&SDDS_dataset, binary?SDDS_BINARY:SDDS_ASCII,
                             1, NULL, NULL, output))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    
  SDDS_dataset.layout.data_mode.column_major = columnMajorOrder;
  
  if (parameters) {
    parameterIndex = tmalloc(sizeof(*parameterIndex)*parameters);
  }
  if (columns) {
    columnIndex = tmalloc(sizeof(*columnIndex)*columns);
  }

  for (i=0; i<parameters; i++) {
    if ((parameterIndex[i] = 
         SDDS_DefineParameter(&SDDS_dataset, parameterValues[i].name, parameterValues[i].symbol,
			      parameterValues[i].units, parameterValues[i].description, NULL, 
                           parameterValues[i].type, 0))<0) {
      sprintf(s, "Problem defining parameter %s.", parameterValues[i].name);
      SDDS_SetError(s);
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
  }
  for (i=0; i<columns; i++) {
    if (columnValues[i].skip)
      continue;
    if ((columnIndex[i] = 
         SDDS_DefineColumn(&SDDS_dataset, columnValues[i].name, columnValues[i].symbol, \
			   columnValues[i].units, columnValues[i].description, NULL, 
                           columnValues[i].type, 0))<0) {
      sprintf(s, "Problem defining column %s.", columnValues[i].name);
      SDDS_SetError(s);
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
  }

  if (!SDDS_WriteLayout(&SDDS_dataset))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  if (!SDDS_StartPage(&SDDS_dataset, initRows))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);


  row = par = col = page = 0;
  while (inputBinary) {
    row = par = col = 0;
    
    if (fread(&rows,sizeof(rows),1,fileID) != 1) {
      if (page == 0) {
	SDDS_SetError("Unable to read number of rows");
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
      } else {
        if (!SDDS_Terminate(&SDDS_dataset))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        for (k=0;k<columns;k++) {
          if (columnValues[k].type == SDDS_STRING) {
            SDDS_FreeStringArray(columnValues[k].stringValues,columnValues[k].elements);
          } else {
            free(columnValues[k].values);
          }
        }
	return 0;
      }
    }
    page++;

    for (par=0;par<parameters;par++) {
      
      switch (parameterValues[par].type) {
      case SDDS_SHORT:
	if (fread(&shortValue,2,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read short parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,shortValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_LONG:
	if (fread(&longValue,4,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read long parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,longValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_FLOAT:
	if (fread(&floatValue,4,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read float parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,floatValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_DOUBLE:
	if (fread(&doubleValue,8,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read double parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,doubleValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_STRING:
	if (fread(&size,4,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read string parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
        if (size>SDDS_MAXLINE-1)
          SDDS_Bomb("String is too long");
	if (size > 0) {
	  if (fread(&stringValue,size,1,fileID) != 1) {
	    SDDS_SetError("Unable to read string parameter");
	    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	  }
          stringValue[size] = 0;
	} else {
	  strcpy(stringValue,"");
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,stringValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_CHARACTER:
	if (fread(&characterValue,1,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read character parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,characterValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      }
    }
    for (i=0;i<columns;i++) {
	if (rows > columnValues[i].elements) {
	  if (columnValues[i].type == SDDS_STRING) {
	    columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements);
	  } else {
	    columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows);
          }
	  columnValues[i].elements = rows;
	}
    }
    if (columnOrder) {
      for (col=0;col<columns;col++) {
	switch (columnValues[col].type) {
	case SDDS_SHORT:
	  for (i=0;i<rows;i++) {
	    if (fread((short*)(columnValues[col].values)+i,2,1,fileID) != 1) {
	      SDDS_SetError("Unable to read short column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	  }
	  break;
	case SDDS_LONG:
	  for (i=0;i<rows;i++) {
	    if (fread((int32_t*)(columnValues[col].values)+i,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read long column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	  }
	  break;
	case SDDS_FLOAT:
	  for (i=0;i<rows;i++) {
	    if (fread((float*)(columnValues[col].values)+i,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read float column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }      
	  }
	  break;
	case SDDS_DOUBLE:
	  for (i=0;i<rows;i++) {
	    if (fread((double*)(columnValues[col].values)+i,8,1,fileID) != 1) {
	      SDDS_SetError("Unable to read double double");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	  }
	  break;
	case SDDS_STRING:
	  for (i=0;i<rows;i++) {
	    if (fread(&size,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read string column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
            if (size>SDDS_MAXLINE-1)
              SDDS_Bomb("String is too long");
            columnValues[col].stringValues[i] = malloc(size + 1);
	    if (size > 0) {
	      if (fread(columnValues[col].stringValues[i],size,1,fileID) != 1) {
		SDDS_SetError("Unable to read string column");
		SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	      }
              columnValues[col].stringValues[i][size] = 0;
	    } else {
	      strcpy(columnValues[col].stringValues[i],"");
	    }
	  }
	  break;
	case SDDS_CHARACTER:
	  for (i=0;i<rows;i++) {
	    if (fread((char*)(columnValues[col].values)+i,1,1,fileID) != 1) {
	      SDDS_SetError("Unable to read character column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	  }
	  break;
	}
      }
    } else {
      for (i=0;i<rows;i++) {
	for (col=0;col<columns;col++) {
	  switch (columnValues[col].type) {
	  case SDDS_SHORT:
	    if (fread((short*)(columnValues[col].values)+i,2,1,fileID) != 1) {
	      SDDS_SetError("Unable to read short column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    break;
	  case SDDS_LONG:
	    if (fread((int32_t*)(columnValues[col].values)+i,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read long column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    break;
	  case SDDS_FLOAT:
	    if (fread((float*)(columnValues[col].values)+i,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read float column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }      
	    break;
	  case SDDS_DOUBLE:
	    if (fread(((double*)(columnValues[col].values)+i),8,1,fileID) != 1) {
	      SDDS_SetError("Unable to read double column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    break;
	  case SDDS_STRING:
	    if (fread(&size,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read string column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
            if (size>SDDS_MAXLINE-1)
              SDDS_Bomb("String is too long");
            columnValues[col].stringValues[i] = malloc(size + 1);
	    if (size > 0) {
	      if (fread(columnValues[col].stringValues[i],size,1,fileID) != 1) {
		SDDS_SetError("Unable to read string column");
		SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	      }
              columnValues[col].stringValues[i][size] = 0;
	    } else {
	      strcpy(columnValues[col].stringValues[i],"");
	    }
	    break;
	  case SDDS_CHARACTER:
	    if (fread(((char*)(columnValues[col].values)+i),1,1,fileID) != 1) {
	      SDDS_SetError("Unable to read character column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    break;
	  }
	}
      }
    }
    if (rows > maxRows) {
      if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) {
	SDDS_SetError("Unable to lengthen table");
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
      }
      maxRows = rows;
    }
    j=n;
    for (i=0;i<columns;i++) {
      if (columnValues[i].skip)
	continue;
      if (columnValues[i].type == SDDS_STRING) {
	SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].stringValues, rows, n);
      } else {
	SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].values, rows, n);
      }
      n++;
    }
    
    if (!SDDS_WritePage(&SDDS_dataset)) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    maxRows = 10000;
    if (!SDDS_StartPage(&SDDS_dataset, initRows))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  row = par = col = n = 0;
  rows = -1;
  ptr = NULL;
  ptr = SDDS_Malloc(sizeof(*ptr)*(ptrSize=2048));
  /*  ptr2 = NULL;
      ptr2 = SDDS_Malloc(sizeof(*ptr)*(ptrSize=2048));*/
  ptr[0] = 0;
  while (1) {
    if (readline) {
      while (skiplines > 0) {
	fgets(ptr, ptrSize, fileID);
	skiplines--;
      }
      if (!fgetsSkipCommentsResize(&ptr,&ptrSize,fileID, '!'))
	break;
      commentFound=0;
      if (checkComment) {
        for (i=0; i<strlen(commentCharacters); i++) {
          if (ptr[0] == commentCharacters[i]) {
            commentFound=1;
          }
        }
      }
      if (commentFound == 1) {
        continue;
      }
      if (ptr[strlen(ptr)-1] == '\n')
        ptr[strlen(ptr)-1] = 0;
      strcpy(temp,ptr);
      /*skip empty lines*/
      if (getToken(temp,data,10240,separator,whitespace)<0)
        continue;
    } else {
      readline = 1;
    }
    if (par < parameters) {
      switch (parameterValues[par].type) {
      case SDDS_SHORT:
	if (sscanf(ptr,"%hd",&shortValue) != 1) {
	  SDDS_SetError("Invalid short parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,shortValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_LONG:
	if (sscanf(ptr,"%" SCNd32 ,&longValue) != 1) {
	  SDDS_SetError("Invalid long parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,longValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_FLOAT:
        ConvertDNotationToENotation(ptr);
	if (sscanf(ptr,"%f",&floatValue) != 1) {
	  SDDS_SetError("Invalid float parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,floatValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_DOUBLE:
        ConvertDNotationToENotation(ptr);
	if (sscanf(ptr,"%lf",&doubleValue) != 1) {
	  SDDS_SetError("Invalid double parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,doubleValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_STRING:
	SDDS_GetToken(ptr,stringValue,SDDS_MAXLINE);
	SDDS_InterpretEscapes(stringValue);
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,stringValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_CHARACTER:
	SDDS_InterpretEscapes(ptr);
	characterValue = ptr[0];
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,characterValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      }
      par++;
    } else if ((rows == -1) && (!noRowCount)) {
      if (sscanf(ptr,"%ld",&rows) != 1) {
	SDDS_SetError("Invalid row count");
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
    } else if ((columns > 0) && ((row < rows) || (noRowCount)))  {

      if (columnOrder) {

	if (noRowCount) {
	  cp_str(&ptr2,ptr);
	  rows = 0;
	  while (getToken(ptr2,data,10240,separator,whitespace) >= 0) {
	    rows++;
          }
          free(ptr2);
	}

	if (rows > columnValues[col].elements) {
	  if (columnValues[col].type == SDDS_STRING) {
	    columnValues[col].stringValues = AllocateColumnStringData(columnValues[col].stringValues, rows, columnValues[col].elements);
	  } else {
	    columnValues[col].values = AllocateColumnData(columnValues[col].type, columnValues[col].values, rows);
          }
	  columnValues[col].elements = rows;
	}
	switch (columnValues[col].type) {
	case SDDS_SHORT:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid short column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	    if (sscanf(data,"%hd",((short*)(columnValues[col].values)+row)) != 1) {
	      SDDS_SetError("Invalid short column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	  }
	  break;
	case SDDS_LONG:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid long column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	    if (sscanf(data,"%" SCNd32,((int32_t*)(columnValues[col].values)+row)) != 1) {
	      SDDS_SetError("Invalid long column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	  }
	  break;
	case SDDS_FLOAT:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid float column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
            ConvertDNotationToENotation(data);
	    if (sscanf(data,"%f",((float*)(columnValues[col].values)+row)) != 1) {
	      SDDS_SetError("Invalid float column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	  }
	  break;
	case SDDS_DOUBLE:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid double column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
            ConvertDNotationToENotation(data);
	    if (sscanf(data,"%lf",((double*)(columnValues[col].values)+row)) != 1) {
	      SDDS_SetError("Invalid double column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	  }
	  break;
	case SDDS_STRING:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid string column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	    SDDS_InterpretEscapes(data);
            columnValues[col].stringValues[row] = malloc(strlen(data) + 1);
	    strcpy(columnValues[col].stringValues[row],data);
	  }
	  break;
	case SDDS_CHARACTER:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid character column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	    SDDS_InterpretEscapes(data);
	    *((char*)(columnValues[col].values)+row) = data[0];
	  }
	  break;
	}
	if (rows > maxRows) {
	  if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) {
	    SDDS_SetError("Unable to lengthen table");
	    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	  }
	  maxRows = rows;
	}
	if (columnValues[col].skip == 0) {
	  if (columnValues[col].type == SDDS_STRING) {
	    SetColumnData(columnValues[col].type, &SDDS_dataset, columnValues[col].stringValues, rows, col);
	  } else {
	    SetColumnData(columnValues[col].type, &SDDS_dataset, columnValues[col].values, rows, col);
	  }
	  n++;
	}
	col++;
	row = 0;
      } else {
	if (noRowCount) {
	  if (row == 0) {
	    rows = 3;
	  } else if (row == rows - 1) {
	    rows = rows + 3;
	    for (i=0;i<columns;i++) {
	      if (rows > columnValues[i].elements) {
		if (columnValues[i].type == SDDS_STRING) {
		  columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements);
		} else {
		  columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows);
                }
	      }
	      columnValues[i].elements = rows;
	    }
	  }
	}
	if (row == 0) 
	  for (i=0;i<columns;i++) {
	    if (rows > columnValues[i].elements) {
	      if (columnValues[i].type == SDDS_STRING) {
		columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements);
	      } else {
		columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows);
              }
	    }
	    columnValues[i].elements = rows;
	  }

	if (noRowCount) {
	  cp_str(&ptr2,ptr);
	  i = 0;
	  while (getToken(ptr2,data,10240,separator,whitespace) >= 0)
	    i++;
          free(ptr2);
	  if ((i != columns) && (parameters>0 && i==1)) {
	    if (row > 0) {
	      if (row > maxRows) {
		if (!SDDS_LengthenTable(&SDDS_dataset, row - maxRows)) {
		  SDDS_SetError("Unable to lengthen table");
		  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
		}
		maxRows = row;
	      }
	      n=0;
	      for (j=0;j<columns;j++) {
		if (columnValues[j].skip)
		  continue;
		if (columnValues[j].type == SDDS_STRING) {
		  SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].stringValues, row, n);
		} else {
		  SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].values, row, n);
		}
		n++;
	      }
	      if (!SDDS_WritePage(&SDDS_dataset))
		SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	      maxRows = 10000;
	      if (!SDDS_StartPage(&SDDS_dataset, initRows))
		SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	      row = par = col = 0;
	      rows = -1;
	    }
	    readline = 0;
	    continue;
	  }
	}

	for (i=0;i<columns;i++) {
	  if (getToken(ptr,data,10240,separator,whitespace) < 0) {
            if (!fillin) {
              SDDS_SetError("Invalid column element");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            } else {
              switch (columnValues[i].type) {
              case SDDS_SHORT:
              case SDDS_LONG:
              case SDDS_FLOAT:
              case SDDS_DOUBLE:
                data[0]='0';
                data[1]='\0';
                break;
              case SDDS_STRING:  
              case SDDS_CHARACTER:
                data[0]='\0';
                break;
              }
            }
	  }

	  switch (columnValues[i].type) {
	  case SDDS_SHORT:
	    if (sscanf(data,"%hd",((short*)(columnValues[i].values)+row)) != 1) {
              if (recover) {
                abort=1;
                row--;
              } else {
                SDDS_SetError("Invalid short column element");
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
              }
            }
	    break;
	  case SDDS_LONG:
	    if (sscanf(data,"%" SCNd32,((int32_t*)(columnValues[i].values)+row)) != 1) {
              if (recover) {
                abort=1;
                row--;
              } else {
                SDDS_SetError("Invalid long column element");
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
              }
            }
	    break;
	  case SDDS_FLOAT:
            ConvertDNotationToENotation(data);
	    if (sscanf(data,"%f",((float*)(columnValues[i].values)+row)) != 1) {
              if (recover) {
                abort=1;
                row--;
              } else {
                SDDS_SetError("Invalid float column element");
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
              }
            }
	    break;
	  case SDDS_DOUBLE:
            ConvertDNotationToENotation(data);
	    if (sscanf(data,"%lf",((double*)(columnValues[i].values)+row)) != 1) {
              if (recover) {
                abort=1;
                row--;
              } else {
                SDDS_SetError("Invalid double column element");
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
              }
	    }
	    break;
	  case SDDS_STRING:
	    SDDS_InterpretEscapes(data);
            columnValues[i].stringValues[row] = malloc(strlen(data) + 1);
	    strcpy(columnValues[i].stringValues[row],data);
	    break;
	  case SDDS_CHARACTER:
	    SDDS_InterpretEscapes(data);
	    *((char*)(columnValues[i].values)+row) = data[0];
	    break;
	  }

          if (recover && abort) {
            break;
          }
        }
	row++;
	if ((row == rows) && (!noRowCount)) {
	  if (rows > maxRows) {
	    if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) {
	      SDDS_SetError("Unable to lengthen table");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    maxRows = rows;
	  }
	  n=0;
	  for (i=0;i<columns;i++) {
	    if (columnValues[i].skip)
	      continue;
	    if (columnValues[i].type == SDDS_STRING) {
	      SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].stringValues, rows, n);
	    } else {
	      SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].values, rows, n);
	    }
	    n++;
	  }
	}
      }
    }
    if ((par == parameters) && 
	(((!noRowCount) && (rows != -1)) || (noRowCount)) && 
	(((columnOrder) && (col == columns)) || ((columns > 0) && (row == rows)) || (columns == 0))) {
      if (!SDDS_WritePage(&SDDS_dataset)) {
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      maxRows = 10000;
      if (!SDDS_StartPage(&SDDS_dataset, initRows))
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      
      row = par = col = 0;
      rows = -1;
    }
    ptr[0] = 0;
  }

  if (noRowCount) {
    if (row > 0) {
      if (row > maxRows) {
	if (!SDDS_LengthenTable(&SDDS_dataset, row - maxRows)) {
	  SDDS_SetError("Unable to lengthen table");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	maxRows = row;
      }
      n=0;
      for (j=0;j<columns;j++) {
	if (columnValues[j].skip)
	  continue;
	if (columnValues[j].type == SDDS_STRING) {
	  SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].stringValues, row, n);
	} else {
	  SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].values, row, n);
	}
	n++;
      }
      if (!SDDS_WritePage(&SDDS_dataset)) {
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      maxRows = 10000;
    }
  }
  for (i=0;i<columns;i++) {
    if (columnValues[i].type == SDDS_STRING) {
      for (j=0;j<columnValues[i].elements;j++) {
	free(columnValues[i].stringValues[j]);
      }
      free(columnValues[i].stringValues);
    } else {
      free(columnValues[i].values);
    }
    if (columnValues[i].name) free(columnValues[i].name);
    if (columnValues[i].units) free(columnValues[i].units);
    if (columnValues[i].description) free(columnValues[i].description);
    if (columnValues[i].symbol) free(columnValues[i].symbol);

  }
  for (i=0;i<parameters;i++) {
    free(parameterValues[i].name);
    if (parameterValues[i].units) free(parameterValues[i].units);
    if (parameterValues[i].description) free(parameterValues[i].description);
    if (parameterValues[i].symbol) free(parameterValues[i].symbol);
  }
  if (columnValues) free(columnValues);
  if (parameterValues) free(parameterValues);
  if (columnIndex) free(columnIndex);
  if (parameterIndex) free(parameterIndex);
  if (ptr) free(ptr);
  if (!SDDS_Terminate(&SDDS_dataset))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  free_scanargs(&s_arg,argc);
  return 0;
}
Beispiel #30
0
int 
HSM1noise (int mode, int operation, GENmodel *inModel, CKTcircuit *ckt,
           register Ndata *data, double *OnDens)
{
  register HSM1model *model = (HSM1model *)inModel;
  register HSM1instance *here;
  char name[N_MXVLNTH];
  double tempOnoise;
  double tempInoise;
  double noizDens[HSM1NSRCS];
  double lnNdens[HSM1NSRCS];
  register int i;

  /* define the names of the noise sources */
  static char * HSM1nNames[HSM1NSRCS] = {
    /* Note that we have to keep the order
       consistent with the index definitions 
       in hsm1defs.h */
    ".rd",              /* noise due to rd */
    ".rs",              /* noise due to rs */
    ".id",              /* noise due to id */
    ".1ovf",            /* flicker (1/f) noise */
    ""                  /* total transistor noise */
  };
  
  for ( ;model != NULL; model = model->HSM1nextModel ) {
    for ( here = model->HSM1instances; here != NULL;
	  here = here->HSM1nextInstance ) {
		  
      if (here->HSM1owner != ARCHme)
	      continue;	  
	    
	  
      switch (operation) {
      case N_OPEN:
	/* see if we have to to produce a summary report */
	/* if so, name all the noise generators */
	  
	if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
	  switch (mode) {
	  case N_DENS:
	    for ( i = 0; i < HSM1NSRCS; i++ ) { 
	      (void) sprintf(name, "onoise.%s%s", 
			     (char *)here->HSM1name, HSM1nNames[i]);
	      data->namelist = 
		(IFuid *) trealloc((char *) data->namelist,
				   (data->numPlots + 1) * sizeof(IFuid));
	      if (!data->namelist)
		return(E_NOMEM);
	      (*(SPfrontEnd->IFnewUid)) 
		(ckt, &(data->namelist[data->numPlots++]),
		 (IFuid) NULL, name, UID_OTHER, (void **) NULL);
	    }
	    break;
	  case INT_NOIZ:
	    for ( i = 0; i < HSM1NSRCS; i++ ) {
	      (void) sprintf(name, "onoise_total.%s%s", 
			     (char *)here->HSM1name, HSM1nNames[i]);
	      data->namelist = 
		(IFuid *) trealloc((char *) data->namelist,
				   (data->numPlots + 1) * sizeof(IFuid));
	      if (!data->namelist)
		return(E_NOMEM);
	      (*(SPfrontEnd->IFnewUid)) 
		(ckt, &(data->namelist[data->numPlots++]),
		 (IFuid) NULL, name, UID_OTHER, (void **) NULL);
	      
	      (void) sprintf(name, "inoise_total.%s%s", 
			     (char *)here->HSM1name, HSM1nNames[i]);
	      data->namelist = 
		(IFuid *) trealloc((char *) data->namelist,
				   (data->numPlots + 1) * sizeof(IFuid));
	      if (!data->namelist)
		return(E_NOMEM);
	      (*(SPfrontEnd->IFnewUid)) 
		(ckt, &(data->namelist[data->numPlots++]),
		 (IFuid) NULL, name, UID_OTHER, (void **)NULL);
	    }
	    break;
	  }
	}
	break;
      case N_CALC:
	switch (mode) {
	case N_DENS:
	  NevalSrc(&noizDens[HSM1RDNOIZ], &lnNdens[HSM1RDNOIZ], 
		   ckt, THERMNOISE,
		   here->HSM1dNodePrime, here->HSM1dNode,
		   here->HSM1drainConductance  * here->HSM1_m);
	  
	  NevalSrc(&noizDens[HSM1RSNOIZ], &lnNdens[HSM1RSNOIZ], 
		   ckt, THERMNOISE,
		   here->HSM1sNodePrime, here->HSM1sNode,
		   here->HSM1sourceConductance * here->HSM1_m);

	  switch( model->HSM1_noise ) {
	    double I;
	  case 1:
	  case 3:
	    I = here->HSM1_gm + here->HSM1_gds + here->HSM1_gmbs;
	    I *= (I < 0.0) ? -1.0 : 1.0;
	    I *= 2.0/3.0;
	    I *=  here->HSM1_m; /* PN */    
	    NevalSrc(&noizDens[HSM1IDNOIZ], &lnNdens[HSM1IDNOIZ], 
		     ckt, THERMNOISE, 
		     here->HSM1dNodePrime, here->HSM1sNodePrime, I);
	    break;
	  case 2:
	  case 4:
	    I = -1.0 * (here->HSM1_qg + here->HSM1_qb)
	      / (here->HSM1_weff * here->HSM1_leff);
	    I *= (I < 0.0) ? -1.0 : 1.0;
	    I *= here->HSM1_mu;
	    I *=  here->HSM1_m; /* PN */  
	    NevalSrc(&noizDens[HSM1IDNOIZ], &lnNdens[HSM1IDNOIZ], 
		     ckt, THERMNOISE, 
		     here->HSM1dNodePrime, here->HSM1sNodePrime, I);
	    break;
	  case 5:
	    NevalSrc(&noizDens[HSM1IDNOIZ], &lnNdens[HSM1IDNOIZ], 
		     ckt, THERMNOISE, 
		     here->HSM1dNodePrime, here->HSM1sNodePrime, 0.0);
	    break;
	  }
	  NevalSrc(&noizDens[HSM1FLNOIZ], (double*) NULL,
		   ckt, N_GAIN, 
		   here->HSM1dNodePrime, here->HSM1sNodePrime, 
		   (double) 0.0);
	  
	  /* flicker noise */
	  switch ( model->HSM1_noise ) {
	  case 1:
	  case 4: /* SPICE2 model */
	    noizDens[HSM1FLNOIZ] *= here->HSM1_m * model->HSM1_kf
	      * exp(model->HSM1_af * log(MAX(fabs(here->HSM1_ids), N_MINLOG)))
	      / (pow(data->freq, model->HSM1_ef) * here->HSM1_leff
		 * here->HSM1_leff * (3.453133e-11 / model->HSM1_tox));
	    /*                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~cox  */
	    break;
	  case 2:
	  case 3:
	  case 5:
	    /* from HiSIM */
	    noizDens[HSM1FLNOIZ] *= here->HSM1_nfc / data->freq; 
	    break;
	  }
	  
	  lnNdens[HSM1FLNOIZ] = log(MAX(noizDens[HSM1FLNOIZ], N_MINLOG));
	  
	  noizDens[HSM1TOTNOIZ] = noizDens[HSM1RDNOIZ] + noizDens[HSM1RSNOIZ]
	    + noizDens[HSM1IDNOIZ] + noizDens[HSM1FLNOIZ];
	  lnNdens[HSM1TOTNOIZ] = log(MAX(noizDens[HSM1TOTNOIZ], N_MINLOG));
	  
	  *OnDens += noizDens[HSM1TOTNOIZ];
	  
	  if ( data->delFreq == 0.0 ) {
	    /* if we haven't done any previous 
	       integration, we need to initialize our
	       "history" variables.
	    */
	    
	    for ( i = 0; i < HSM1NSRCS; i++ ) 
	      here->HSM1nVar[LNLSTDENS][i] = lnNdens[i];
	    
	    /* clear out our integration variables
	       if it's the first pass
	    */
	    if (data->freq == ((NOISEAN*) ckt->CKTcurJob)->NstartFreq) {
	      for (i = 0; i < HSM1NSRCS; i++) {
		here->HSM1nVar[OUTNOIZ][i] = 0.0;
		here->HSM1nVar[INNOIZ][i] = 0.0;
	      }
	    }
	  }
	  else {
	    /* data->delFreq != 0.0,
	       we have to integrate.
	    */
	    for ( i = 0; i < HSM1NSRCS; i++ ) {
	      if ( i != HSM1TOTNOIZ ) {
		tempOnoise = 
		  Nintegrate(noizDens[i], lnNdens[i],
			     here->HSM1nVar[LNLSTDENS][i], data);
		tempInoise = 
		  Nintegrate(noizDens[i] * data->GainSqInv, 
			     lnNdens[i] + data->lnGainInv,
			     here->HSM1nVar[LNLSTDENS][i] + data->lnGainInv,
			     data);
		here->HSM1nVar[LNLSTDENS][i] = lnNdens[i];
		data->outNoiz += tempOnoise;
		data->inNoise += tempInoise;
		if ( ((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0 ) {
		  here->HSM1nVar[OUTNOIZ][i] += tempOnoise;
		  here->HSM1nVar[OUTNOIZ][HSM1TOTNOIZ] += tempOnoise;
		  here->HSM1nVar[INNOIZ][i] += tempInoise;
		  here->HSM1nVar[INNOIZ][HSM1TOTNOIZ] += tempInoise;
		}
	      }
	    }
	  }
	  if ( data->prtSummary ) {
	    for (i = 0; i < HSM1NSRCS; i++) {
	      /* print a summary report */
	      data->outpVector[data->outNumber++] = noizDens[i];
	    }
	  }
	  break;
	case INT_NOIZ:
	  /* already calculated, just output */
	  if ( ((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0 ) {
	    for ( i = 0; i < HSM1NSRCS; i++ ) {
	      data->outpVector[data->outNumber++] = here->HSM1nVar[OUTNOIZ][i];
	      data->outpVector[data->outNumber++] = here->HSM1nVar[INNOIZ][i];
	    }
	  }
	  break;
	}
	break;
      case N_CLOSE:
	/* do nothing, the main calling routine will close */
	return (OK);
	break;   /* the plots */
      }       /* switch (operation) */
    }    /* for here */
  }    /* for model */
  
  return(OK);
}