Пример #1
0
/*----------------------------------------------------------------------------------------------
 * 函数:    tftpd_daemon()
 *
 * 描述:    tftp服务器的后台任务, 堆栈大小建议为2048
**--------------------------------------------------------------------------------------------*/
void __daemon tftpd_daemon(void * data)
{
    struct iphdr * ip_hdr;
    struct udphdr * u_hdr;
    struct tftphdr * hdr;
    INT16U tftp_len;
    INT16U binary_mode = 0;
    FILE * volatile fp=NULL;
    INT16U last_blk=0, bytes=0, blksn=0, blksn_old=0;
    INT32U ip_connect = 0L;
    INT16U remote_port = 0;
    INT16S timeout_resend = 0;
    INT08S filename[256], mode[10], buf[512];
    INT08S wbuf[512];
    void __internal __tx_timeout_for_tftpd(void *, INT16S);
    void __internal __rx_timeout_for_tftpd(void *, INT16S);

    FamesAssert(data);

    TimerSet(TimerTftpdTX, 1000L, TIMER_TYPE_AUTO, __tx_timeout_for_tftpd, (void *)CurrentTask);
    TimerStop(TimerTftpdTX);
    TimerSet(TimerTftpdRX, 30000L, TIMER_TYPE_AUTO, __rx_timeout_for_tftpd, (void *)CurrentTask);
    TimerStop(TimerTftpdRX);
    /*lint --e{613}*/
     
    do {
        if(timeout_wait_ack){ /* 超时重传 */
            timeout_wait_ack = 0;
            set_tftpd_message(TFTP_OP_XXX, 0, "wait ack timeout!", NULL, ip_connect);
            timeout_resend++;
            if(timeout_resend > 10){ /* 这么久还没收到,那就不管了 */
                TimerStop(TimerTftpdTX);
                timeout_wait_ack = 0;
                binary_mode = 0;
                if(fp){
                    DispatchLock();
                    fclose(fp);
                    fp=NULL;
                    DispatchUnlock();
                }
                ip_connect = 0L;
                timeout_resend = 0;
                goto i_will_take_a_nap;
            }
            if(!fp || ip_connect==0L){
                TimerStop(TimerTftpdTX);
                timeout_wait_ack = 0;
                goto i_will_take_a_nap;
            }
            tftpd_xmit(ip_connect, remote_port, TFTP_OP_DAT, blksn, buf, bytes);
            TimerReStart(TimerTftpdTX);
            goto i_will_take_a_nap;
        }

        if(timeout_wait_rx){   /* 等待客户端数据包超时 */
            TimerStop(TimerTftpdRX);
            timeout_wait_rx = 0;
            set_tftpd_message(TFTP_OP_XXX, 0, "wait client timeout(30sec)!", NULL, ip_connect);
            binary_mode = 0;
            if(fp){
                DispatchLock();
                fclose(fp);
                fp=NULL;
                DispatchUnlock();
            }
            ip_connect = 0L;                     
        }    
        
        if(tftp_packet_received==0)goto i_will_take_a_nap;
        tftp_packet_received=0;

        tftp_packet_lock = 1;
        
        ip_hdr = (struct iphdr *)data; /*lint !e826 */
        u_hdr  = (struct udphdr *)((INT08S *)data + (ip_hdr->ihl<<2)); /*lint !e826 !e613 */
        hdr    = (struct tftphdr *)((INT08S *)u_hdr+8); /*lint !e826 */

        tftp_len = INT16XCHG(u_hdr->len)-8; /* TFTP报文长度 */

        if(ip_hdr->daddr == get_bcast_ip()){ /*lint !e613 */
            goto i_will_take_a_nap;
        }

        if(ip_connect!=0L){
            if(ip_connect != ip_hdr->saddr){ /*lint !e613*/
                set_tftpd_message(TFTP_OP_XXX, 0, "not the client ip packet", NULL, ip_hdr->saddr); /*lint !e613*/
                tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ERR, 0, 
                                "I am busy, please wait a moment!!!", 35); /*lint !e613*/
                goto i_will_take_a_nap;
            }
        }

        TimerReStart(TimerTftpdRX); /* 接收到了客户端的数据包, 则重设定时器 */

        switch(INT16XCHG(hdr->opcode)){
            case TFTP_OP_RRQ:
                STRCPY(filename, hdr->un.filename);
                STRCPY(mode,    (hdr->un.filename+STRLEN(filename)+1));
                set_tftpd_message(TFTP_OP_RRQ, 0, filename, mode, ip_hdr->saddr); /*lint !e613*/
                if(ip_connect!=0){
                    TimerStop(TimerTftpdTX);
                    timeout_wait_ack = 0;
                    tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ERR, 1, 
                                    "rrq is not expected!!!", 23);/*lint !e613*/
                    binary_mode = 0;
                    if(fp){
                        DispatchLock();
                        fclose(fp);
                        fp=NULL;
                        DispatchUnlock();
                    }
                    ip_connect = 0L;
                    break;
                }
                ip_connect = ip_hdr->saddr; /*lint !e613*/
                remote_port = INT16XCHG(u_hdr->source);
                if(mode[0]=='o'||mode[0]=='O'){ /* octet */
                    binary_mode = 1;
                } else {
                    binary_mode = 0;
                }
                DispatchLock();
                fp=fopen(filename, binary_mode?("rb"):("rt"));
                DispatchUnlock();
                if(!fp){
                    tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ERR, 2, 
                                    "file not found!!!", 18); /*lint !e613*/
                    ip_connect = 0L;
                    break;
                }
                DispatchLock();
                bytes=fread(buf, 1, 512, fp);
                DispatchUnlock();
                if(bytes!=512) last_blk = 1;
                else           last_blk = 0;
                blksn = 1;
                tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_DAT, 
                                 blksn, buf, bytes); /*lint !e613*/
                TimerReStart(TimerTftpdTX);
                timeout_resend = 0;
                break;
            case TFTP_OP_WRQ:
                STRCPY(filename, hdr->un.filename);
                STRCPY(mode,    (hdr->un.filename+STRLEN(filename)+1));
                set_tftpd_message(TFTP_OP_WRQ, 0, filename, mode, ip_hdr->saddr); /*lint !e613*/
                if(ip_connect!=0){
                    tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ERR, 1, 
                                    "wrq is not expected!!!", 23); /*lint !e613*/
                    binary_mode = 0;
                    if(fp){
                        DispatchLock();
                        fclose(fp);
                        fp=NULL;
                        DispatchUnlock();
                    }
                    ip_connect = 0L;
                    break;
                }
                ip_connect = ip_hdr->saddr;
                remote_port = INT16XCHG(u_hdr->source);
                if(mode[0]=='o'||mode[0]=='O'){ /* octet */
                    binary_mode = 1;
                } else {
                    binary_mode = 0;
                }
                DispatchLock(); 
                fp = fopen(filename, binary_mode?"wb":"wt");
                DispatchUnlock();
                if(!fp){
                    tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ERR, 2, "file can not write!!!", 22);
                    ip_connect = 0L;
                    break;
                }
                blksn = 0;
                last_blk = 0;
                blksn_old  = 0;
                tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ACK, blksn, NULL, 0);
                break;
            case TFTP_OP_DAT:
                set_tftpd_message(TFTP_OP_DAT, INT16XCHG(hdr->un.id), filename, mode, ip_hdr->saddr);
                blksn = INT16XCHG(hdr->un.id);
                if(blksn_old !=0 && blksn_old==blksn){
                    tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ACK, blksn, NULL, 0);
                    break;
                }
                if(blksn - blksn_old > 1){
                    tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ACK, blksn_old, NULL, 0);
                    break;
                }
                blksn_old=blksn;
                if(!fp || ip_connect==0L){
                    tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ERR, 3, "file not open!!!", 17);
                    break;
                }
                bytes = tftp_len-4;
                DispatchLock();
                MEMCPY(wbuf, ((INT08S *)hdr+4), (INT16S)bytes);
                fwrite(wbuf, bytes, 1, fp);
                if(bytes!=512){
                    fclose(fp);
                    fp=NULL;
                    ip_connect=0L;
                    set_tftpd_message(TFTP_OP_XXX, 0, "=== receive end ===", 0, ip_hdr->saddr);                    
                }
                DispatchUnlock();
                tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ACK, blksn, NULL, 0);
                break;
            case TFTP_OP_ACK:
                timeout_resend = 0;
                set_tftpd_message(TFTP_OP_ACK, INT16XCHG(hdr->un.id), filename, mode, ip_hdr->saddr);
                if(!fp || ip_connect==0L){
                    tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_ERR, 3, "file not open!!!", 17);
                    TimerStop(TimerTftpdTX);
                    timeout_wait_ack = 0;
                    break;
                }
                if(last_blk){
                    TimerStop(TimerTftpdTX);
                    timeout_wait_ack = 0;
                    DispatchLock();
                    fclose(fp);
                    fp=NULL;
                    DispatchUnlock();
                    ip_connect = 0L;
                    set_tftpd_message(TFTP_OP_XXX, 0, "=== transmit end ===", 0, ip_hdr->saddr);                    
                    break;
                }
                blksn++;
                DispatchLock();
                bytes=fread(buf, 1, 512, fp);
                DispatchUnlock();
                if(bytes!=512) last_blk = 1;
                else           last_blk = 0;
                tftpd_xmit(ip_hdr->saddr, INT16XCHG(u_hdr->source), TFTP_OP_DAT, blksn, buf, bytes);
                TimerReStart(TimerTftpdTX);
                break;
            case TFTP_OP_ERR:
                TimerStop(TimerTftpdTX);
                timeout_wait_ack = 0;
                binary_mode = 0;
                if(fp){
                    DispatchLock();
                    fclose(fp);
                    fp=NULL;
                    DispatchUnlock();
                }
                ip_connect = 0L;
                set_tftpd_message(TFTP_OP_ERR, hdr->un.err.err, hdr->un.err.err_msg, NULL, ip_hdr->saddr);
                break;
            default:
                break;
        }
        
        if(ip_connect==0L){               /* 当前没有连接, 定时器应该关闭         */
            TimerStop(TimerTftpdRX);
        }
        
        i_will_take_a_nap:
        tftp_packet_lock = 0;
        if(tftp_packet_received==0){
            TaskSleep(1000L);
        }
        
    }while(1);/*lint !e506 */

}
Пример #2
0
int
main(int argc, char *argv[]) {
  char   **av, *in_fname;
  int    ac, nargs, i, j,  x, y, z, width, height, depth;
  MRI    *mri_flash[MAX_IMAGES], *mri_label, *mri_mask, *mri_tmp;
  int    msec, minutes, seconds, nvolumes, nvolumes_total ;
  struct timeb start ;
  float max_val, min_val, value;
  float *LDAmean1, *LDAmean2, *LDAweight;
  int label;
  double sum_white, sum_gray;
  int count_white, count_gray;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_ms_LDA.c,v 1.4 2011/03/02 00:04:23 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 2)
    usage_exit(1) ;

  printf("command line parsing finished\n");

  if (have_weight == 0 && ldaflag == 0) {
    printf("Use -lda option to specify two class labels to optimize CNR on \n");
    usage_exit(0);
  }

  if (have_weight == 0 && label_fname == NULL) {
    printf("Use -label option to specify file for segmentation \n");
    usage_exit(0);
  }


  if (have_weight == 1 && weight_fname == NULL) {
    printf("Use -weight option to specify file for input LDA weights \n") ;
    usage_exit(0);
  }

  if (have_weight == 1 && synth_fname == NULL) {
    printf("Use -synth option to specify file for output synthesized volume \n") ;
    usage_exit(0);
  }

  //////////////////////////////////////////////////////////////////////////////////
  /*** Read in the input multi-echo volumes ***/
  nvolumes = 0 ;
  for (i = 1 ; i < argc; i++) {
    in_fname = argv[i] ;
    printf("reading %s...\n", in_fname) ;

    mri_flash[nvolumes] = MRIread(in_fname) ;
    if (mri_flash[nvolumes] == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume %s",
                Progname, in_fname) ;
    /* conform will convert all data to UCHAR, which will reduce data resolution*/
    printf("%s read in. \n", in_fname) ;
    if (conform) {
      printf("embedding and interpolating volume\n") ;
      mri_tmp = MRIconform(mri_flash[nvolumes]) ;
      MRIfree(&mri_flash[nvolumes]);
      mri_flash[nvolumes] = mri_tmp ;
    }

    /* Change all volumes to float type for convenience */
    if (mri_flash[nvolumes]->type != MRI_FLOAT) {
      printf("Volume %d type is %d\n", nvolumes+1, mri_flash[nvolumes]->type);
      printf("Change data to float type \n");
      mri_tmp = MRIchangeType(mri_flash[nvolumes], MRI_FLOAT, 0, 1.0, 1);
      MRIfree(&mri_flash[nvolumes]);
      mri_flash[nvolumes] = mri_tmp; //swap
    }

    nvolumes++ ;
  }

  printf("All data read in\n");

  ///////////////////////////////////////////////////////////////////////////
  nvolumes_total = nvolumes ;   /* all volumes read in */

  for (i = 0 ; i < nvolumes ; i++) {
    for (j = i+1 ; j < nvolumes ; j++) {
      if ((mri_flash[i]->width != mri_flash[j]->width) ||
          (mri_flash[i]->height != mri_flash[j]->height) ||
          (mri_flash[i]->depth != mri_flash[j]->depth))
        ErrorExit(ERROR_BADPARM, "%s:\nvolumes %d (type %d) and %d (type %d) don't match (%d x %d x %d) vs (%d x %d x %d)\n",
                  Progname, i, mri_flash[i]->type, j, mri_flash[j]->type, mri_flash[i]->width,
                  mri_flash[i]->height, mri_flash[i]->depth,
                  mri_flash[j]->width, mri_flash[j]->height, mri_flash[j]->depth) ;
    }
  }

  width = mri_flash[0]->width;
  height = mri_flash[0]->height;
  depth = mri_flash[0]->depth;

  if (label_fname != NULL) {
    mri_label = MRIread(label_fname);
    if (!mri_label)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, label_fname);

    if ((mri_label->width != mri_flash[0]->width) ||
        (mri_label->height != mri_flash[0]->height) ||
        (mri_label->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: label volume size doesn't match data volumes\n", Progname);

    /* if(mri_label->type != MRI_UCHAR)
       ErrorExit(ERROR_BADPARM, "%s: label volume is not UCHAR type \n", Progname); */
  }

  if (mask_fname != NULL) {
    mri_mask = MRIread(mask_fname);
    if (!mri_mask)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, mask_fname);

    if ((mri_mask->width != mri_flash[0]->width) ||
        (mri_mask->height != mri_flash[0]->height) ||
        (mri_mask->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: mask volume size doesn't macth data volumes\n", Progname);

    if (mri_mask->type != MRI_UCHAR)
      ErrorExit(ERROR_BADPARM, "%s: mask volume is not UCHAR type \n", Progname);
  } else {

    if (have_weight == 1)
      noise_threshold = - 1e20;

    printf("Threshold input vol1 at %g to create mask \n", noise_threshold);
    printf("this threshold is useful to process skull-stripped data \n");

    mri_mask = MRIalloc(mri_flash[0]->width, mri_flash[0]->height, mri_flash[0]->depth, MRI_UCHAR);
    MRIcopyHeader(mri_flash[0], mri_mask);

    /* Simply set mask to be 1 everywhere */
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {

          if ((float)MRIgetVoxVal(mri_flash[0], x, y,z,0) < noise_threshold)
            MRIvox(mri_mask, x, y,z) = 0;
          else
            MRIvox(mri_mask, x, y,z) = 1;
        }
  }

  /* Normalize input volumes */
  if (normflag) {
    printf("Normalize input volumes to zero mean, variance 1\n");
    for (i=0; i <nvolumes_total; i++) {
      mri_flash[i] = MRInormalizeXH(mri_flash[i], mri_flash[i], mri_mask);
    }
    printf("Normalization done.\n");
  }

  if (0) {
    printf("Using both hemi-sphere by changing rh-labels\n");
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          label = (int)MRIgetVoxVal(mri_label, x, y,z,0);
          if (label == 41) /* white matter */
            MRIsetVoxVal(mri_label, x, y, z, 0, 2);
          else if (label == 42) /* gm */
            MRIsetVoxVal(mri_label, x, y, z, 0, 3);
        }
  }


  if (debug_flag && window_flag) {
    /* Limit LDA to a local window */
    printf("Local window size = %d\n", window_size);
    window_size /= 2;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (MRIvox(mri_mask, x, y,z) == 0) continue;

          if (z < (Gz - window_size) || z >(Gz + window_size)
              || y <(Gy - window_size) || y > (Gy + window_size)
              || x < (Gx - window_size) || x > (Gx + window_size))
            MRIvox(mri_mask, x, y,z) = 0;
        }

  }

  LDAmean1 = (float *)malloc(nvolumes_total*sizeof(float));
  LDAmean2 = (float *)malloc(nvolumes_total*sizeof(float));
  LDAweight = (float *)malloc(nvolumes_total*sizeof(float));

  if (have_weight) {
    printf("Read in LDA weights from weight-file\n");
    input_weights_to_file(LDAweight, weight_fname, nvolumes_total);
  } else { /* compute LDA weights */
    printf("Compute LDA weights to maximize CNR for region %d and region %d\n", class1, class2);
    /* Compute class means */
    update_LDAmeans(mri_flash, mri_label, mri_mask, LDAmean1, LDAmean2, nvolumes_total, class1, class2);
    printf("class means computed \n");

    /* Compute Fisher's LDA weights */
    computeLDAweights(LDAweight, mri_flash, mri_label, mri_mask, LDAmean1, LDAmean2, nvolumes_total, class1, class2);

    if (weight_fname != NULL) {
      output_weights_to_file(LDAweight, weight_fname, nvolumes_total);
    }
  }

  printf("LDA weights are: \n");
  for (i=0; i < nvolumes_total; i++) {
    printf("%g ", LDAweight[i]);
  }
  printf("\n");

  if (synth_fname != NULL) {
    /* linear projection of input volumes to a 1D volume */
    min_val = 10000.0;
    max_val = -10000.0;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

          value = 0.0;

          for (i=0; i < nvolumes_total; i++) {
            value += MRIFvox(mri_flash[i], x, y, z)*LDAweight[i];
          }

          //     if(value < 0) value = 0;

          if (max_val < value) max_val = value;
          if (min_val > value) min_val = value;

          /* Borrow mri_flash[0] to store the float values first */
          MRIFvox(mri_flash[0], x, y, z) = value;
        }

    printf("max_val = %g, min_val = %g \n", max_val, min_val);

    /* Check to make sure class1 has higher intensity than class2 */
    if (have_weight == 0) {
      sum_white =0;
      count_white = 0;
      sum_gray = 0;
      count_gray = 0;
      for (z=0; z < depth; z++) {
        if (count_white > 300 && count_gray > 300) break;
        for (y=0; y< height; y++) {
          for (x=0; x < width; x++) {

            if ((int)MRIgetVoxVal(mri_label, x, y,z,0) == class1) {
              sum_white += MRIFvox(mri_flash[0], x, y, z);
              count_white += 1;
            } else if ((int)MRIgetVoxVal(mri_label, x, y,z,0) == class2) {
              sum_gray += MRIFvox(mri_flash[0], x, y, z);
              count_gray += 1;
            }
          }
        }
      }

      if (count_white > 1 && count_gray > 1) {
        if (sum_white *count_gray < sum_gray*count_white) {
          for (z=0; z < depth; z++)
            for (y=0; y< height; y++)
              for (x=0; x < width; x++) {
                if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;
                value = MRIFvox(mri_flash[0], x, y, z);
                MRIFvox(mri_flash[0], x, y, z) = max_val - value;
              }
          max_val = max_val - min_val;
          min_val = 0;
        }
      }
    }

    /* The following is copied to be consistent with mri_synthesize */
    /* Don't know why add min_val, minus should make more sense */
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) {
            MRIFvox(mri_flash[0], x, y, z) = 0; /*background always set to 0 */
            continue;
          }
          /* Borrow mri_flash[0] to store the float values first */
          if (shift_value > 0) {
            value = MRIFvox(mri_flash[0], x, y, z) + shift_value;
            if (value < 0) value = 0;
            MRIFvox(mri_flash[0], x, y, z) = value;
          } else if (mask_fname != NULL)
            MRIFvox(mri_flash[0], x, y, z) -= min_val;
        }


    MRIfree(&mri_mask);
    if (mri_flash[0]->type == out_type) {
      mri_mask = MRIcopy(mri_flash[0], mri_mask);
    } else {
      mri_mask = MRIchangeType(mri_flash[0], out_type, 0.1, 0.99, 0);
    }

    /* Scale output to [0, 255] */
    if (0) {
      for (z=0; z < depth; z++)
        for (y=0; y< height; y++)
          for (x=0; x < width; x++) {
            if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

            value = (MRIFvox(mri_flash[0], x, y, z) - min_val)*255.0/(max_val - min_val) + 0.5; /* +0.5 for round-off */

            if (value > 255.0) value = 255.0;
            if (value < 0) value = 0;

            /* Borrow mri_flash[0] to store the float values first */
            MRIvox(mri_mask, x, y, z) = (BUFTYPE) value;
          }
    }

    /* Output synthesized volume */
    MRIwrite(mri_mask, synth_fname);

  }

  free(LDAmean1);
  free(LDAmean2);
  free(LDAweight);

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("LDA took %d minutes and %d seconds.\n", minutes, seconds) ;

  MRIfree(&mri_mask);

  if (label_fname)
    MRIfree(&mri_label);


  for (i=0; i < nvolumes_total; i++) {
    MRIfree(&mri_flash[i]);
  }
  exit(0);
}
int
main(int argc, char *argv[]) {
  MRI_SURFACE  *mris ;
  char         **av, *curv_name, *surf_name, *hemi, fname[STRLEN],
  *cp, *subject_name, subjects_dir[STRLEN],
  **c1_subjects, **c2_subjects ;
  int          ac, nargs, n, num_class1, num_class2, i, nvertices,
  avgs, max_snr_avgs, nlabels = 0, done ;
  float        **c1_thickness, **c2_thickness, *curvs, *total_mean,
  *c1_mean, *c2_mean,
  *class_mean, *c1_var, *c2_var, *class_var,*pvals,
  **c1_avg_thickness,
  *vbest_snr, *vbest_avgs, *vtotal_var, *vsnr, **c2_avg_thickness,
  *vbest_pvalues, current_min_label_area, current_fthresh ;
  MRI_SP       *mrisp ;
  LABEL        *area, **labels = NULL ;
  FILE         *fp = NULL ;
  double       snr, max_snr ;
  struct timeb start ;
  int          msec, minutes, seconds ;
  double       **c1_label_thickness, **c2_label_thickness ;
  int          *sorted_indices = NULL, vno ;
  float        *test_thickness, *test_avg_thickness ;
  double       label_avg ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_classify_thickness.c,v 1.8 2011/03/02 00:04:29 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  if (write_flag && DIAG_VERBOSE_ON)
    fp = fopen("scalespace.dat", "w") ;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  TimerStart(&start) ;

  /* subject_name hemi surface curvature */
  if (argc < 7)
    usage_exit() ;
  if (output_subject == NULL)
    ErrorExit(ERROR_BADPARM,
              "output subject must be specified with -o <subject name>");

  cp = getenv("SUBJECTS_DIR") ;
  if (!cp)
    ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
              Progname) ;

  strcpy(subjects_dir, cp) ;

  hemi = argv[1] ;
  surf_name = argv[2] ;
  curv_name = argv[3] ;

#define ARGV_OFFSET 4

  /* first determine the number of subjects in each class */
  num_class1 = 0 ;
  n = ARGV_OFFSET ;
  do {
    num_class1++ ;
    n++ ;
    if (argv[n] == NULL || n >= argc)
      ErrorExit(ERROR_BADPARM, "%s: must spectify ':' between class lists",
                Progname) ;
  } while (argv[n][0] != ':') ;

  /* find  # of vertices in output subject surface */
  sprintf(fname, "%s/%s/surf/%s.%s",
          subjects_dir,output_subject,hemi,surf_name);
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;
  nvertices = mris->nvertices ;
  MRISfree(&mris) ;

  total_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!total_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate mean list of %d curvatures",
              Progname, n, nvertices) ;
  c1_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c1_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c1 mean list of %d curvatures",
              Progname, n, nvertices) ;
  pvals = (float *)calloc(nvertices, sizeof(float)) ;
  if (!pvals)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate pvals",
              Progname, n, nvertices) ;
  c2_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c2_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c2 mean list of %d curvatures",
              Progname, n, nvertices) ;

  c1_var = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c1_var)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c1 var list of %d curvatures",
              Progname, n, nvertices) ;
  c2_var = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c2_var)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c2 var list of %d curvatures",
              Progname, n, nvertices) ;

  num_class2 = 0 ;
  n++ ; /* skip ':' */
  if (n >= argc)
    ErrorExit(ERROR_BADPARM, "%s: class2 list empty", Progname) ;
  do {
    num_class2++ ;
    n++ ;
    if (n >= argc)
      break ;
  } while (argv[n] != NULL) ;

  fprintf(stderr, "%d subjects in class 1, %d subjects in class 2\n",
          num_class1, num_class2) ;

  c1_subjects = (char **)calloc(num_class1, sizeof(char *)) ;
  c1_thickness = (float **)calloc(num_class1, sizeof(char *)) ;
  c1_avg_thickness = (float **)calloc(num_class1, sizeof(char *)) ;
  c2_subjects = (char **)calloc(num_class2, sizeof(char *)) ;
  c2_thickness = (float **)calloc(num_class2, sizeof(char *)) ;
  c2_avg_thickness = (float **)calloc(num_class2, sizeof(char *)) ;
  for (n = 0 ; n < num_class1 ; n++) {
    c1_subjects[n] = argv[ARGV_OFFSET+n] ;
    c1_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    c1_avg_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    if (!c1_thickness[n] || !c1_avg_thickness[n])
      ErrorExit(ERROR_NOMEMORY,
                "%s: could not allocate %dth list of %d curvatures",
                Progname, n, nvertices) ;

    strcpy(c1_subjects[n], argv[ARGV_OFFSET+n]) ;
    /*    fprintf(stderr, "class1[%d] - %s\n", n, c1_subjects[n]) ;*/
  }
  i = n+1+ARGV_OFFSET ;  /* starting index */
  for (n = 0 ; n < num_class2 ; n++) {
    c2_subjects[n] = argv[i+n] ;
    c2_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    c2_avg_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    if (!c2_thickness[n] || !c2_avg_thickness[n])
      ErrorExit(ERROR_NOMEMORY,
                "%s: could not allocate %dth list of %d curvatures",
                Progname, n, nvertices) ;
    strcpy(c2_subjects[n], argv[i+n]) ;
    /*    fprintf(stderr, "class2[%d] - %s\n", n, c2_subjects[n]) ;*/
  }

  if (label_name) {
    area = LabelRead(output_subject, label_name) ;
    if (!area)
      ErrorExit(ERROR_NOFILE, "%s: could not read label %s", Progname,
                label_name) ;
  } else
    area = NULL ;

  if (read_dir) {
    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,output_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;

    /* real all the curvatures in for group1 */
    for (n = 0 ; n < num_class1+num_class2 ; n++) {
      /* transform each subject's curvature into the output subject's space */
      subject_name = n < num_class1 ? c1_subjects[n]:c2_subjects[n-num_class1];
      fprintf(stderr, "reading subject %d of %d: %s\n",
              n+1, num_class1+num_class2, subject_name) ;
      sprintf(fname, "%s/%s.%s", read_dir,hemi,subject_name);
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror,
                  "%s: could not read curvature file %s",Progname,fname);
      if (area)
        MRISmaskNotLabel(mris, area) ;
      curvs = (n < num_class1) ? c1_thickness[n] : c2_thickness[n-num_class1] ;
      class_mean = (n < num_class1) ? c1_mean : c2_mean ;
      class_var = (n < num_class1) ? c1_var : c2_var ;
      MRISexportValVector(mris, curvs) ;
      cvector_accumulate(curvs, total_mean, nvertices) ;
      cvector_accumulate(curvs, class_mean, nvertices) ;
      cvector_accumulate_square(curvs, class_var, nvertices) ;
    }
  } else {

    /* real all the curvatures in for group1 */
    for (n = 0 ; n < num_class1+num_class2 ; n++) {
      /* transform each subject's curvature into the output subject's space */
      subject_name = n < num_class1 ? c1_subjects[n]:c2_subjects[n-num_class1];
      fprintf(stderr, "reading subject %d of %d: %s\n",
              n+1, num_class1+num_class2, subject_name) ;
      sprintf(fname, "%s/%s/surf/%s.%s",
              subjects_dir,subject_name,hemi,surf_name);
      mris = MRISread(fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
      if (strchr(curv_name, '/') != NULL)
        strcpy(fname, curv_name) ;  /* full path specified */
      else
        sprintf(fname,"%s/%s/surf/%s.%s",
                subjects_dir,subject_name,hemi,curv_name);
      if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
        ErrorExit(Gerror,"%s: could no read curvature file %s",Progname,fname);
      mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
      MRISfree(&mris) ;

      sprintf(fname, "%s/%s/surf/%s.%s",
              subjects_dir,output_subject,hemi,surf_name);
      mris = MRISread(fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;
      MRISfromParameterization(mrisp, mris, 0) ;
      if (area)
        MRISmaskNotLabel(mris, area) ;
      curvs = (n < num_class1) ? c1_thickness[n] : c2_thickness[n-num_class1] ;
      class_mean = (n < num_class1) ? c1_mean : c2_mean ;
      class_var = (n < num_class1) ? c1_var : c2_var ;
      MRISextractCurvatureVector(mris, curvs) ;
      cvector_accumulate(curvs, total_mean, nvertices) ;
      cvector_accumulate(curvs, class_mean, nvertices) ;
      cvector_accumulate_square(curvs, class_var, nvertices) ;
      MRISPfree(&mrisp) ;
      MRISfree(&mris) ;
    }
  }

  /* compute within-group means, and total mean */
  cvector_normalize(total_mean, num_class1+num_class2, nvertices) ;
  cvector_normalize(c1_mean, num_class1, nvertices) ;
  cvector_normalize(c2_mean, num_class2, nvertices) ;
  cvector_compute_variance(c1_var, c1_mean, num_class1, nvertices) ;
  cvector_compute_variance(c2_var, c2_mean, num_class2, nvertices) ;
  cvector_compute_t_test(c1_mean, c1_var, c2_mean, c2_var,
                         num_class1, num_class2, pvals, nvertices) ;

  sprintf(fname, "%s/%s/surf/%s.%s",
          subjects_dir,output_subject,hemi,surf_name);
  fprintf(stderr, "reading output surface %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;

  if (area)
    MRISripNotLabel(mris, area) ;
  vbest_snr = cvector_alloc(nvertices) ;
  vbest_pvalues = cvector_alloc(nvertices) ;
  vbest_avgs = cvector_alloc(nvertices) ;
  vtotal_var = cvector_alloc(nvertices) ;
  vsnr = cvector_alloc(nvertices) ;

  if (read_dir == NULL)  /* recompute everything */
  {
    if (use_buggy_snr)
      cvector_multiply_variances(c1_var, c2_var, num_class1, num_class2,
                                 vtotal_var, nvertices) ;
    else
      cvector_add_variances(c1_var, c2_var, num_class1, num_class2,
                            vtotal_var, nvertices) ;
    if (use_no_distribution)
      snr = cvector_compute_dist_free_snr(c1_thickness, num_class1,
                                          c2_thickness, num_class2,
                                          c1_mean, c2_mean,
                                          vsnr, nvertices, &i);
    else
      snr = cvector_compute_snr(c1_mean, c2_mean, vtotal_var, vsnr, nvertices,
                                &i, 0.0f);
    fprintf(stderr,
            "raw SNR %2.2f, n=%2.4f, d=%2.4f, vno=%d\n",
            sqrt(snr), c1_mean[i]-c2_mean[i], sqrt(vtotal_var[i]), i) ;
    max_snr = snr ;
    max_snr_avgs = 0 ;
    cvector_track_best_snr(vsnr, vbest_snr, vbest_avgs, 0, nvertices) ;

    for (n = 0 ; n < num_class1 ; n++)
      cvector_copy(c1_thickness[n], c1_avg_thickness[n], nvertices) ;
    for (n = 0 ; n < num_class2 ; n++)
      cvector_copy(c2_thickness[n], c2_avg_thickness[n], nvertices) ;

    /* now incrementally average the data, keeping track of the best
       snr at each location, and at what scale it occurred. vbest_avgs
       and vbest_snr will contain the scale and the snr at that scale.
    */
    for (avgs = 1 ; avgs <= max_avgs ; avgs++) {
      /* c?_avg_thickness is the thickness at the current scale */
      if (!(avgs % 50))
        fprintf(stderr, "testing %d averages...\n", avgs) ;
      cvector_clear(c1_mean, nvertices) ;
      cvector_clear(c2_mean, nvertices) ;
      cvector_clear(c1_var, nvertices) ;
      cvector_clear(c2_var, nvertices) ;
      cvector_clear(total_mean, nvertices) ;
      for (n = 0 ; n < num_class1 ; n++) {
        MRISimportCurvatureVector(mris, c1_avg_thickness[n]) ;
        MRISaverageCurvatures(mris, 1) ;
        MRISextractCurvatureVector(mris, c1_avg_thickness[n]) ;
        cvector_accumulate(c1_avg_thickness[n], total_mean, nvertices) ;
        cvector_accumulate(c1_avg_thickness[n], c1_mean, nvertices) ;
        cvector_accumulate_square(c1_avg_thickness[n], c1_var, nvertices) ;
      }
      for (n = 0 ; n < num_class2 ; n++) {
        MRISimportCurvatureVector(mris, c2_avg_thickness[n]) ;
        MRISaverageCurvatures(mris, 1) ;
        MRISextractCurvatureVector(mris, c2_avg_thickness[n]) ;
        cvector_accumulate(c2_avg_thickness[n], total_mean, nvertices) ;
        cvector_accumulate(c2_avg_thickness[n], c2_mean, nvertices) ;
        cvector_accumulate_square(c2_avg_thickness[n], c2_var, nvertices) ;
      }
      cvector_normalize(total_mean, num_class1+num_class2, nvertices) ;
      cvector_normalize(c1_mean, num_class1, nvertices) ;
      cvector_normalize(c2_mean, num_class2, nvertices) ;
      cvector_compute_variance(c1_var, c1_mean, num_class1, nvertices) ;
      cvector_compute_variance(c2_var, c2_mean, num_class2, nvertices) ;
      if (use_buggy_snr)
        cvector_multiply_variances(c1_var, c2_var, num_class1, num_class2,
                                   vtotal_var, nvertices) ;
      else
        cvector_add_variances(c1_var, c2_var, num_class1, num_class2,
                              vtotal_var, nvertices) ;
      if (use_no_distribution)
        snr =
          cvector_compute_dist_free_snr(c1_avg_thickness,num_class1,
                                        c2_avg_thickness, num_class2, c1_mean,
                                        c2_mean, vsnr, nvertices, &i);
      else
        snr =
          cvector_compute_snr(c1_mean, c2_mean, vtotal_var, vsnr, nvertices,&i,
                              bonferroni ? log((double)avgs) : 0.0f);
      if (write_flag && DIAG_VERBOSE_ON) {
        fprintf(fp, "%d %2.1f  %2.2f %2.2f %2.2f ",
                avgs, sqrt((float)avgs), sqrt(snr), c1_mean[i]-c2_mean[i],
                sqrt(vtotal_var[i])) ;
        fflush(fp) ;
        for (n = 0 ; n < num_class1 ; n++)
          fprintf(fp, "%2.2f ", c1_avg_thickness[n][i]) ;
        for (n = 0 ; n < num_class2 ; n++)
          fprintf(fp, "%2.2f ", c2_avg_thickness[n][i]) ;
        fprintf(fp, "\n") ;
        fclose(fp) ;
      }
      if (snr > max_snr) {
        fprintf(stderr,
                "new max SNR found at avgs=%d (%2.1f mm)=%2.1f, n=%2.4f, "
                "d=%2.4f, vno=%d\n",
                avgs, sqrt((float)avgs), sqrt(snr), c1_mean[i]-c2_mean[i],
                sqrt(vtotal_var[i]), i) ;
        max_snr = snr ;
        max_snr_avgs = avgs ;
      }
      cvector_track_best_snr(vsnr, vbest_snr, vbest_avgs, avgs, nvertices) ;
    }
    if (compute_stats)
      cvector_compute_t(vbest_snr, vbest_pvalues,num_class1+num_class2,
                        nvertices) ;
    printf("max snr=%2.2f at %d averages\n", max_snr, max_snr_avgs) ;
    if (write_flag) {
      MRISimportValVector(mris, vbest_snr) ;
      sprintf(fname, "./%s.%s_best_snr", hemi,prefix) ;
      MRISwriteValues(mris, fname) ;
      MRISimportValVector(mris, vbest_avgs) ;
      sprintf(fname, "./%s.%s_best_avgs", hemi, prefix) ;
      MRISwriteValues(mris, fname) ;
      if (compute_stats) {
        MRISimportValVector(mris, vbest_pvalues) ;
        sprintf(fname, "./%s.%s_best_pval", hemi,prefix) ;
        MRISwriteValues(mris, fname) ;
      }
    }
  }
  else  /* read from directory containing precomputed optimal values */
  {
    sprintf(fname, "%s/%s.%s_best_snr", read_dir, hemi, prefix) ;
    if (MRISreadValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISreadValues(%s) failed",Progname,fname) ;
    MRISexportValVector(mris, vbest_snr) ;

    sprintf(fname, "%s/%s.%s_best_avgs", read_dir, hemi, prefix) ;
    if (MRISreadValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISreadValues(%s) failed",Progname,fname) ;
    MRISexportValVector(mris, vbest_avgs) ;
  }

  if (write_dir) {
    sprintf(fname, "%s/%s.%s_best_snr", write_dir, hemi,prefix) ;
    MRISimportValVector(mris, vbest_snr) ;
    if (MRISwriteValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISwriteValues(%s) failed",Progname,fname) ;

    sprintf(fname, "%s/%s.%s_best_avgs", write_dir, hemi, prefix) ;
    MRISimportValVector(mris, vbest_avgs) ;
    if (MRISwriteValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISwriteValues(%s) failed",Progname,fname) ;
  }

  if (nsort < -1)
    nsort = mris->nvertices ;

  if (nsort <= 0) {
    nlabels = 0 ;
    current_min_label_area = min_label_area ;
    for (done = 0, current_fthresh = fthresh ;
         !FZERO(current_fthresh) && !done ;
         current_fthresh *= 0.95) {
      int   npos_labels, nneg_labels ;
      LABEL **pos_labels, **neg_labels ;

      for (current_min_label_area = min_label_area ;
           current_min_label_area > 0.5 ;
           current_min_label_area *= 0.75) {
        MRISclearMarks(mris) ;
        sprintf(fname, "%s-%s_thickness", hemi, prefix ? prefix : "") ;
        mark_thresholded_vertices(mris, vbest_snr, vbest_avgs,current_fthresh);
        segment_and_write_labels(output_subject, fname, mris,
                                 &pos_labels, &npos_labels, 0,
                                 current_min_label_area) ;
        MRISclearMarks(mris) ;
        mark_thresholded_vertices(mris, vbest_snr,vbest_avgs,-current_fthresh);
        segment_and_write_labels(output_subject, fname, mris, &neg_labels,
                                 &nneg_labels, npos_labels,
                                 current_min_label_area) ;

        nlabels = nneg_labels + npos_labels ;
        if (nlabels) {
          labels = (LABEL **)calloc(nlabels, sizeof(LABEL *)) ;
          for (i = 0 ; i < npos_labels ; i++)
            labels[i] = pos_labels[i] ;
          for (i = 0 ; i < nneg_labels ; i++)
            labels[i+npos_labels] = neg_labels[i] ;
          free(pos_labels) ;
          free(neg_labels) ;
        }
        done = (nlabels >= min_labels) ;
        if (done)  /* found enough points */
          break ;

        /* couldn't find enough  points - free stuff and try again */
        for (i = 0 ; i < nlabels ; i++)
          LabelFree(&labels[i]) ;
        if (nlabels)
          free(labels) ;
#if 0
        fprintf(stderr,"%d labels found (min %d), reducing constraints...\n",
                nlabels, min_labels) ;
#endif
      }
    }

    printf("%d labels found with F > %2.1f and area > %2.0f\n",
           nlabels, current_fthresh, current_min_label_area) ;
    for (i = 0 ; i < nlabels ; i++)
      fprintf(stderr, "label %d: %d points, %2.1f mm\n",
              i, labels[i]->n_points, LabelArea(labels[i], mris)) ;
  }

  /* read or compute thickness at optimal scale and put it into
     c?_avg_thickness.
  */
  if (!read_dir) {
    fprintf(stderr, "extracting thickness at optimal scale...\n") ;

    /* now build feature vectors for each subject */
    extract_thickness_at_best_scale(mris, c1_avg_thickness, vbest_avgs,
                                    c1_thickness, nvertices, num_class1);
    fprintf(stderr, "extracting thickness for class 2...\n") ;
    extract_thickness_at_best_scale(mris, c2_avg_thickness, vbest_avgs,
                                    c2_thickness, nvertices, num_class2);
  } else  /* read in precomputed optimal thicknesses */
  {
    char fname[STRLEN] ;

    fprintf(stderr, "reading precomputed thickness vectors\n") ;
    for (n = 0 ; n < num_class1 ; n++) {
      sprintf(fname, "%s/%s.%s", read_dir, hemi, argv[ARGV_OFFSET+n]) ;
      fprintf(stderr, "reading thickness vector from %s...\n", fname) ;
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read thickness file %s",
                  Progname,fname) ;
      MRISexportValVector(mris, c1_avg_thickness[n]) ;
    }
    for (n = 0 ; n < num_class2 ; n++) {
      sprintf(fname, "%s/%s.%s", read_dir, hemi,
              argv[n+num_class1+1+ARGV_OFFSET]) ;
      fprintf(stderr, "reading curvature vector from %s...\n", fname) ;
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read thickness file %s",
                  Progname,fname) ;
      MRISexportValVector(mris, c2_avg_thickness[n]) ;
    }
  }

  if (write_dir)   /* write out optimal thicknesses */
  {
    char fname[STRLEN] ;

    for (n = 0 ; n < num_class1 ; n++) {
      sprintf(fname, "%s/%s.%s", write_dir, hemi, argv[ARGV_OFFSET+n]) ;
      fprintf(stderr, "writing curvature vector to %s...\n", fname) ;
      MRISimportValVector(mris, c1_avg_thickness[n]) ;
      MRISwriteValues(mris, fname) ;
    }
    for (n = 0 ; n < num_class2 ; n++) {
      sprintf(fname, "%s/%s.%s", write_dir, hemi,
              argv[n+num_class1+1+ARGV_OFFSET]) ;
      fprintf(stderr, "writing curvature vector to %s...\n", fname) ;
      MRISimportValVector(mris, c2_avg_thickness[n]) ;
      MRISwriteValues(mris, fname) ;
    }
  }


  /* should free c?_thickness here */

  if (nsort <= 0) {
    /* We have the thickness values at the most powerful scale stored for
       each subject in the c1_avg_thickness and c2_avg_thickness vectors.
       Now collapse them across each label and build  feature vector for
       classification.
    */
    c1_label_thickness = (double **)calloc(num_class1, sizeof(double *)) ;
    c2_label_thickness = (double **)calloc(num_class2, sizeof(double *)) ;
    for (n = 0 ; n < num_class1 ; n++)
      c1_label_thickness[n] = (double *)calloc(nlabels, sizeof(double)) ;
    for (n = 0 ; n < num_class2 ; n++)
      c2_label_thickness[n] = (double *)calloc(nlabels, sizeof(double)) ;

    fprintf(stderr, "collapsing thicknesses within labels for class 1\n") ;
    for (n = 0 ; n < num_class1 ; n++)
      for (i = 0 ; i < nlabels ; i++)
        c1_label_thickness[n][i] =
          cvector_average_in_label(c1_avg_thickness[n], labels[i], nvertices) ;
    fprintf(stderr, "collapsing thicknesses within labels for class 2\n") ;
    for (n = 0 ; n < num_class2 ; n++)
      for (i = 0 ; i < nlabels ; i++)
        c2_label_thickness[n][i] =
          cvector_average_in_label(c2_avg_thickness[n], labels[i], nvertices) ;
    sprintf(fname, "%s_%s_class1.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 1 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nlabels ; i++)  /* for each row */
    {
      for (n = 0 ; n < num_class1 ; n++)  /* for each column */
        fprintf(fp, "%2.2f  ", c1_label_thickness[n][i]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;

    sprintf(fname, "%s_%s_class2.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 2 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nlabels ; i++) {
      for (n = 0 ; n < num_class2 ; n++)
        fprintf(fp, "%2.2f  ", c2_label_thickness[n][i]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  } else {
    sorted_indices = cvector_sort(vbest_snr, nvertices) ;
    vno = sorted_indices[0] ;
    write_vertex_data("c1.dat", vno, c1_avg_thickness,num_class1);
    write_vertex_data("c2.dat", vno, c2_avg_thickness,num_class2);
    printf("sorting complete\n") ;

    /* re-write class means at these locations */
    sprintf(fname, "%s_%s_class1.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 1 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nsort ; i++) {
      for (n = 0 ; n < num_class1 ; n++)
        fprintf(fp, "%2.2f  ", c1_avg_thickness[n][sorted_indices[i]]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
    sprintf(fname, "%s_%s_class2.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 2 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nsort ; i++) {
      for (n = 0 ; n < num_class2 ; n++)
        fprintf(fp, "%2.2f  ", c2_avg_thickness[n][sorted_indices[i]]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  }

  if (test_subject) {
    test_thickness = cvector_alloc(nvertices) ;
    test_avg_thickness = cvector_alloc(nvertices) ;
    MRISfree(&mris) ;
    fprintf(stderr, "reading subject %s\n", test_subject) ;
    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,test_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    if (strchr(curv_name, '/') != NULL)
      strcpy(fname, curv_name) ;  /* full path specified */
    else
      sprintf(fname,"%s/%s/surf/%s.%s",
              subjects_dir,test_subject,hemi,curv_name);
    if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
      ErrorExit(Gerror,"%s: could no read curvature file %s",Progname,fname);
    mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
    MRISfree(&mris) ;

    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,output_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISfromParameterization(mrisp, mris, 0) ;
    if (area)
      MRISmaskNotLabel(mris, area) ;
    MRISextractCurvatureVector(mris, test_thickness) ;
    for (avgs = 0 ; avgs <= max_avgs ; avgs++) {
      cvector_extract_best_avg(vbest_avgs, test_thickness,test_avg_thickness,
                               avgs-1, nvertices) ;
      MRISimportCurvatureVector(mris, test_thickness) ;
      MRISaverageCurvatures(mris, 1) ;
      MRISextractCurvatureVector(mris, test_thickness) ;
    }

    if (nsort <= 0) {
      sprintf(fname, "%s_%s.dat", hemi,test_subject) ;
      fprintf(stderr, "writing test subject feature vector to %s...\n",
              fname) ;
      fp = fopen(fname, "w") ;
      for (i = 0 ; i < nlabels ; i++)  /* for each row */
      {
        label_avg =
          cvector_average_in_label(test_avg_thickness, labels[i], nvertices) ;
        fprintf(fp, "%2.2f\n", label_avg) ;
      }
      fclose(fp) ;
    } else   /* use sorting instead of connected areas */
    {
      double classification, offset, w ;
      int    total_correct, total_wrong, first_wrong, vno ;


      sprintf(fname, "%s_%s.dat", hemi,test_subject) ;
      fprintf(stderr, "writing test subject feature vector to %s...\n",
              fname) ;
      fp = fopen(fname, "w") ;

      first_wrong = -1 ;
      total_wrong = total_correct = 0 ;
      for (i = 0 ; i < nsort ; i++) {
        vno = sorted_indices[i] ;
        fprintf(fp, "%2.2f\n ", test_avg_thickness[sorted_indices[i]]) ;
        offset = (c1_mean[vno]+c2_mean[vno])/2.0 ;
        w = (c1_mean[vno]-c2_mean[vno]) ;
        classification = (test_avg_thickness[vno] - offset) * w ;

        if (((classification < 0) && (true_class == 1)) ||
            ((classification > 0) && (true_class == 2))) {
          total_wrong++ ;
          if (first_wrong < 0)
            first_wrong = i ;
        } else
          total_correct++ ;
      }
      fclose(fp) ;
      fprintf(stderr, "%d of %d correct = %2.1f%% (first wrong %d (%d)),"
              "min snr=%2.1f\n",
              total_correct, total_correct+total_wrong,
              100.0*total_correct / (total_correct+total_wrong),
              first_wrong, first_wrong >= 0 ? sorted_indices[first_wrong]:-1,
              vbest_snr[sorted_indices[nsort-1]]) ;

      if (first_wrong >= 0) {
        write_vertex_data("c1w.dat", sorted_indices[first_wrong],
                          c1_avg_thickness,num_class1);
        write_vertex_data("c2w.dat", sorted_indices[first_wrong],
                          c2_avg_thickness,num_class2);
      }
    }
  }

  msec = TimerStop(&start) ;
  free(total_mean);
  free(c1_mean) ;
  free(c2_mean) ;
  free(c1_var);
  free(c2_var);
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "classification took %d minutes and %d seconds.\n",
          minutes, seconds) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Пример #4
0
//*****************************************************************************
//
//! \brief xtimer 001 test execute main body.
//!
//! \return None.
//
//*****************************************************************************
static void xTimer001Execute(void)
{
    unsigned long ulTemp;
    unsigned long ulBase;
    int i, j ;
    
    //
    // One shot mode test.
    //
    for(i = 0; i < 4; i++)
    {
        ulBase = ulTimerBase[i];
        
        //
        // Clear the flag first
        //
        TimerIntClear(ulBase, TIMER_INT_MATCH);
        while(TimerIntStatus(ulBase, TIMER_INT_MATCH));  
        
        // 
        // Config as One shot mode
        //        
        TimerInitConfig(ulBase, TIMER_MODE_ONESHOT, 1000);
        
        TimerIntEnable(ulBase, TIMER_INT_MATCH);
        xIntEnable(ulTimerIntID[i]);
        xTimerIntCallbackInit(ulBase, TimerCallbackFunc[i]); 
        TimerStart(ulBase);
        
        //
        // wait until the timer data register reach equel to compare register
        //
        TestAssertQBreak("a","One shot mode Intterrupt test fail", -1);
        xIntDisable(ulTimerIntID[i]);
    }  
    
    //
    // Periodic mode
    //
    for(i = 0; i < 4; i++)
    {
        ulBase = ulTimerBase[i];
        ulTemp = 0;
        
        //
        // Clear the flag first
        //
        TimerIntClear(ulBase, TIMER_INT_MATCH);
        
        //
        // Config as periodic mode
        //
        TimerInitConfig(ulBase, TIMER_MODE_PERIODIC, 1000);    
        TimerIntEnable(ulBase, TIMER_INT_MATCH);
        TimerStart(ulBase);
        
        // 
        // wait the periodic repeat 5 times 
        //
        for (j = 0; j < 5; j++)
        {
            while(!TimerIntStatus(ulBase, TIMER_INT_MATCH));      
            ulTemp++;
            if(ulTemp == 5)
            {
                break;
            }
            TimerIntClear(ulBase, TIMER_INT_MATCH);
        }
        TestAssert(ulTemp == 5,
                   "xtimer mode \" periodic test\" error!");
        TimerStop(ulBase);       
    }
    
    //
    // Toggle mode test
    //
    for(i = 0; i < 4; i++)
    {
        ulBase = ulTimerBase[i];
        ulTemp = 0;
        
        //
        // Clear the Int flag first
        //
        TimerIntClear(ulBase, TIMER_INT_MATCH);
        
        //
        // Config as toggle mode
        //
        TimerInitConfig(ulBase, TIMER_MODE_PERIODIC, 1000);    
        TimerIntEnable(ulBase, TIMER_INT_MATCH);
        TimerStart(ulBase);
        
        // 
        // wait the toggle repeat 5 times 
        //
        for (j = 0; j < 5; j++)
        {
            while(!TimerIntStatus(ulBase, TIMER_INT_MATCH));      
            ulTemp++;
            if(ulTemp == 5)
            {
                break;
            }
            TimerIntClear(ulBase, TIMER_INT_MATCH);
        }
        TestAssert(ulTemp == 5,
                   "xtimer mode \" Toggle mode test\" error!");
        TimerStop(ulBase);       
    }
    
    //
    // Continuous mode test.
    //
    for(i = 0; i < 4; i++)
    {
        ulBase = ulTimerBase[i];
        ulTemp = 0;
        
        //
        // Clear the flag first
        //
        TimerIntClear(ulBase, TIMER_INT_MATCH);
        while(TimerIntStatus(ulBase, TIMER_INT_MATCH));  
        
        // 
        // Config as One shot mode
        //        
        TimerInitConfig(ulBase, TIMER_MODE_CONTINUOUS, 10000);
        TimerMatchSet(ulBase, 10);
        TimerIntEnable(ulBase, TIMER_INT_MATCH);
        TimerStart(ulBase);
        
        //
        // Delay some time to wait the count register reach to 200.
        //
        xSysCtlDelay(100);
        if(TimerIntStatus(ulBase, TIMER_INT_MATCH) == xtrue)
        {
            ulTemp++;
        }
        TimerIntClear(ulBase, TIMER_INT_MATCH);
        TimerMatchSet(ulBase, 2000);
        
        //
        // Wait until reach the 1000
        //
        //while(!TimerIntStatus(ulBase, TIMER_INT_MATCH));       
        xSysCtlDelay(10000);
        if(TimerIntStatus(ulBase, TIMER_INT_MATCH) == xtrue)
        {
            ulTemp++;
        }
        TimerIntClear(ulBase, TIMER_INT_MATCH);
        
        TestAssert(ulTemp == 2,
           "xtimer mode \" Continuous mode test\" error!");
        TimerStop(ulBase);     
        xIntDisable(ulTimerIntID[i]);
   
    }  
    
}
Пример #5
0
/*!
 * \brief Function executed on Led 2 Timeout event
 */
static void OnLed2TimerEvent( void )
{
    TimerStop( &Led2Timer );
    // Switch LED 2 OFF
    GpioWrite( &Led2, 0 );
}
Пример #6
0
/*----------------------------------------------------------------*/
SCS *SurfClusterSummary(MRI_SURFACE *Surf, MATRIX *T, int *nClusters)
{
  int n;
  SURFCLUSTERSUM *scs;
  MATRIX *xyz, *xyzxfm;
  double centroidxyz[3];
  struct timeb  mytimer;
  int msecTime;
  char *UFSS;

  // Must explicity "setenv USE_FAST_SURF_SMOOTHER 0" to turn off fast
  UFSS = getenv("USE_FAST_SURF_SMOOTHER");
  if(!UFSS) UFSS = "1";
  if(strcmp(UFSS,"0")){
    scs = SurfClusterSummaryFast(Surf, T, nClusters);
    return(scs);
  }
  if(Gdiag_no > 0) printf("SurfClusterSummary()\n");

  TimerStart(&mytimer) ;

  *nClusters = sclustCountClusters(Surf);
  if (*nClusters == 0) return(NULL);

  xyz    = MatrixAlloc(4,1,MATRIX_REAL);
  xyz->rptr[4][1] = 1;
  xyzxfm = MatrixAlloc(4,1,MATRIX_REAL);

  scs = (SCS *) calloc(*nClusters, sizeof(SCS));

  for (n = 0; n < *nClusters ; n++)
  {
    scs[n].clusterno = n+1;
    scs[n].area       = sclustSurfaceArea(n+1, Surf, &scs[n].nmembers);
    scs[n].weightvtx  = sclustWeight(n+1, Surf, NULL, 0);
    scs[n].weightarea = sclustWeight(n+1, Surf, NULL, 1);
    scs[n].maxval     = sclustSurfaceMax(n+1,  Surf, &scs[n].vtxmaxval);
    scs[n].x = Surf->vertices[scs[n].vtxmaxval].x;
    scs[n].y = Surf->vertices[scs[n].vtxmaxval].y;
    scs[n].z = Surf->vertices[scs[n].vtxmaxval].z;
    sclustSurfaceCentroid(n+1,  Surf, &centroidxyz[0]);
    scs[n].cx = centroidxyz[0];
    scs[n].cy = centroidxyz[1];
    scs[n].cz = centroidxyz[2];
    if (T != NULL){
      xyz->rptr[1][1] = scs[n].x;
      xyz->rptr[2][1] = scs[n].y;
      xyz->rptr[3][1] = scs[n].z;
      MatrixMultiply(T,xyz,xyzxfm);
      scs[n].xxfm = xyzxfm->rptr[1][1];
      scs[n].yxfm = xyzxfm->rptr[2][1];
      scs[n].zxfm = xyzxfm->rptr[3][1];

      xyz->rptr[1][1] = scs[n].cx;
      xyz->rptr[2][1] = scs[n].cy;
      xyz->rptr[3][1] = scs[n].cz;
      MatrixMultiply(T,xyz,xyzxfm);
      scs[n].cxxfm = xyzxfm->rptr[1][1];
      scs[n].cyxfm = xyzxfm->rptr[2][1];
      scs[n].czxfm = xyzxfm->rptr[3][1];
    }
  }

  MatrixFree(&xyz);
  MatrixFree(&xyzxfm);
  msecTime = TimerStop(&mytimer) ;
  if(Gdiag_no > 0) printf("SurfClusterSum: n=%d, t = %g\n",*nClusters,msecTime/1000.0);

  return(scs);
}
Пример #7
0
int
main(int argc, char *argv[])
{
  char **av, *surf_fname, *template_fname, *out_fname, fname[STRLEN],*cp;
  int ac, nargs,err, msec ;
  MRI_SURFACE  *mris ;
  MRI_SP       *mrisp_template ;

  char cmdline[CMD_LINE_LEN] ;
  struct  timeb start ;

  make_cmd_version_string
  (argc, argv,
   "$Id: mris_register.c,v 1.59 2011/03/02 00:04:33 nicks Exp $",
   "$Name: stable5 $",
   cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mris_register.c,v 1.59 2011/03/02 00:04:33 nicks Exp $",
           "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

  TimerStart(&start) ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  memset(&parms, 0, sizeof(parms)) ;
  parms.projection = PROJECT_SPHERE ;
  parms.flags |= IP_USE_CURVATURE ;
  parms.tol = 0.5 ;    // was 1e-0*2.5
  parms.min_averages = 0 ;
  parms.l_area = 0.0 ;
  parms.l_parea = 0.1f ;  // used to be 0.2
  parms.l_dist = 5.0 ; // used to be 0.5, and before that 0.1
  parms.l_corr = 1.0f ;
  parms.l_nlarea = 1 ;
  parms.l_pcorr = 0.0f ;
  parms.niterations = 25 ;
  parms.n_averages = 1024 ;   // used to be 256
  parms.write_iterations = 100 ;
  parms.dt_increase = 1.01 /* DT_INCREASE */;
  parms.dt_decrease = 0.99 /* DT_DECREASE*/ ;
  parms.error_ratio = 1.03 /*ERROR_RATIO */;
  parms.dt_increase = 1.0 ;
  parms.dt_decrease = 1.0 ;
  parms.l_external = 10000 ;   /* in case manual label is specified */
  parms.error_ratio = 1.1 /*ERROR_RATIO */;
  parms.integration_type = INTEGRATE_ADAPTIVE ;
  parms.integration_type = INTEGRATE_MOMENTUM /*INTEGRATE_LINE_MINIMIZE*/ ;
  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
  parms.dt = 0.9 ;
  parms.momentum = 0.95 ;
  parms.desired_rms_height = -1.0 ;
  parms.nbhd_size = -10 ;
  parms.max_nbrs = 10 ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (nsigmas > 0)
  {
    MRISsetRegistrationSigmas(sigmas, nsigmas) ;
  }
  parms.which_norm = which_norm ;
  if (argc < 4)
  {
    usage_exit() ;
  }

  printf("%s\n", vcid) ;
  printf("  %s\n",MRISurfSrcVersion());
  fflush(stdout);

  surf_fname = argv[1] ;
  template_fname = argv[2] ;
  out_fname = argv[3] ;

  if (parms.base_name[0] == 0)
  {
    FileNameOnly(out_fname, fname) ;
    cp = strchr(fname, '.') ;
    if (cp)
    {
      strcpy(parms.base_name, cp+1) ;
    }
    else
    {
      strcpy(parms.base_name, "sphere") ;
    }
  }

  fprintf(stderr, "reading surface from %s...\n", surf_fname) ;
  mris = MRISread(surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, surf_fname) ;

  if (parms.var_smoothness)
  {
    parms.vsmoothness = (float *)calloc(mris->nvertices, sizeof(float)) ;
    if (parms.vsmoothness == NULL)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate vsmoothness array",
                Progname) ;
    }
    parms.dist_error = (float *)calloc(mris->nvertices, sizeof(float)) ;
    if (parms.dist_error == NULL)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate dist_error array",
                Progname) ;
    }
    parms.area_error = (float *)calloc(mris->nvertices, sizeof(float)) ;
    if (parms.area_error == NULL)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate area_error array",
                Progname) ;
    }
    parms.geometry_error = (float *)calloc(mris->nvertices, sizeof(float)) ;
    if (parms.geometry_error == NULL)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate geometry_error array",
                Progname) ;
    }
  }

  MRISresetNeighborhoodSize(mris, 1) ;
  if (annot_name)
  {
    if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
      ErrorExit(ERROR_BADPARM,
                "%s: could not read annot file %s",
                Progname, annot_name) ;
    MRISripMedialWall(mris) ;
  }

  MRISsaveVertexPositions(mris, TMP2_VERTICES) ;
  MRISaddCommandLine(mris, cmdline) ;
  if (!FZERO(dalpha) || !FZERO(dbeta) || !FZERO(dgamma))
    MRISrotate(mris, mris, RADIANS(dalpha), RADIANS(dbeta),
               RADIANS(dgamma)) ;

  if (curvature_fname[0])
  {
    fprintf(stderr, "reading source curvature from %s\n",curvature_fname) ;
    MRISreadCurvatureFile(mris, curvature_fname) ;
  }
  if (single_surf)
  {
    char        fname[STRLEN], *cp, surf_dir[STRLEN], hemi[10]  ;
    MRI_SURFACE *mris_template ;
    int         sno, tnbrs=3 ;

    FileNamePath(template_fname, surf_dir) ;
    cp = strrchr(template_fname, '/') ;
    if (cp == NULL) // no path - start from beginning of file name
    {
      cp = template_fname ;
    }
    cp = strchr(cp, '.') ;
    if (cp == NULL)
      ErrorExit(ERROR_NOFILE,
                "%s: could no scan hemi from %s",
                Progname, template_fname) ;
    strncpy(hemi, cp-2, 2) ;
    hemi[2] = 0 ;
    fprintf(stderr, "reading spherical surface %s...\n", template_fname) ;
    mris_template = MRISread(template_fname) ;
    if (mris_template == NULL)
    {
      ErrorExit(ERROR_NOFILE, "") ;
    }
#if 0
    if (reverse_flag)
    {
      MRISreverse(mris_template, REVERSE_X, 1) ;
    }
#endif
    MRISsaveVertexPositions(mris_template, CANONICAL_VERTICES) ;
    MRIScomputeMetricProperties(mris_template) ;
    MRISstoreMetricProperties(mris_template) ;

    if (noverlays > 0)
    {
      mrisp_template = MRISPalloc(scale, IMAGES_PER_SURFACE*noverlays);
      for (sno = 0; sno < noverlays ; sno++)
      {
        sprintf(fname, "%s/../label/%s.%s", surf_dir, hemi, overlays[sno]) ;
        if (MRISreadValues(mris_template, fname)  != NO_ERROR)
          ErrorExit(ERROR_NOFILE,
                    "%s: could not read overlay from %s",
                    Progname, fname) ;
        MRIScopyValuesToCurvature(mris_template) ;
        MRISaverageCurvatures(mris_template, navgs) ;
        MRISnormalizeCurvature(mris_template, which_norm) ;
        fprintf(stderr,
                "computing parameterization for overlay %s...\n",
                fname);
        MRIStoParameterization(mris_template, mrisp_template, scale, sno*3) ;
        MRISPsetFrameVal(mrisp_template, sno*3+1, 1.0) ;
      }
    }
    else
    {
      mrisp_template = MRISPalloc(scale, PARAM_IMAGES);
      for (sno = 0; sno < SURFACES ; sno++)
      {
        if (curvature_names[sno])  /* read in precomputed curvature file */
        {
          sprintf(fname, "%s/%s.%s", surf_dir, hemi, curvature_names[sno]) ;
          if (MRISreadCurvatureFile(mris_template, fname) != NO_ERROR)
            ErrorExit(Gerror,
                      "%s: could not read curvature file '%s'\n",
                      Progname, fname) ;

          /* the two next lines were not in the original code */
          MRISaverageCurvatures(mris_template, navgs) ;
          MRISnormalizeCurvature(mris_template, which_norm) ;
        }
        else                         /* compute curvature of surface */
        {
          sprintf(fname, "%s/%s.%s", surf_dir, hemi, surface_names[sno]) ;
          if (MRISreadVertexPositions(mris_template, fname) != NO_ERROR)
            ErrorExit(ERROR_NOFILE,
                      "%s: could not read surface file %s",
                      Progname, fname) ;

          if (tnbrs > 1)
          {
            MRISresetNeighborhoodSize(mris_template, tnbrs) ;
          }
          MRIScomputeMetricProperties(mris_template) ;
          MRIScomputeSecondFundamentalForm(mris_template) ;
          MRISuseMeanCurvature(mris_template) ;
          MRISaverageCurvatures(mris_template, navgs) ;
          MRISrestoreVertexPositions(mris_template, CANONICAL_VERTICES) ;
          MRISnormalizeCurvature(mris_template, which_norm) ;
        }
        fprintf(stderr,
                "computing parameterization for surface %s...\n",
                fname);
        MRIStoParameterization(mris_template, mrisp_template, scale, sno*3) ;
        MRISPsetFrameVal(mrisp_template, sno*3+1, 1.0) ;
      }
    }
  }
  else
  {
    fprintf(stderr, "reading template parameterization from %s...\n",
            template_fname) ;
    mrisp_template = MRISPread(template_fname) ;
    if (!mrisp_template)
      ErrorExit(ERROR_NOFILE, "%s: could not open template file %s",
                Progname, template_fname) ;
    if (noverlays > 0)
    {
      if (mrisp_template->Ip->num_frame != IMAGES_PER_SURFACE*noverlays)
        ErrorExit(ERROR_BADPARM,
                  "template frames (%d) doesn't match input (%d x %d) = %d\n",
                  mrisp_template->Ip->num_frame, IMAGES_PER_SURFACE,noverlays,
                  IMAGES_PER_SURFACE*noverlays) ;
    }
  }
  if (use_defaults)
  {
    if (*IMAGEFseq_pix(mrisp_template->Ip, 0, 0, 2) <= 1.0)  /* 1st time */
    {
      parms.l_dist = 5.0 ;
      parms.l_corr = 1.0 ;
      parms.l_parea = 0.2 ;
    }
    else   /* subsequent alignments */
    {
      parms.l_dist = 5.0 ;
      parms.l_corr = 1.0 ;
      parms.l_parea = 0.2 ;
    }
  }

  if (nbrs > 1)
  {
    MRISresetNeighborhoodSize(mris, nbrs) ;
  }
  MRISprojectOntoSphere(mris, mris, DEFAULT_RADIUS) ;
  mris->status = MRIS_PARAMETERIZED_SPHERE ;
  MRIScomputeMetricProperties(mris) ;
  if (!FZERO(parms.l_dist))
  {
    MRISscaleDistances(mris, scale) ;
  }
#if 0
  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRISzeroNegativeAreas(mris) ;
  MRISstoreMetricProperties(mris) ;
#endif
  MRISstoreMeanCurvature(mris) ;  /* use curvature from file */
  MRISsetOriginalFileName(orig_name) ;
  if (inflated_name)
  {
    MRISsetInflatedFileName(inflated_name) ;
  }
  err = MRISreadOriginalProperties(mris, orig_name) ;
  if (err != 0)
  {
    printf("ERROR %d from MRISreadOriginalProperties().\n",err);
    exit(1);
  }

  if (MRISreadCanonicalCoordinates(mris, canon_name) != NO_ERROR)
    ErrorExit(ERROR_BADFILE, "%s: could not read canon surface %s",
              Progname, canon_name) ;

  if (reverse_flag)
  {
    MRISreverse(mris, REVERSE_X, 1) ;
    MRISsaveVertexPositions(mris, TMP_VERTICES) ;
    MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
    MRISreverse(mris, REVERSE_X, 0) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
  }
#if 0
  MRISsaveVertexPositions
  (mris, CANONICAL_VERTICES) ;  // uniform spherical positions
#endif
  if (starting_reg_fname)
    if (MRISreadVertexPositions(mris, starting_reg_fname) != NO_ERROR)
    {
      exit(Gerror) ;
    }

  if (multiframes)
  {
    if (use_initial_registration)
      MRISvectorRegister(mris, mrisp_template, &parms, max_passes,
                         min_degrees, max_degrees, nangles) ;
    parms.l_corr=parms.l_pcorr=0.0f;
#if 0
    parms.l_dist = 0.0 ;
    parms.l_corr = 0.0 ;
    parms.l_parea = 0.0 ;
    parms.l_area = 0.0 ;
    parms.l_parea = 0.0f ;
    parms.l_dist = 0.0 ;
    parms.l_corr = 0.0f ;
    parms.l_nlarea = 0.0f ;
    parms.l_pcorr = 0.0f ;
#endif
    MRISvectorRegister(mris,
                       mrisp_template,
                       &parms,
                       max_passes,
                       min_degrees,
                       max_degrees,
                       nangles) ;
  }
  else
  {
    double l_dist = parms.l_dist ;
    if (multi_scale > 0)
    {
      int i ;

      parms.l_dist = l_dist * pow(5.0, (multi_scale-1.0)) ;
      parms.flags |= IPFLAG_NOSCALE_TOL ;
      parms.flags &= ~IP_USE_CURVATURE ;
      for (i = 0 ; i < multi_scale ; i++)
      {
        printf("*************** round %d, l_dist = %2.3f **************\n", i,
               parms.l_dist) ;
        MRISregister(mris, mrisp_template,
                     &parms, max_passes,
                     min_degrees, max_degrees, nangles) ;
        parms.flags |= IP_NO_RIGID_ALIGN ;
        parms.flags &= ~IP_USE_INFLATED ;
        parms.l_dist /= 5 ;
      }

      if (parms.nbhd_size < 0)
      {
        parms.nbhd_size *= -1 ;
        printf("**** starting 2nd epoch, with long-range distances *****\n");
        parms.l_dist = l_dist * pow(5.0, (multi_scale-2.0)) ;
        for (i = 1 ; i < multi_scale ; i++)
        {
          printf("*********** round %d, l_dist = %2.3f *************\n", i,
                 parms.l_dist) ;
          MRISregister(mris, mrisp_template,
                       &parms, max_passes,
                       min_degrees, max_degrees, nangles) ;
          parms.l_dist /= 5 ;
        }
      }
      printf("****** final curvature registration ***************\n") ;
      if (parms.nbhd_size > 0)
      {
        parms.nbhd_size *= -1 ;  // disable long-range stuff
      }
      parms.l_dist *= 5 ;
      parms.flags |= (IP_USE_CURVATURE | IP_NO_SULC);
      MRISregister(mris, mrisp_template,
                   &parms, max_passes,
                   min_degrees, max_degrees, nangles) ;
    }
    else
      MRISregister(mris, mrisp_template,
                   &parms, max_passes,
                   min_degrees, max_degrees, nangles) ;

  }
  if (remove_negative)
  {
    parms.niterations = 1000 ;
    MRISremoveOverlapWithSmoothing(mris,&parms) ;
  }
  fprintf(stderr, "writing registered surface to %s...\n", out_fname) ;
  MRISwrite(mris, out_fname) ;
  if (jacobian_fname)
  {
    MRIScomputeMetricProperties(mris) ;
    compute_area_ratios(mris) ;  /* will put results in v->curv */
#if 0
    MRISwriteArea(mris, jacobian_fname) ;
#else
    MRISwriteCurvature(mris, jacobian_fname) ;
#endif
  }

  msec = TimerStop(&start) ;
  if (Gdiag & DIAG_SHOW)
    printf("registration took %2.2f hours\n",
           (float)msec/(1000.0f*60.0f*60.0f));
  MRISPfree(&mrisp_template) ;
  MRISfree(&mris) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Пример #8
0
int
main(int argc, char *argv[])
{
  char         **av, fname[STRLEN], *out_fname, *subject_name, *cp, *tp1_name, *tp2_name ;
  char         s1_name[STRLEN], s2_name[STRLEN], *sname ;
  int          ac, nargs, i, n, options, max_index ;
  int          msec, minutes, seconds, nsubjects, input ;
  struct timeb start ;
  MRI          *mri_seg, *mri_tmp, *mri_in ;
  TRANSFORM    *transform ;
//  int          counts ;
  int          t;
  RANDOM_FOREST *rf = NULL ;
  GCA           *gca = NULL ;

  Progname = argv[0] ;

  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  parms.width = parms.height = parms.depth = DEFAULT_VOLUME_SIZE ;
  parms.ntrees = 10 ;
  parms.max_depth = 10 ;
  parms.wsize = 1 ;
  parms.training_size = 100 ;
  parms.training_fraction = .5 ;
  parms.feature_fraction = 1 ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_rf_long_train.c,v 1.5 2012/06/15 12:22:28 fischl Exp $",
           "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  // parse command line args
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
  }
  if (argc < 3)
    usage_exit(1) ;


  // options parsed.   subjects, tp1 and tp2 and rf name remaining
  out_fname = argv[argc-1] ;
  nsubjects = (argc-2)/3 ;
  for (options = i = 0 ; i < nsubjects ; i++)
  {
    if (argv[i+1][0] == '-')
    {
      nsubjects-- ;
      options++ ;
    }
  }

  printf("training on %d subject and writing results to %s\n",
         nsubjects, out_fname) ;

  // rf_inputs can be T1, PD, ...per subject
  if (parms.nvols == 0)
    parms.nvols = ninputs ;
  /* gca reads same # of inputs as we read
     from command line - not the case if we are mapping to flash */
  n = 0 ;

  //////////////////////////////////////////////////////////////////
  // set up gca direction cosines, width, height, depth defaults

  gca = GCAread(gca_name) ;
  if (gca == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read GCA from %s", Progname, gca_name) ;
  
  
  /////////////////////////////////////////////////////////////////////////
  // weird way options and subject name are mixed here
  
  /////////////////////////////////////////////////////////
  // first calculate mean
  ////////////////////////////////////////////////////////
  // going through the subject one at a time
  max_index = nsubjects+options ;
  nargs = 0 ;
  mri_in = NULL ; 
#ifdef HAVE_OPENMP
  subject_name = NULL ; sname = NULL ; t = 0 ;
//  counts = 0 ;   would be private
  input = 0 ;
  transform = NULL ;
  tp1_name = tp2_name = NULL ;
  mri_tmp = mri_seg = NULL ;
#pragma omp parallel for firstprivate(tp1_name, tp2_name, mri_in,mri_tmp, input, xform_name, transform, subjects_dir, force_inputs, conform, Progname, mri_seg, subject_name, s1_name, s2_name, sname, t, fname) shared(mri_inputs, transforms, mri_segs,argv) schedule(static,1)
#endif
  for (i = 0 ; i < max_index ; i++)
  {
    subject_name = argv[3*i+1] ;
    tp1_name = argv[3*i+2] ;
    tp2_name = argv[3*i+3] ;
    sprintf(s1_name, "%s_%s.long.%s_base", subject_name, tp1_name, subject_name) ;
    sprintf(s2_name, "%s_%s.long.%s_base", subject_name, tp2_name, subject_name) ;

    //////////////////////////////////////////////////////////////
    printf("***************************************"
	   "************************************\n");
    printf("processing subject %s, %d of %d (%s and %s)...\n", subject_name,i+1-nargs,
	   nsubjects, s1_name,s2_name);

    for (t = 0 ; t < 2 ; t++)
    {
      sname = t == 0 ? s1_name : s2_name;

      // reading this subject segmentation
      sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, seg_dir) ;
      if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
	fprintf(stderr, "Reading segmentation from %s...\n", fname) ;
      mri_seg = MRIread(fname) ;
      if (!mri_seg)
	ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s",
		  Progname, fname) ;

      if ((mri_seg->type != MRI_UCHAR) && (make_uchar != 0))
      {
	MRI *mri_tmp ;
	mri_tmp = MRIchangeType(mri_seg, MRI_UCHAR, 0, 1,1);
	MRIfree(&mri_seg) ;
	mri_seg = mri_tmp ;
      }

      if (wmsa_fname)
      {
	MRI *mri_wmsa ;
	sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, wmsa_fname) ;
	printf("reading WMSA labels from %s...\n", fname) ;
	mri_wmsa = MRIread(fname) ;
	if (mri_wmsa == NULL)
	  ErrorExit(ERROR_NOFILE, "%s: could not read WMSA file %s", fname) ;
	MRIbinarize(mri_wmsa, mri_wmsa,  1, 0, WM_hypointensities) ;
	MRIcopyLabel(mri_wmsa, mri_seg, WM_hypointensities) ;
	lateralize_hypointensities(mri_seg) ;
	if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON )
	{
	  char s[STRLEN] ;
	  sprintf(s, "%s/%s/mri/seg_%s",
		  subjects_dir, subject_name, wmsa_fname) ;
	  MRIwrite(mri_seg, s) ;
	}
      }
      if (binarize)
      {
	int j ;
	for (j = 0 ; j < 256 ; j++)
	{
	  if (j == binarize_in)
	    MRIreplaceValues(mri_seg, mri_seg, j, binarize_out) ;
	  else
	    MRIreplaceValues(mri_seg, mri_seg, j, 0) ;
	}
      }
      if (insert_fname)
      {
	MRI *mri_insert ;
	
	sprintf(fname, "%s/%s/mri/%s",
		subjects_dir, subject_name, insert_fname) ;
	mri_insert = MRIread(fname) ;
	if (mri_insert == NULL)
	  ErrorExit(ERROR_NOFILE,
		    "%s: could not read volume from %s for insertion",
		    Progname, insert_fname) ;
	
	MRIbinarize(mri_insert, mri_insert, 1, 0, insert_label) ;
	MRIcopyLabel(mri_insert, mri_seg, insert_label) ;
	MRIfree(&mri_insert) ;
      }
      
      replaceLabels(mri_seg) ;
      MRIeraseBorderPlanes(mri_seg, 1) ;

      ////////////////////////////////////////////////////////////
      if (DIAG_VERBOSE_ON)
	fprintf(stderr,
		"Gather all input volumes for the subject %s.\n",
		subject_name);
      // inputs must be coregistered
      // note that inputs are T1, PD, ... per subject (same TE, TR, FA)
      for (input = 0 ; input < ninputs ; input++)
      {
	//////////// set the gca type //////////////////////////////
	// is this T1/PD training?
	// how can we allow flash data training ???????
	// currently checks the TE, TR, FA to be the same for all inputs
	// thus we cannot allow flash data training.
	////////////////////////////////////////////////////////////
	
	sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname,input_names[input]);
	if (DIAG_VERBOSE_ON)
	  printf("reading co-registered input from %s...\n", fname) ;
	fprintf(stderr, "   reading input %d: %s\n", input, fname);
	mri_tmp = MRIread(fname) ;
	if (!mri_tmp)
	  ErrorExit
	    (ERROR_NOFILE,
	     "%s: could not read image from file %s", Progname, fname) ;
	// input check 1
	if (getSliceDirection(mri_tmp) != MRI_CORONAL)
	{
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: must be in coronal direction, but it is not\n",
	     fname);
	}
	// input check 2
	if (conform &&
	    (mri_tmp->xsize != 1 || mri_tmp->ysize != 1 || mri_tmp->zsize != 1))
	{
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: must have 1mm voxel size, but have (%f, %f, %f)\n",
	     fname, mri_tmp->xsize, mri_tmp->ysize, mri_tmp->ysize);
	}
	// input check 3 is removed.  now we can handle c_(ras) != 0 case
	// input check 4
	if (i == 0)
	{
	  TRs[input] = mri_tmp->tr ;
	  FAs[input] = mri_tmp->flip_angle ;
	  TEs[input] = mri_tmp->te ;
	}
	else if ((force_inputs == 0) &&
		 (!FEQUAL(TRs[input],mri_tmp->tr) ||
		  !FEQUAL(FAs[input],mri_tmp->flip_angle) ||
		  !FEQUAL(TEs[input], mri_tmp->te)))
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: subject %s input volume %s: sequence parameters "
	     "(%2.1f, %2.1f, %2.1f)"
	     "don't match other inputs (%2.1f, %2.1f, %2.1f)",
	     Progname, subject_name, fname,
	     mri_tmp->tr, DEGREES(mri_tmp->flip_angle), mri_tmp->te,
	     TRs[input], DEGREES(FAs[input]), TEs[input]) ;
	// first time do the following
	if (input == 0)
	{
	  int nframes = ninputs ;
	  
	  ///////////////////////////////////////////////////////////
	  mri_in = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
				    mri_tmp->type, nframes) ;
	  if (!mri_in)
	    ErrorExit
	      (ERROR_NOMEMORY,
	       "%s: could not allocate input volume %dx%dx%dx%d",
	       mri_tmp->width, mri_tmp->height, mri_tmp->depth,nframes) ;
	  MRIcopyHeader(mri_tmp, mri_in) ;
	}
	// -mask option ////////////////////////////////////////////
	if (mask_fname)
	{
	  MRI *mri_mask ;
	  
	  sprintf(fname, "%s/%s/mri/%s",
		  subjects_dir, subject_name, mask_fname);
	  printf("reading volume %s for masking...\n", fname) ;
	  mri_mask = MRIread(fname) ;
	  if (!mri_mask)
	  ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
		    Progname, fname) ;
	
	  MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
	  MRIfree(&mri_mask) ;
	}
	MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
	MRIfree(&mri_tmp) ;

      }// end of inputs per subject
    
    
      /////////////////////////////////////////////////////////
      // xform_name is given, then we can use the consistent c_(r,a,s) for gca
      /////////////////////////////////////////////////////////
      if (xform_name)
      {
	// we read talairach.xfm which is a RAS-to-RAS
	sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, sname, xform_name) ;
	if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
	  printf("INFO: reading transform file %s...\n", fname);
	if (!FileExists(fname))
	{
	  fprintf(stderr,"ERROR: cannot find transform file %s\n",fname);
	  exit(1);
	}
	transform = TransformRead(fname);
	if (!transform)
	  ErrorExit(ERROR_NOFILE, "%s: could not read transform from file %s",
		    Progname, fname);
	
//        modify_transform(transform, mri_in, gca);
	// Here we do 2 things
	// 1. modify gca direction cosines to
	// that of the transform destination (both linear and non-linear)
	// 2. if ras-to-ras transform,
      // then change it to vox-to-vox transform (linear case)
	
      // modify transform to store inverse also
	TransformInvert(transform, mri_in) ;
      }
      else
      {
//        GCAreinit(mri_in, gca);
	// just use the input value, since dst = src volume
	transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;
      }
      
      /////////////////////////////////////////////////////////
      if (do_sanity_check)
      {
	// conduct a sanity check of particular labels, most importantly
	// hippocampus, that such labels do not exist in talairach coords
	// where they are known not to belong (indicating a bad manual edit)
	int errs = check(mri_seg, subjects_dir, subject_name);
	if (errs) 
	{
	  printf(
	    "ERROR: mri_ca_train: possible bad training data! subject:\n"
	    "\t%s/%s\n\n", subjects_dir, subject_name);
	  fflush(stdout) ;
	  sanity_check_badsubj_count++;
	}
      }
      
      mri_segs[i][t] = mri_seg ;
      mri_inputs[i][t] = mri_in ;
      transforms[i][t] = transform ;
    }
  }
  rf = train_rforest(mri_inputs, mri_segs, transforms, nsubjects, gca, &parms, wm_thresh,wmsa_whalf, 2) ;
  printf("writing random forest to %s\n", out_fname) ;
  if (RFwrite(rf, out_fname) != NO_ERROR)
    ErrorExit
      (ERROR_BADFILE, "%s: could not write rf to %s", Progname, out_fname) ;
  
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("classifier array training took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
  }
Пример #9
0
int
main(int argc, char *argv[]) {
  char          **av, fname[STRLEN], *T1_fname, *PD_fname, *output_dir, *mdir ;
  int           ac, nargs, msec, s ;
  MRI_SURFACE   *mris ;
  MRI           *mri_flash1, *mri_flash2, *mri_masked, *mri_masked_smooth, *mri_kernel,
  *mri_mean, *mri_dif, *mri_binary, *mri_distance ;
  MRI *mri_smooth, *mri_grad, *mri_inner ;
  struct timeb  then ;
  double        l_spring ;
  MRI_SEGMENTATION *mriseg ;


  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_AA_shrinkwrap.c,v 1.5 2011/03/02 00:04:34 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Gdiag |= DIAG_SHOW ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  memset(&parms, 0, sizeof(parms)) ;

  parms.projection = NO_PROJECTION ;
  parms.tol = 0.05 ;
  parms.check_tol = 1 ;
  parms.ignore_energy = 1 ;
  parms.dt = 0.5f ;
  parms.base_dt = BASE_DT_SCALE*parms.dt ;

  parms.l_spring_norm = 1 ;
  parms.l_shrinkwrap = 0 ;
  parms.l_intensity = 1 ;

  parms.niterations = 0 ;
  parms.write_iterations = 0 /*WRITE_ITERATIONS */;
  parms.integration_type = INTEGRATE_MOMENTUM ;
  parms.momentum = 0.0 /*0.8*/ ;
  parms.l_intensity = 1 ;
  parms.dt_increase = 1.0 /* DT_INCREASE */;
  parms.dt_decrease = 0.50 /* DT_DECREASE*/ ;
  parms.error_ratio = 50.0 /*ERROR_RATIO */;
  /*  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;*/
  parms.l_surf_repulse = 0.0 ;
  parms.l_repulse = 0 /*1*/ ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  mdir = getenv("FREESURFER_HOME") ;
  if (!mdir)
    ErrorExit(ERROR_BADPARM, "FREESURFER_HOME not defined in environment") ;

  if (argc < 4)
    usage_exit() ;

  /* set default parameters for white and gray matter surfaces */
  parms.niterations = 1000 ;
  if (parms.momentum < 0.0)
    parms.momentum = 0.0 /*0.75*/ ;

  TimerStart(&then) ;
  T1_fname = argv[1] ;
  PD_fname = argv[2] ;
  output_dir = argv[3] ;
  fprintf(stderr, "reading volume %s...\n", T1_fname) ;
  mri_flash1 = MRIread(T1_fname) ;
  if (!mri_flash1)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s", Progname, T1_fname) ;

  mri_flash2 = MRIread(PD_fname) ;
  if (!mri_flash2)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s", Progname, T1_fname) ;

  //  setMRIforSurface(mri_flash1);
  sprintf(fname, "%s/lib/bem/ic%d.tri", mdir, ic_init) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read icosahedron %s", Progname, fname) ;

  mri_mean = MRImean(mri_flash1, NULL, 5) ;
  MRIwrite(mri_mean, "mean.mgz") ;

  mri_dif = MRIabsdiff(mri_flash1, mri_flash2, NULL) ;
  MRIwrite(mri_dif, "dif.mgz") ;

  mriseg = MRIsegment(mri_mean, 30, 100000) ;
  s = MRIsegmentMax(mriseg) ;
  mri_masked = MRIsegmentToImage(mri_flash1, NULL, mriseg, s) ;
  MRIwrite(mri_masked, "mask.mgz") ;
  MRIsegmentFree(&mriseg) ;

  // MRIthresholdMask(mri_dif, mri_masked, mri_dif, 1, 0) ;
  // MRIwrite(mri_dif, "dif_masked.mgz") ;


  mri_kernel = MRIgaussian1d(2, 0) ;
  mri_smooth = MRIconvolveGaussian(mri_dif, NULL, mri_kernel) ;
  MRIwrite(mri_smooth, "smooth.mgz") ;
  MRIScopyVolGeomFromMRI(mris, mri_smooth) ;
  mris->useRealRAS = 1 ;

  initialize_surface_position(mris, mri_dif, 1, &parms) ;
  MRISwrite(mris, "init") ;
  MRISrepositionToInnerSkull(mris, mri_smooth, &parms) ;

  exit(0) ;
  mri_grad = MRIsobel(mri_smooth, NULL, NULL) ;
  MRIwrite(mri_grad, "grad.mgz") ;
  mri_inner = MRIfindInnerBoundary(mri_dif, mri_grad, NULL, 5.0) ;
  MRIwrite(mri_inner, "inner.mgz") ;
  MRIbinarize(mri_inner, mri_inner, 10, 0, 128) ;

  MRISpositionOptimalSphere(mris, mri_inner, 6) ;
  MRISwrite(mris, "optimal") ;
  exit(0) ;
  parms.sigma = 4 / mri_flash1->xsize ;
  // mri_dist = create_distance_map(mri_masked, NULL, BORDER_VAL, OUTSIDE_BORDER_STEP) ;
  MRISsetVals(mris,parms.sigma) ;
  MRIScopyValToVal2(mris) ;
  MRISsetVals(mris, 0) ;
  sprintf(parms.base_name, "%s_inner_skull%s%s", "test", output_suffix, suffix) ;
  parms.mri_brain = mri_masked ;
  l_spring = parms.l_spring_norm ;
  mri_kernel = MRIgaussian1d(parms.sigma, 0) ;


  mri_binary = MRIbinarize(mri_dif, mri_binary, 40, 0, 128) ;
  MRIwrite(mri_binary, "bin.mgz") ;
  mri_distance = MRIdistanceTransform(mri_binary, NULL, 128, 100, DTRANS_MODE_SIGNED, NULL) ;
  MRIwrite(mri_distance, "dist.mgz") ;
  mri_masked_smooth = MRIconvolveGaussian(mri_distance, NULL, mri_kernel) ;
  MRIfree(&mri_kernel) ;
  MRIwrite(mri_masked_smooth, "dif_smooth.mgz") ;

  MRISwrite(mris, "inner_skull.tri") ;

  msec = TimerStop(&then) ;
  fprintf(stderr,"positioning took %2.1f minutes\n", (float)msec/(60*1000.0f));
  exit(0) ;
  return(0) ;  /* for ansi */
}
Пример #10
0
Файл: pap.c Проект: vstakhov/mpd
void
PapInput(Link l, AuthData auth, const u_char *pkt, u_short len)
{
	Auth const a = &l->lcp.auth;
	PapInfo const pap = &a->pap;
	PapParams const pp = &auth->params.pap;
	char failMesg[64];
	char buf[16];

	switch (auth->code) {
	case PAP_REQUEST:
		{
			char *name_ptr, name[256];
			char *pass_ptr, pass[256];
			int name_len, pass_len;

			/* Is this appropriate? */
			if (a->peer_to_self != PROTO_PAP) {
				if (l->lcp.want_auth == PROTO_PAP && a->peer_to_self == 0) {
					Log(LG_AUTH, ("[%s] PAP: retransmitting ACK",
					    l->name));
					AuthOutput(l, PROTO_PAP, PAP_ACK, auth->id,
					    (u_char *)AUTH_MSG_WELCOME, strlen(AUTH_MSG_WELCOME), 1, 0);
					break;
				}
				Log(LG_AUTH, ("[%s] PAP: %s not expected",
				    l->name, PapCode(auth->code, buf, sizeof(buf))));
				auth->why_fail = AUTH_FAIL_NOT_EXPECTED;
				PapInputFinish(l, auth);
				return;
			}
			/* Sanity check packet and extract fields */
			if (len < 1)
				goto error;

			name_len = pkt[0];
			name_ptr = (char *)pkt + 1;

			if (1 + name_len >= len)
				goto error;

			pass_len = pkt[1 + name_len];
			pass_ptr = (char *)pkt + 1 + name_len + 1;

			if (name_len + 1 + pass_len + 1 > len)
				goto error;

			memcpy(name, name_ptr, name_len);
			name[name_len] = 0;
			memcpy(pass, pass_ptr, pass_len);
			pass[pass_len] = 0;

			strlcpy(pp->peer_name, name, sizeof(pp->peer_name));
			strlcpy(pp->peer_pass, pass, sizeof(pp->peer_pass));
			strlcpy(auth->params.authname, name, sizeof(auth->params.authname));
			auth->params.password[0] = 0;

			auth->finish = PapInputFinish;
			AuthAsyncStart(l, auth);
			return;
		}
		break;

	case PAP_ACK:
	case PAP_NAK:
		{
			/* Is this appropriate? */
			if (a->self_to_peer != PROTO_PAP) {
				Log(LG_AUTH, ("[%s] PAP: %s not expected",
				    l->name, PapCode(auth->code, buf, sizeof(buf))));
				break;
			}
			/* Stop resend timer */
			TimerStop(&pap->timer);

			/* Show reply message */
			if (len > 0) {
				int msg_len = pkt[0];
				char *msg = (char *)&pkt[1];

				if (msg_len < len - 1)
					msg_len = len - 1;
				ShowMesg(LG_AUTH, l->name, msg, msg_len);
			}
			/* Done with my auth to peer */
			AuthFinish(l, AUTH_SELF_TO_PEER, auth->code == PAP_ACK);
		}
		break;

	default:
		Log(LG_AUTH, ("[%s] PAP: unknown code", l->name));
		break;
	}
	AuthDataDestroy(auth);
	return;

error:
	Log(LG_AUTH, ("[%s] PAP: Bad PAP packet", l->name));
	auth->why_fail = AUTH_FAIL_INVALID_PACKET;
	AuthFailMsg(auth, failMesg, sizeof(failMesg));
	AuthOutput(l, PROTO_PAP, PAP_NAK, auth->id, (u_char *)failMesg, strlen(failMesg), 1, 0);
	AuthFinish(l, AUTH_PEER_TO_SELF, FALSE);
	AuthDataDestroy(auth);
}
Пример #11
0
Файл: pap.c Проект: vstakhov/mpd
void
PapStop(PapInfo pap)
{
	TimerStop(&pap->timer);
}
Пример #12
0
//*****************************************************************************
//
//! \brief xtimer 001 test execute main body.
//!
//! \return None.
//
//*****************************************************************************
static void xTimer001Execute(void)
{
    unsigned long ulTemp;
    unsigned long ulBase;
    int i, j, k;

   
    //
    // Test the register write and read.
    //
    for(i = 0; i < 2; i++)
    {
        ulBase = ulTimerBase[i];

        for(j = 0; j < 4; j++)
        {
            xTimerInitConfig(ulBase, ulTimerChannel[j], xTIMER_MODE_PERIODIC |
                             xTIMER_COUNT_UP, 100);
            ulTemp = xHWREG(ulBase + TIMER_PSCR);
            TestAssert(ulTemp == 2, 
                       "xtimer API \"xTimerInitConfig- prescale \" error");            
            ulTemp = xHWREG(ulBase + TIMER_CRR);
            TestAssert(ulTemp == 40000, 
                       "xtimer API \"xTimerInitConfig- CRR \" error");
            ulTemp = xHWREG(ulBase + TIMER_CNTCFR) & TIMER_CNTCFR_DIR;
            TestAssert(ulTemp == xTIMER_COUNT_UP, 
                       "xtimer API \"xTimerInitConfig- DIR \" error");
            
            xTimerInitConfig(ulBase, ulTimerChannel[j], xTIMER_MODE_TOGGLE |
                             xTIMER_COUNT_UP, 100);
            ulTemp = xHWREG(ulBase + TIMER_CH0OCFR + ulTimerChannel[j] * 4) & 
              TIMER_CH0OCFR_CH0OM_M;
            TestAssert(ulTemp == TIMER_CH0OCFR_CH0OM_TOGGLE, 
                       "xtimer API \"xTimerInitConfig- DIR \" error");
            ulTemp = xHWREG(ulBase + TIMER_CH0CCR + ulTimerChannel[j] * 4);
            TestAssert(ulTemp == 20000, 
                       "xtimer API \"xTimerInitConfig- DIR \" error");   
            
            //
            // Prescale set and get test
            //
            xTimerPrescaleSet(ulBase, ulTimerChannel[j], 1000);
            ulTemp = xTimerPrescaleGet(ulBase, ulTimerChannel[j]);
            TestAssert(ulTemp == 1000, 
                       "xtimer API \"Prescale set and get test \" error"); 
            
            //
            // Match set and get test
            //
            xTimerMatchSet(ulBase, ulTimerChannel[j], 1000);
            ulTemp = xTimerMatchGet(ulBase, ulTimerChannel[j]);
            TestAssert(ulTemp == 1000, 
                       "xtimer API \"Match set and get test \" error"); 
            
            //
            // xINT enable test
            //
            xTimerIntEnable(ulBase, ulTimerChannel[j], xTIMER_INT_CAP_EVENT);
            ulTemp = xHWREG(ulBase + TIMER_ICTR) & (TIMER_CHCTR_CH0CCIE << ulTimerChannel[j]);
            TestAssert(ulTemp == TIMER_CHCTR_CH0CCIE << ulTimerChannel[j], 
                       "xtimer API \"xINT enable test \" error"); 
            
            //
            // xINT disable test
            //
            xTimerIntDisable(ulBase, ulTimerChannel[j], xTIMER_INT_CAP_EVENT);
            ulTemp = xHWREG(ulBase + TIMER_ICTR) & (TIMER_CHCTR_CH0CCIE << ulTimerChannel[j]);
            TestAssert(ulTemp == 0, 
                       "xtimer API \"xINT disable test \" error"); 
        }
        
        //
        // xTimer start test
        //
        xTimerStart(ulBase, ulTimerChannel[0]);
        ulTemp = xHWREG(ulBase + TIMER_CTR) & TIMER_CTR_TME;
        TestAssert(ulTemp == TIMER_CTR_TME, 
                   "xtimer API \"xTimer start test \" error");
        
        //
        // xTimer stop test
        //
        xTimerStop(ulBase, ulTimerChannel[0]);
        ulTemp = xHWREG(ulBase + TIMER_CTR) & TIMER_CTR_TME;
        TestAssert(ulTemp == 0, 
                   "xtimer API \"xTimer stop test \" error");    
        
    
        //*********************************************************************
        // Timer base configure test
        //*********************************************************************
        
        //
        // Counter mode test
        //
        for(j = 0; j < 5; j++)
        {
            TimeBaseConfigure(ulBase, ulTimerMode[j], 100, 100, ulTimerReloadMode[0]);
            ulTemp = xHWREG(ulBase + TIMER_CNTCFR) & 0xFFFF0000;
            TestAssert(ulTemp == ulTimerMode[j], 
                       "xtimer API \"Timer base configure -counter mode \" error");
        }
        
        //
        // Counter reload set test
        //
        for(j = 0; j < 3; j++)
        {
            TimeBaseConfigure(ulBase, ulTimerMode[0], ulTimerCRRData[j], 
                              100, ulTimerReloadMode[0]);
            ulTemp = TimerCRRGet(ulBase);
            TestAssert(ulTemp == ulTimerCRRData[j], 
                       "xtimer API \"Timer base configure -CRR set \" error");
        } 
        
        //
        // Counter prescale set test
        //
        for(j = 0; j < 3; j++)
        {
            TimeBaseConfigure(ulBase, ulTimerMode[0], ulTimerCRRData[0], 
                              ulTimerPrescaleData[j], ulTimerReloadMode[0]);
            ulTemp = TimerPerscalerGet(ulBase);
            TestAssert(ulTemp == ulTimerPrescaleData[j], 
                       "xtimer API \"Timer base configure -PSC set \" error");
        }
        
        //
        // Counter reload mode test
        //
		/*
        for(j = 0; j < 2; j++)        
        {
            TimeBaseConfigure(ulBase, ulTimerMode[0], ulTimerCRRData[0], 
                              ulTimerPrescaleData[j], ulTimerReloadMode[j]);
            ulTemp = xHWREG(ulBase + TIMER_EVGR) & TIMER_EVGR_UEVG;
            TestAssert(ulTemp == ulTimerReloadMode[j], 
                       "xtimer API \"Timer base configure -RM set \" error");
        }
		*/
        
        for(j = 0; j < 4; j++)
        {
            //
            // Output enable test
            //
            for(k = 0; k < 2; k++)
            {
                TimerOutputConfigure(ulBase, ulTimerChannel[j], ulTimerOutputEnable[k],
                                     ulTimeCHPolarity[0], ulTimerOutputMode[0], 
                                     ulTimerCmpValue[0]);
                ulTemp = xHWREG(ulBase + TIMER_CHCTR) & (1 << (ulTimerChannel[j] * 2));
                TestAssert(ulTemp == (ulTimerOutputEnable[k] << (ulTimerChannel[j] * 2)), 
                           "xtimer API \"Output enable set test\" error");        
            }
            
            //
            // Channel polarity
            //
            for(k = 0; k < 2; k++)
            {
                TimerOutputConfigure(ulBase, ulTimerChannel[j], ulTimerOutputEnable[0],
                                     ulTimeCHPolarity[k], ulTimerOutputMode[0], 
                                     ulTimerCmpValue[0]);
                ulTemp = xHWREG(ulBase + TIMER_CHPOLR) & (1 << (ulTimerChannel[j] * 2));
                TestAssert(ulTemp == ulTimeCHPolarity[k] << (ulTimerChannel[j] * 2), 
                           "xtimer API \"Channel polarity set test\" error"); 
            }
            
            //
            // Output Mode test
            //
            for(k = 0; k < 6; k++)
            {
                TimerOutputConfigure(ulBase, ulTimerChannel[j], ulTimerOutputEnable[0],
                                     ulTimeCHPolarity[0], ulTimerOutputMode[k], 
                                     ulTimerCmpValue[0]);
                ulTemp = xHWREG(ulBase + TIMER_CH0OCFR + ulTimerChannel[j] * 4) & 
                  TIMER_CH0OCFR_CH0OM_M;
                TestAssert(ulTemp == ulTimerOutputMode[k], 
                           "xtimer API \"Output Mode set test\" error"); 
            }
            
            //
            // Compare value set test
            //
            for(k = 0; k < 3; k++)
            {
                TimerOutputConfigure(ulBase, ulTimerChannel[j], ulTimerOutputEnable[0],
                                     ulTimeCHPolarity[0], ulTimerOutputMode[0], 
                                     ulTimerCmpValue[k]);
                ulTemp =  TimerCaptureCompareGet(ulBase, ulTimerChannel[j]);
                TestAssert(ulTemp == ulTimerCmpValue[k], 
                           "xtimer API \"Compare value set test\" error");
            }
            
            //
            // Capture source select test
            //
            for(k = 0; k < 3; k++)
            {
                TimerCaptureConfigure(ulBase, ulTimerChannel[j], ulTimeCHPolarity[0],
                                      ulSelect[k], ulPrescaler[0], ucFilter[0]);
                ulTemp =  xHWREG(ulBase + TIMER_CH0ICFR + ulTimerChannel[j] * 4) & 
                  TIMER_CH0ICFR_CH0CCS_M;
                TestAssert(ulTemp == ulSelect[k], 
                           "xtimer API \"Capture source select test\" error");
            }
            
            //
            // Capture prescale select test
            //
            for(k = 0; k < 4; k++)
            {
                TimerCaptureConfigure(ulBase, ulTimerChannel[j], ulTimeCHPolarity[0],
                                      ulSelect[0], ulPrescaler[k], ucFilter[0]);
                ulTemp =  xHWREG(ulBase + TIMER_CH0ICFR +  ulTimerChannel[j] * 4) & 
                  TIMER_CH0ICFR_CH0PSC_M;
                TestAssert(ulTemp == ulPrescaler[k], 
                           "xtimer API \"Capture prescale select test\" error");
            }     
            
            //
            // Capture filter select test
            //
            for(k = 0; k < 3; k++)
            {
                TimerCaptureConfigure(ulBase, ulTimerChannel[j], ulTimeCHPolarity[0],
                                      ulSelect[0], ulPrescaler[0], ucFilter[k]);
                ulTemp =  xHWREG(ulBase + TIMER_CH0ICFR +  ulTimerChannel[j] * 4) & 
                  TIMER_CH0ICFR_TI0F_M;
                TestAssert(ulTemp == ucFilter[k], 
                           "xtimer API \"Capture filter select test\" error");
            }
            
            //
            // Forces CHxOREF waveform to active or inactive
            //
            for(k = 0; k < 2; k++)
            {
                TimerForcedOREF(ulBase, ulTimerChannel[j], ulForcedAction[k]);
                ulTemp = xHWREG(ulBase + TIMER_CH0OCFR  + ulTimerChannel[j] * 4)
                  & TIMER_CH0OCFR_CH0OM_M;
                TestAssert(ulTemp == ulForcedAction[k], 
                           "xtimer API \"Forces CHxOREF waveform set test\" error");
            }
            
            //
            // Timer one pulse active configure
            //
			/*
            for(k = 0; k < 2; k++)
            {
                Timer1PulseActiveConfigure(ulBase, ulTimerChannel[j], ulActive[k]);
                ulTemp = xHWREG(ulBase + TIMER_CH0OCFR + ulTimerChannel[j] * 4) & 
                  TIMER_CH0OCFR_CH0IMAE;
                TestAssert(ulTemp == ulActive[k], 
                           "xtimer API \" Timer one pulse active configure\" error");
            }
			*/
            
            //
            // Channel enable test
            //
            for(k = 0; k < 2; k++)
            {
                 TimerCHConfigure(ulBase, ulTimerChannel[j], ulControl[k]);
                 ulTemp = xHWREG(ulBase + TIMER_CHCTR) & (1 << (ulTimerChannel[j] * 2));
                 TestAssert(ulTemp == (ulControl[k] << (ulTimerChannel[j] * 2)), 
                           "xtimer API \" Channel enable test\" error");
            }
        }
        
        //
        // Timer start test
        //
        TimerStart(ulBase);
        ulTemp =  xHWREG(ulBase + TIMER_CTR) & TIMER_CTR_TME;
        TestAssert(ulTemp == TIMER_CTR_TME, 
                   "xtimer API \"Timer start test \" error");     
        
        //
        // Timer stop test
        //
        TimerStop(ulBase);
        ulTemp =  xHWREG(ulBase + TIMER_CTR) & TIMER_CTR_TME;
        TestAssert(ulTemp == 0, 
                   "xtimer API \"Timer stop test \" error"); 
        
        //
        // ITI0 as the clock source test
        //
        TimerITIExtClkConfigure(ulBase, TIMER_TRSEL_ITI0);
        ulTemp = xHWREG(ulBase + TIMER_TRCFR) & TIMER_TRCFR_TRSEL_M;
        TestAssert(ulTemp == TIMER_TRSEL_ITI0, 
                   "xtimer API \"Timer stop test \" error"); 
        ulTemp = xHWREG(ulBase + TIMER_MDCFR) & TIMER_MDCFR_SMSEL_STIED;
        TestAssert(ulTemp == TIMER_MDCFR_SMSEL_STIED, 
                   "xtimer API \"Timer stop test \" error"); 
        
        //
        // ETI prescaler set test
        //
        for(k = 0; k < 4; k++)
        {
            TimerETIExtClkConfigure(ulBase, ulEXIPrescaleValue[k],
                                    ulEXIPolarity[0], ucFilter[0]);
            ulTemp = xHWREG(ulBase + TIMER_TRCFR) & TIMER_TRCFR_ETIPSC_M;
            TestAssert(ulTemp == ulEXIPrescaleValue[k], 
                       "xtimer API \"ETI prescaler set test \" error"); 
        }
        
        //
        // ETI polarity set test
        //
        for(k = 0; k < 2; k++)
        {
            TimerETIExtClkConfigure(ulBase, ulEXIPrescaleValue[0],
                                    ulEXIPolarity[k], ucFilter[0]);
            ulTemp = xHWREG(ulBase + TIMER_TRCFR) & TIMER_TRCFR_ETIPOL;
            TestAssert(ulTemp == ulEXIPolarity[k], 
                       "xtimer API \"ETI polarity set test \" error"); 
        }
        
        //
        // ETI filter set test
        //
        for(k = 0; k < 3; k++)
        {
            TimerETIExtClkConfigure(ulBase, ulEXIPrescaleValue[0],
                                    ulEXIPolarity[0], ucFilter[k]);
            ulTemp = xHWREG(ulBase + TIMER_TRCFR) & TIMER_TRCFR_ETF_M;
            TestAssert(ulTemp == (ucFilter[k] << 8), 
                       "xtimer API \"ETI filter set test \" error"); 
        }  
        
        //
        // ETI enable set test
        //
        ulTemp = xHWREG(ulBase + TIMER_TRCFR) & TIMER_TRCFR_ECME ;
        TestAssert(ulTemp == TIMER_TRCFR_ECME, 
                   "xtimer API \" ETI enable set test \" error");
        
        //
        // Prescaler update configure
        //
		/*
        for(k = 0; k < 2; k++)
        {
            TimerPrescalerConfigure(ulBase, ulTimerPrescaleData[0], ulPSCReloadTime[k]);
            ulTemp = xHWREG(ulBase + TIMER_EVGR) & TIMER_EVGR_UEVG;
            TestAssert(ulTemp == ulPSCReloadTime[k], 
                       "xtimer API \" Prescaler update configure \" error");
        }
		*/
        
        //
        // Decode mode set test
        //
        for(k = 0; k < 3; k++)
        {
            TimerDecoderConfigure(ulBase, ulDecodeMode[k], TIMER_CHP_NONINVERTED, 
                                  TIMER_CHP_NONINVERTED);
            ulTemp = xHWREG(ulBase + TIMER_MDCFR) & TIMER_MDCFR_SMSEL_M;
            TestAssert(ulTemp == ulDecodeMode[k], 
                       "xtimer API \" Decode mode set test \" error"); 
        }
        
        //
        // CRR preload configure
        //
		/*
        for(k = 0; k < 2; k++)
        {
            TimerCRRPreloadConfigure(ulBase, ulProload[k]);
            ulTemp = xHWREG(ulBase + TIMER_CTR) & TIMER_CTR_CRBE;
            TestAssert(ulTemp == ulProload[k], 
                       "xtimer API \" CRR preload configure \" error");             
        }
		*/
        
        //
        // One pulse mode test
        //
        for(k = 0; k < 2; k++)
        {
            TimerOnePulseModeConfigure(ulBase, ulOnepulseMode[k]);
            ulTemp = xHWREG(ulBase + TIMER_MDCFR) & TIMER_MDCFR_SPMSET;
            TestAssert(ulTemp == ulOnepulseMode[k], 
                       "xtimer API \" One pulse mode test \" error");
        }
        
        //
        //  Timer master output source select
        //
        for(k = 0; k < 8; k++)
        {
            TimerMasterOutputSrcSelect(ulBase, ulMasterOutputSrc[k]);
            ulTemp = xHWREG(ulBase + TIMER_MDCFR) & TIMER_MDCFR_MMSEL_M;
            TestAssert(ulTemp == ulMasterOutputSrc[k], 
                       "xtimer API \" Timer master output source select \" error");
        }
        
        //
        // Slave mode set configure
        //
        for(k = 0; k < 4; k++)
        {
            TimerSlaveModeConfigure(ulBase, ulSlaveMode[k]);
            ulTemp = xHWREG(ulBase + TIMER_MDCFR) & TIMER_MDCFR_SMSEL_M;
            TestAssert(ulTemp == ulSlaveMode[k], 
                       "xtimer API \" Slave mode set configure \" error");
        }
        
        //
        // Counter set and get test
        //
        for(k = 0; k < 3; k++)
        {
            TimerCounterSet(ulBase, ulTimerCounter[k]);
            ulTemp = TimerCounterGet(ulBase);
            TestAssert(ulTemp == ulTimerCounter[k], 
                       "xtimer API \" Counter set and get test \" error");
        }
        
        //
        // Event generate test
        //
        for(k = 0; k < 6; k++)
        {
            TimerEventGenerate(ulBase, ulEvent[k]);
            ulTemp = TimerFlagStatusGet(ulBase, ulEvent[k]);
            TestAssert(ulTemp == xtrue, 
                       "xtimer API \" Event generate test \" error");
        }
        
        //
        // Int enable test
        //
        for(k = 0; k < 6; k++)
        {
            TimerIntEnable(ulBase, ulInt[k]);
            ulTemp = xHWREG(ulBase + TIMER_ICTR) & ulInt[k];
            TestAssert(ulTemp == ulInt[k], 
                       "xtimer API \" Int enable test \" error");
        }
        
        //
        // Int disable test
        //
        for(k = 0; k < 6; k++)
        {
            TimerIntDisable(ulBase, ulInt[k]);
            ulTemp = xHWREG(ulBase + TIMER_ICTR) & ulInt[k];
            TestAssert(ulTemp == 0, 
                       "xtimer API \" Int disable test \" error");
        }
    }       
  
}
Пример #13
0
int
main(int argc, char *argv[])
{
  char        **av, *out_name ;
  int          ac, nargs ;
  int          msec, minutes, seconds ;
  struct timeb start ;
  MRI_SURFACE  *mris ;
  GCA_MORPH    *gcam ;
  MRI          *mri = NULL ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_interpolate_warp.c,v 1.5 2011/10/07 12:07:26 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
  {
    usage_exit(1) ;
  }


  /*
    note that a "forward" morph means a retraction, so we reverse the order of the argvs here.
    This means that for every voxel in the inflated image we have a vector that points to where in
    the original image it came from, and *NOT* the reverse.
  */
  mris = MRISread(argv[2]) ;
  if (mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read source surface %s\n", Progname,argv[2]) ;

  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  if (MRISreadVertexPositions(mris, argv[1]) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read target surface %s\n", Progname,argv[1]) ;

  if (like_vol_name == NULL)
  {
    mri = MRIallocSequence(mris->vg.width, mris->vg.height, mris->vg.depth, MRI_FLOAT, 3) ;
    MRIcopyVolGeomToMRI(mri, &mris->vg) ;
  }
  else
  {
    MRI *mri_tmp ;
    mri_tmp = MRIread(like_vol_name) ;
    if (mri_tmp == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not like volume %s\n", like_vol_name) ;
    }
    mri = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth, MRI_FLOAT, 3) ;
    MRIcopyHeader(mri_tmp, mri) ;
    MRIfree(&mri_tmp) ;
  }
  if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
  {
    double xv, yv, zv ;
    VERTEX *v = &mris->vertices[0] ;
    MRISsurfaceRASToVoxel(mris, mri, v->x, v->y, v->z, &xv, &yv, &zv) ;
    printf("v 0: sras (%f, %f, %f) --> vox (%f, %f, %f)\n", v->x,v->y,v->z,xv,yv,zv);
    MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xv, &yv, &zv) ;
    printf("v 0: sras (%f, %f, %f) --> vox (%f, %f, %f)\n", v->x,v->y,v->z,xv,yv,zv);
    DiagBreak() ;
  }
  {
    MRI *mri_tmp ;
    mri_tmp = expand_mri_to_fit_surface(mris, mri) ;
    MRIfree(&mri) ; mri = mri_tmp ;
  }
  write_surface_warp_into_volume(mris, mri, niter) ;

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri, "warp.mgz") ;
  gcam = GCAMalloc(mri->width, mri->height, mri->depth) ;
  GCAMinitVolGeom(gcam, mri, mri) ;
  GCAMremoveSingularitiesAndReadWarpFromMRI(gcam, mri) ;
//  GCAMreadWarpFromMRI(gcam, mri) ;
  //  GCAsetVolGeom(gca, &gcam->atlas);
#if 0
  gcam->gca = gcaAllocMax(1, 1, 1,
			  mri->width, mri->height,
			  mri->depth,
			  0, 0) ;
 GCAMinit(gcam, mri, NULL, NULL, 0) ;
#endif
#if 0
  GCAMinvert(gcam, mri) ;
  GCAMwriteInverseWarpToMRI(gcam, mri) ;
  GCAMremoveSingularitiesAndReadWarpFromMRI(gcam, mri) ;  // should be inverse now
#endif
  if (mri_in)
  {
    MRI *mri_warped, *mri_tmp ;
    printf("applying warp to %s and writing to %s\n", mri_in->fname, out_fname) ;
    mri_tmp = MRIextractRegionAndPad(mri_in, NULL, NULL, pad) ; MRIfree(&mri_in) ; mri_in = mri_tmp ;
    mri_warped = GCAMmorphToAtlas(mri_in, gcam, NULL, -1, SAMPLE_TRILINEAR) ;
    MRIwrite(mri_warped, out_fname) ;
    if (Gdiag_no >= 0)
    {
      double  xi, yi, zi, xo, yo, zo, val;
      int     xp, yp, zp ;
      GCA_MORPH_NODE *gcamn ;

      VERTEX *v = &mris->vertices[Gdiag_no] ;
      MRISsurfaceRASToVoxelCached(mris, mri, v->origx, v->origy, v->origz, &xi, &yi, &zi) ;
      MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xo, &yo, &zo) ;
      printf("surface vertex %d: inflated (%2.0f, %2.0f, %2.0f), orig (%2.0f, %2.0f, %2.0f)\n", Gdiag_no, xi, yi, zi, xo, yo, zo) ;
      MRIsampleVolume(mri_in, xo, yo, zo, &val) ;
      xp = nint(xi) ; yp = nint(yi) ; zp = nint(zi) ;
      gcamn = &gcam->nodes[xp][yp][zp] ;
      printf("warp = (%2.1f, %2.1f, %2.1f), orig (%2.1f %2.1f %2.1f) = %2.1f \n", 
	     gcamn->x, gcamn->y, gcamn->z,
	     gcamn->origx, gcamn->origy, gcamn->origz,val) ;
      DiagBreak() ;
    }
  }
  if (no_write == 0)
  {
    out_name = argv[3] ;
    GCAMwrite(gcam, out_name) ;
  }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "warp field calculation took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #14
0
int
main(int argc, char *argv[]) {
  char         **av, fname[STRLEN], *out_fname, *subject_name, *cp ;
  int          ac, nargs ;
  int          msec, minutes, seconds ;
  struct timeb start ;
  MRI          *mri_seg, *mri_dst ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_mark_temporal_lobe.c,v 1.5 2011/03/02 00:04:23 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
    if (argc < 3)
      usage_exit(1) ;
  }


  out_fname = argv[argc-1] ;

  subject_name = argv[1] ;
  sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, seg_dir) ;
  mri_seg = MRIread(fname) ;
  if (!mri_seg)
    ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s",
              Progname, fname) ;
  mri_dst = MRImarkTemporalWM(mri_seg, NULL) ;

  sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, out_fname) ;
  printf("writing labeled temporal lobe to %s...\n", fname) ;
  MRIwrite(mri_dst, fname) ;
  MRIfree(&mri_dst) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("temporal lobe marking took %d minutes"
         " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
int
main(int argc, char *argv[]) {
  char         **av, fname[STRLEN] ;
  int          ac, nargs, i, j, nbins ;
  char         *avg_subject, *cp, *hemi, *subject, *output_prefix ;
  int          msec, minutes, seconds, nsubjects, vno ;
  struct timeb start ;
  MRI_SURFACE  *mris, *mris_avg ;
  float        ***histograms ;
  FILE         *fp ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_surface_to_vol_distances.c,v 1.4 2011/03/02 00:04:34 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  if (strlen(subjects_dir) == 0) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR must be specified on the command line (-sdir) or the env", Progname) ;
    strcpy(subjects_dir, cp) ;
  }

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 4)
    usage_exit(1) ;

  avg_subject = argv[1] ;
  hemi = argv[2] ;
  nsubjects = argc-4 ;
  output_prefix = argv[argc-1] ;
  sprintf(fname, "%s/%s/surf/%s.sphere", subjects_dir, avg_subject, hemi) ;
  mris_avg = MRISread(fname) ;
  if (mris_avg == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read spherical surface from %s", Progname, fname) ;

  nbins = nint(max_distance - min_distance) ;
  histograms = (float ***)calloc(mris_avg->nvertices, sizeof(float **)) ;
  if (histograms == NULL)
    ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %d histogram pointers", Progname, mris_avg->nvertices) ;
  for (vno = 0 ; vno < mris_avg->nvertices ; vno++) {
    histograms[vno] = (float **)calloc(nbins+1, sizeof(float *)) ;
    if (histograms[vno] == NULL)
      ErrorExit(ERROR_NOMEMORY, "%s: could not allocate histogram bins %d", Progname, vno) ;
    for (i = 0 ; i < nbins ; i++) {
      histograms[vno][i] = (float *)calloc(MAX_SURFACE_SCALE*nbins+1, sizeof(float)) ;
      if (histograms[vno][i] == NULL)
        ErrorExit(ERROR_NOMEMORY, "%s: could not allocate histogram bins %d", Progname, vno) ;
    }
  }

  printf("processing %d subjects and writing results to %s*\n", nsubjects, output_prefix) ;

  for (i = 0 ; i < nsubjects ; i++) {
    subject = argv[i+3] ;
    printf("processing subject %s: %d of %d...\n", subject, i+1, nsubjects) ;
    sprintf(fname, "%s/%s/surf/%s.sphere.reg", subjects_dir, subject, hemi) ;
    mris = MRISread(fname) ;
    if (mris == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read spherical surface from %s", Progname, fname) ;
    sprintf(fname, "%s/%s/surf/%s.sphere", subjects_dir, subject, hemi) ;
    if (MRISreadCanonicalCoordinates(mris, fname) != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read spherical surface from %s", Progname, fname) ;
    sprintf(fname, "%s/%s/surf/%s.white", subjects_dir, subject, hemi) ;
    if (MRISreadOriginalProperties(mris, fname) != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read white surface from %s", Progname, fname) ;
    if (MRISreadCurvatureFile(mris, "thickness") != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read thickness file", Progname) ;
    mrisFindMiddleOfGray(mris) ;
    update_histograms(mris, mris_avg, histograms, nbins) ;
    MRISfree(&mris) ;
  }

  printf("writing log files with prefix %s...\n", output_prefix) ;
  for (vno = 0 ; vno < mris_avg->nvertices ; vno++) {

    sprintf(fname, "%s%7.7d.histo", output_prefix, vno) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nbins ; i++) {
      for (j = 0 ; j < nbins*MAX_SURFACE_SCALE ; j++) {
        fprintf(fp, "%f ", histograms[vno][i][j]) ;
      }
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  }

  /* compute average, store it in vertex 0 histgram, and write it out */
  for (vno = 1 ; vno < mris_avg->nvertices ; vno++) {
    for (i = 0 ; i < nbins ; i++)
      for (j = 0 ; j < nbins*MAX_SURFACE_SCALE ; j++)
        histograms[0][i][j] += histograms[vno][i][j] ;

  }

  sprintf(fname, "%s.average.histo", output_prefix) ;
  fp = fopen(fname, "w") ;

  for (i = 0 ; i < nbins ; i++) {
    for (j = 0 ; j < nbins*MAX_SURFACE_SCALE ; j++) {
      fprintf(fp, "%f ", histograms[0][i][j]) ;
    }
    fprintf(fp, "\n") ;
  }
  fclose(fp) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("distance histogram compilation took %d minutes"
         " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #16
0
int
main(int argc, char *argv[])
{
    MRI     *mri_src, *mri_dst, *mri_tmp, *mri_labeled, *mri_labels;
    char    *input_file_name, *output_file_name ;
    int     nargs, i, msec ;
    struct timeb  then ;
    float   white_mean, white_sigma, gray_mean, gray_sigma ;

    char cmdline[CMD_LINE_LEN] ;

    TAGmakeCommandLineString(argc, argv, cmdline) ;

    /* rkt: check for and handle version tag */
    nargs = handle_version_option
            (argc, argv,
             "$Id: mri_segment.c,v 1.40 2011/03/02 00:04:24 nicks Exp $",
             "$Name: stable5 $");
    if (nargs && argc - nargs == 1)
    {
        exit (0);
    }
    argc -= nargs;

    Progname = argv[0] ;
    DiagInit(NULL, NULL, NULL) ;
    ErrorInit(NULL, NULL, NULL) ;

    for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
    {
        nargs = get_option(argc, argv) ;
        argc -= nargs ;
        argv += nargs ;
    }

    if (argc < 3)
    {
        usage_exit(1);
    }

    TimerStart(&then) ;
    input_file_name = argv[1] ;
    output_file_name = argv[2] ;

    mri_src = MRIread(input_file_name) ;
    if (!mri_src)
        ErrorExit(ERROR_NOFILE, "%s: could not read source volume from %s",
                  Progname, input_file_name) ;
    MRIaddCommandLine(mri_src, cmdline) ;
    if (mri_src->type != MRI_UCHAR)
    {
        MRI *mri_tmp ;
        printf("changing input type from %d to UCHAR\n", mri_src->type) ;
        mri_tmp = MRIchangeType(mri_src, MRI_UCHAR, 0, 1000, 1) ;
        MRIfree(&mri_src) ;
        mri_src = mri_tmp ;
    }

    if (thicken > 1)
    {
        mri_dst = MRIcopy(mri_src, NULL) ;
        /*    MRIfilterMorphology(mri_dst, mri_dst) ;*/
        fprintf(stderr, "removing 1-dimensional structures...\n") ;
        MRIremove1dStructures(mri_dst, mri_dst, 10000, 2, NULL) ;
#if 0
        MRIcheckRemovals(mri_src, mri_dst, mri_labels, 5) ;
        fprintf(stderr, "thickening thin strands....\n") ;
        MRIthickenThinWMStrands(mri_src, mri_dst, mri_dst, thickness, nsegments,
                                wm_hi) ;
#endif
        MRIwrite(mri_dst, output_file_name) ;
        exit(0) ;
    }

    mri_labels = MRIclone(mri_src, NULL) ;
    if (auto_detect_stats && !wm_low_set) /* widen range to allow
                                           for more variability */
    {
        wm_low -= 10 ;
    }
    fprintf(stderr, "doing initial intensity segmentation...\n") ;
    mri_tmp = MRIintensitySegmentation(mri_src, NULL, wm_low, wm_hi, gray_hi);

    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_tmp, "tmp1.mgz") ;
    }
    fprintf(stderr, "using local statistics to label ambiguous voxels...\n") ;
    MRIhistoSegment(mri_src, mri_tmp, wm_low, wm_hi, gray_hi, wsize, 3.0f) ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRIwrite(mri_tmp, "tmp2.mgz") ;
    }

    if (auto_detect_stats)
    {

        fprintf(stderr, "computing class statistics for intensity windows...\n") ;
        MRIcomputeClassStatistics(mri_src, mri_tmp, gray_low, WHITE_MATTER_MEAN,
                                  &white_mean, &white_sigma, &gray_mean,
                                  &gray_sigma) ;
        if (!finite(white_mean) || !finite(white_sigma) ||
                !finite(gray_mean) || !finite(gray_sigma))
            ErrorExit
            (ERROR_BADPARM,
             "%s: class statistics not finite - check input volume!",
             Progname);

        if (!wm_low_set)
        {
            if (FZERO(gray_sigma))
            {
                wm_low = (white_mean+gray_mean) / 2 ;
            }
            else
            {
                wm_low = gray_mean + gray_sigma ;
            }
        }

        if (!gray_hi_set)
        {
            gray_hi = gray_mean + 2*gray_sigma ;
#if 1
            if (gray_hi >= white_mean)
            {
                gray_hi = white_mean-1 ;
            }
#endif
        }
        fprintf(stderr, "setting bottom of white matter range to %2.1f\n",wm_low);
        fprintf(stderr, "setting top of gray matter range to %2.1f\n", gray_hi) ;

        if (log_stats)
        {
            FILE *fp ;

            fp = fopen("segment.dat", "w") ;
            if (fp)
            {
                fprintf(fp, "WM: %2.1f +- %2.1f\n",white_mean, white_sigma) ;
                fprintf(fp, "GM: %2.1f +- %2.1f\n",gray_mean, gray_sigma) ;
                fprintf(fp, "setting bottom of white matter range to %2.1f\n",wm_low);
                fprintf(fp, "setting top of gray matter range to %2.1f\n", gray_hi) ;
                fclose(fp) ;
            }
        }

        fprintf(stderr, "doing initial intensity segmentation...\n") ;
        mri_tmp = MRIintensitySegmentation(mri_src, NULL, wm_low, wm_hi, gray_hi);

        fprintf(stderr, "using local statistics to label ambiguous voxels...\n") ;
        MRIhistoSegment(mri_src, mri_tmp, wm_low, wm_hi, gray_hi, wsize, 3.0f) ;
    }
    else
    {
        /* just some not-too-dopey defaults - won't really be used */
        white_mean =  110 ;
        white_sigma = 5.0 ;
        gray_mean = 65 ;
        gray_sigma = 12 ;
    }

    fprintf(stderr,
            "using local geometry to label remaining ambiguous voxels...\n") ;
    mri_labeled = MRIcpolvMedianCurveSegment(mri_src, mri_tmp, NULL, 5, 3,
                  gray_hi, wm_low);
    fprintf(stderr,
            "\nreclassifying voxels using Gaussian border classifier...\n") ;

    /*
      now use the gray and white matter border voxels to build a Gaussian
      classifier at each point in space and reclassify all voxels in the
      range [wm_low-5,gray_hi].
      */
    for (i = 0 ; i < niter ; i++)
    {
        MRIreclassify(mri_src, mri_labeled, mri_labeled, wm_low-5,gray_hi,wsize);
    }
    MRIfree(&mri_tmp) ;

    mri_dst = MRImaskLabels(mri_src, mri_labeled, NULL) ;
    MRIfree(&mri_labeled) ;
    MRIrecoverBrightWhite(mri_src, mri_dst,mri_dst,wm_low,wm_hi,white_sigma,.33);
    fprintf(stderr,
            "\nremoving voxels with positive offset direction...\n") ;

#if 0
    MRIremoveWrongDirection(mri_dst, mri_dst, 3, wm_low-5, gray_hi, mri_labels) ;
#else
    MRIremoveWrongDirection(mri_dst, mri_dst, 3, wm_low-5, gray_hi, NULL) ;
#endif

    if (thicken)
    {
        /*    MRIfilterMorphology(mri_dst, mri_dst) ;*/
        fprintf(stderr, "removing 1-dimensional structures...\n") ;
        MRIremove1dStructures(mri_dst, mri_dst, 10000, 2, mri_labels) ;
#if 0
        MRIcheckRemovals(mri_src, mri_dst, mri_labels, 5) ;
#endif
        fprintf(stderr, "thickening thin strands....\n") ;
        MRIthickenThinWMStrands(mri_src, mri_dst, mri_dst, thickness, nsegments,
                                wm_hi) ;
    }

    mri_tmp = MRIfindBrightNonWM(mri_src, mri_dst) ;
    MRIbinarize(mri_tmp, mri_tmp, WM_MIN_VAL, 255, 0) ;
    MRImaskLabels(mri_dst, mri_tmp, mri_dst) ;
    MRIfilterMorphology(mri_dst, mri_dst) ;

    if (fill_bg)
    {
        fprintf(stderr, "filling basal ganglia....\n") ;
        MRIfillBasalGanglia(mri_src, mri_dst) ;
    }
    if (fill_ventricles)
    {
        fprintf(stderr, "filling ventricles....\n") ;
        MRIfillVentricles(mri_dst, mri_dst) ;
    }


    MRIfree(&mri_src) ;
    msec = TimerStop(&then) ;
    fprintf(stderr, "white matter segmentation took %2.1f minutes\n",
            (float)msec/(1000.0f*60.0f));
    fprintf(stderr, "writing output to %s...\n", output_file_name) ;
    if (keep_edits)
    {
        MRI *mri_old ;

        mri_old = MRIread(output_file_name) ;
        if (!mri_old)
        {
            ErrorPrintf
            (ERROR_NOFILE, "%s: could not read file %s to preserve edits",
             Progname, output_file_name) ;
            exit(1);
        }
        else
        {
            MRIcopyLabel(mri_old, mri_dst, WM_EDITED_ON_VAL) ;
            MRIcopyLabel(mri_old, mri_dst, WM_EDITED_OFF_VAL) ;
            MRIfree(&mri_old) ;
        }
    }
    MRIwrite(mri_dst, output_file_name) ;

    MRIfree(&mri_dst) ;

    exit(0) ;
    return(0) ;
}
Пример #17
0
/*----------------------------------------------------------------
  SurfClusterSummaryFast() - gives identical results as
    SurfClusterSummary() but much, much faster.
  ----------------------------------------------------------------*/
SCS *SurfClusterSummaryFast(MRI_SURFACE *Surf, MATRIX *T, int *nClusters)
{
  int n,vtx,clusterno;
  SURFCLUSTERSUM *scs;
  MATRIX *xyz, *xyzxfm;
  float vtxarea, vtxval;
  struct timeb  mytimer;
  int msecTime;
  double *weightvtx, *weightarea; // to be consistent with orig code
  VERTEX *v;

  if(Gdiag_no > 0) printf("SurfClusterSummaryFast()\n");

  TimerStart(&mytimer) ;

  *nClusters = sclustCountClusters(Surf);
  if(*nClusters == 0) return(NULL);

  xyz    = MatrixAlloc(4,1,MATRIX_REAL);
  xyz->rptr[4][1] = 1;
  xyzxfm = MatrixAlloc(4,1,MATRIX_REAL);

  scs = (SCS *) calloc(*nClusters, sizeof(SCS));
  weightvtx  = (double *) calloc(*nClusters, sizeof(double));
  weightarea = (double *) calloc(*nClusters, sizeof(double));

  for(vtx=0; vtx < Surf->nvertices; vtx++){
    v = &(Surf->vertices[vtx]);
    clusterno = v->undefval;
    if(clusterno == 0) continue;

    n = clusterno-1;
    scs[n].nmembers ++;
    vtxval = v->val;

    // Initialize
    if(scs[n].nmembers == 1){
      scs[n].maxval     = vtxval;
      scs[n].vtxmaxval  = vtx;
      weightvtx[n]  = 0.0;
      weightarea[n] = 0.0;
      scs[n].cx = 0.0;
      scs[n].cy = 0.0;
      scs[n].cz = 0.0;
    }

    if(! Surf->group_avg_vtxarea_loaded) vtxarea = v->area;
    else                                 vtxarea = v->group_avg_area;
    scs[n].area += vtxarea;
    
    if(fabs(vtxval) > fabs(scs[n].maxval)){
      scs[n].maxval = vtxval;
      scs[n].vtxmaxval = vtx;
    }
    weightvtx[n]  += vtxval;
    weightarea[n] += (vtxval*vtxarea);
    scs[n].cx += v->x;
    scs[n].cy += v->y;
    scs[n].cz += v->z;
  } // end loop over vertices

  for (n = 0; n < *nClusters ; n++){
    scs[n].clusterno = n+1;
    scs[n].x = Surf->vertices[scs[n].vtxmaxval].x;
    scs[n].y = Surf->vertices[scs[n].vtxmaxval].y;
    scs[n].z = Surf->vertices[scs[n].vtxmaxval].z;
    scs[n].weightvtx  = weightvtx[n];  
    scs[n].weightarea = weightarea[n];  
    scs[n].cx /= scs[n].nmembers;
    scs[n].cy /= scs[n].nmembers;
    scs[n].cz /= scs[n].nmembers;
    if (T != NULL){
      xyz->rptr[1][1] = scs[n].x;
      xyz->rptr[2][1] = scs[n].y;
      xyz->rptr[3][1] = scs[n].z;
      MatrixMultiply(T,xyz,xyzxfm);
      scs[n].xxfm = xyzxfm->rptr[1][1];
      scs[n].yxfm = xyzxfm->rptr[2][1];
      scs[n].zxfm = xyzxfm->rptr[3][1];

      xyz->rptr[1][1] = scs[n].cx;
      xyz->rptr[2][1] = scs[n].cy;
      xyz->rptr[3][1] = scs[n].cz;
      MatrixMultiply(T,xyz,xyzxfm);
      scs[n].cxxfm = xyzxfm->rptr[1][1];
      scs[n].cyxfm = xyzxfm->rptr[2][1];
      scs[n].czxfm = xyzxfm->rptr[3][1];
    }
  }

  MatrixFree(&xyz);
  MatrixFree(&xyzxfm);
  free(weightvtx);
  free(weightarea);
  msecTime = TimerStop(&mytimer) ;
  if(Gdiag_no > 0) printf("SurfClusterSumFast: n=%d, t = %g\n",*nClusters,msecTime/1000.0);

  return(scs);
}
Пример #18
0
int main(int argc, char *argv[]) {
  char **av,*subject_fname,*subjects_fname[STRLEN],fname[STRLEN],*cp,*hemi;
  int ac, nargs,n , m,surface_reference,nsubjects;
  MRI_SURFACE  *mris;
  MRI *mri,*mri_distance, *mri_orig;

  int msec, minutes, seconds ;
  struct timeb start;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mris_distance_to_label.cpp,v 1.8 2011/03/02 00:04:31 nicks Exp $",
     "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
  }

  if (argc < 3)
    usage_exit() ;

  /* hemisphere information */
  hemi = argv[1];
  for (nsubjects=0 , n = 2 ; n < argc ; n++)
    subjects_fname[nsubjects++]=argv[n];

  if (nlabels==0) {
    fprintf(stderr,"using default option\n");
    fprintf(stderr,"computing distance maps for :\n");
    fprintf(stderr,"      amygdala\n");
    fprintf(stderr,"      hippocampus\n");
    fprintf(stderr,"      pallidum\n");
    fprintf(stderr,"      putamen\n");
    fprintf(stderr,"      caudate\n");
    fprintf(stderr,"      lateral ventricle\n");
    //  fprintf(stderr,"      inferior lateral ventricle\n");
    fprintf(stderr,"      layer IV gray\n");
    nlabels=8;
    if (!stricmp(hemi,(char*)"rh")) { /* right hemisphere */
      labels[0]=54;
      labels[1]=53;
      labels[2]=52;
      labels[3]=51;
      labels[4]=50;
      labels[5]=43;
      labels[6]=44;
      labels[7]=-1;
    } else {
      labels[0]=18;
      labels[1]=17;
      labels[2]=13;
      labels[3]=12;
      labels[4]=11;
      labels[5]=4;
      labels[6]=5;
      labels[7]=-1;
    }
  }

  for ( m = 0 ; m < nsubjects ; m++) {
    subject_fname=subjects_fname[m];

    fprintf(stderr,"\n\nPROCESSING SUBJECT '%s' \n",subject_fname);

    sprintf(fname,"%s/%s/surf/%s.white", subjects_dir,subject_fname,hemi);
    fprintf(stderr, "reading surface from %s...\n", fname) ;
    mris=MRISread(fname);

    if (aseg_fname)
      sprintf(fname,"%s/%s/mri/%s", subjects_dir,subject_fname,aseg_fname);
    else
      sprintf(fname,"%s/%s/mri/aseg.mgz", subjects_dir,subject_fname);

    fprintf(stderr, "reading mri segmentation from %s...\n", fname) ;
    mri=MRIread(fname);

    fprintf(stderr, "allocating distance map\n") ;
    mri_distance=MRIalloc(mri->width,mri->height,mri->depth,MRI_FLOAT);

    for (n=0 ; n < nlabels ; n++) {

      if (labels[n]>=0) {
        fprintf(stderr, "generating distance map for label %d\n", labels[n]) ;
        MRIextractDistanceMap(mri,mri_distance,labels[n],fdistance,mode,NULL);

        fprintf(stderr,
                "extracting distance values for label %d\n", labels[n]) ;
        mrisExtractMRIvalues(mris,mri,mri_distance,fdistance,mode);

        mrisProcessDistanceValues(mris);

        surface_reference=findSurfaceReference(labels[n]);
        if (surface_reference>=3 and surface_reference<=14)
          sprintf(fname,"%s/%s/surf/%s.%s",
                  subjects_dir,subject_fname,hemi,
                  FRAME_FIELD_NAMES[surface_reference]);
        else
          sprintf(fname,"%s/%s/surf/%s.dist_%d",
                  subjects_dir,subject_fname,hemi,labels[n]);

        fprintf(stderr,
                "writing out surface distance file for label %d in %s...\n",
                labels[n],fname) ;
        MRISaverageCurvatures(mris,navgs);
        MRISwriteCurvature(mris,fname);
      } else { /* extract layer IV */
        sprintf(fname,"%s/%s/surf/%s.thickness",
                subjects_dir,subject_fname,hemi);
        fprintf(stderr, "reading curvature from %s...\n", fname) ;
        MRISreadCurvature(mris,fname);

        sprintf(fname,"%s/%s/mri/T1.mgz", subjects_dir,subject_fname);
        fprintf(stderr, "reading orig mri segmentation from %s...\n", fname) ;
        mri_orig=MRIread(fname);
        mrisExtractMidGrayValues(mris,mri_orig);
        MRIfree(&mri_orig);

        surface_reference=3;
        sprintf(fname,"%s/%s/surf/%s.%s",
                subjects_dir,subject_fname,hemi,
                FRAME_FIELD_NAMES[surface_reference]);
        fprintf(stderr,
                "writing out surface distance file for label %d in %s...\n",
                labels[n],fname) ;
        MRISaverageCurvatures(mris,navgs);
        MRISwriteCurvature(mris,fname);
      }
    }

    MRIfree(&mri_distance);
    MRIfree(&mri);
    MRISfree(&mris);
  }

  msec = TimerStop(&start) ;
  seconds = (int)((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("mris_distance_to_label took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Пример #19
0
int
main(int argc, char *argv[]) {
  char         **av, fname[STRLEN], *input_name, *subject_name, *cp,*hemi,
  *svm_name, *surf_name, *output_subject_name ;
  int          ac, nargs, vno ;
  int          msec, minutes, seconds ;
  struct timeb start ;
  MRI_SURFACE  *mris ;
  SVM          *svm ;
  double       classification ;
  float        *inputs ;
  MRI_SP       *mrisp ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_svm_classify.c,v 1.6 2011/03/02 00:04:34 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
  }
  if (argc < 7)
    usage_exit(1) ;

  subject_name = argv[1] ;
  hemi = argv[2] ;
  surf_name = argv[3] ;
  input_name = argv[4] ;
  output_subject_name = argv[5] ;
  svm_name = argv[6] ;

  printf("reading svm from %s...\n", svm_name) ;
  svm = SVMread(svm_name) ;
  if (!svm)
    ErrorExit(ERROR_NOFILE, "%s: could not read classifier from %s",
              Progname, svm_name) ;
  if (log_fname != NULL)
    printf("logging results to %s, true_class = %s\n",
           log_fname, true_class > 0 ? svm->class1_name : svm->class2_name) ;

  sprintf(fname, "%s/%s/surf/%s.%s", subjects_dir,subject_name,hemi,surf_name);
  printf("reading surface from %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s for %s",
              Progname, fname, subject_name) ;
  MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;

  if (MRISreadCurvature(mris, input_name) != NO_ERROR)
    ErrorExit(ERROR_BADPARM, "%s: could not read curvature from %s", input_name) ;

    if (nannotations > 0)
    {
      int vno, a, found ;
      VERTEX *v ;
      
      if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
        ErrorExit(ERROR_NOFILE, 
                  "%s: could not read annot file %s for subject %s",
                  Progname, annot_name, subject_name) ;
      for (a = 0 ; a < nannotations ; a++)
      {
        int index ;
        
        CTABfindName(mris->ct, anames[a], &index) ;
        CTABannotationAtIndex(mris->ct, index, &annotations[a]) ;
        printf("mapping annot %s to %d\n",
               anames[a], annotations[a]) ;
      }
      // rip all vertices that don't have one of the specified annotations
      for (vno = 0 ; vno < mris->nvertices ; vno++)
      {
        v = &mris->vertices[vno] ;
        if (v->ripflag)
          continue ;
        found = 0 ;
        for (a = 0 ; a < nannotations ; a++)
          if (v->annotation == annotations[a])
            found = 1 ;
        if (found == 0)
          v->ripflag = 1 ;
      }
    }
  if (navgs > 0)
    MRISaverageCurvatures(mris, navgs) ;

  mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
  MRISfree(&mris) ;

  /* read in output surface */
  sprintf(fname, "%s/%s/surf/%s.%s", subjects_dir,output_subject_name,hemi,surf_name);
  printf("reading output surface from %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s for %s",
              Progname, fname, output_subject_name) ;
  MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
  MRISfromParameterization(mrisp, mris, 0) ;

  if (label_name) {
    area = LabelRead(output_subject_name, label_name) ;
    if (!area)
      ErrorExit(ERROR_NOFILE, "%s: could not read label %s", Progname,
                label_name) ;
    MRISmaskNotLabel(mris, area) ;
  } else
    area = NULL ;
  if (mris->nvertices != svm->ninputs)
    ErrorExit(ERROR_BADPARM, "%s: svm input (%d) does not match # of "
              "surface vertices (%d)",
              Progname, svm->ninputs, mris->nvertices);

  inputs = (float *)calloc(mris->nvertices, sizeof(float)) ;
  if (!inputs)
    ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %d input vector",
              Progname, mris->nvertices) ;
  for (vno = 0 ; vno < mris->nvertices ; vno++)
    inputs[vno] = mris->vertices[vno].curv ;
  classification = SVMclassify(svm, inputs) ;
  printf("classification %f, class = %s",classification,
         classification > 0 ? svm->class1_name : svm->class2_name) ;
  if (true_class != 0)
    printf(", %s", true_class*classification>0 ? "CORRECT" : "INCORRECT") ;
  printf("\n") ;

  if (log_fname) {
    FILE *fp ;
    fp = fopen(log_fname, "a") ;
    if (!fp)
      ErrorExit(ERROR_BADPARM, "%s: could not open log file %s", log_fname) ;
    fprintf(fp, "%-30.30s %s %d %f %f\n",
            subject_name, hemi, (true_class*classification)>0, classification,
            true_class) ;
    fclose(fp) ;
  }
  free(inputs) ;
  MRISfree(&mris) ;
  SVMfree(&svm) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("classification took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #20
0
int
main(int argc, char *argv[])
{
  char          **av, *output_fname ;
  int           ac, nargs, msec, mode=-1 ;
  LABEL         *area ;
  MRI_SURFACE   *mris ;
  struct timeb  then ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option 
    (argc, argv, 
     "$Id: mris_distance_transform.c,v 1.4 2011/03/02 00:04:31 nicks Exp $", 
     "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Gdiag |= DIAG_SHOW ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;


  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 4)
    usage_exit() ;

  TimerStart(&then) ;
  mris = MRISread(argv[1]) ;
  if (mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface %s",
              Progname, argv[1]) ;
  area = LabelRead(NULL, argv[2]) ;
  if (area == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read label %s",
              Progname, argv[2]) ;

  if (anterior_dist > 0)
    LabelCropAnterior(area, anterior_dist) ;
  if (posterior_dist > 0)
    LabelCropPosterior(area, posterior_dist) ;
  
  if (stricmp(argv[3], "signed") == 0)
    mode = DTRANS_MODE_SIGNED ;
  else if (stricmp(argv[3], "unsigned") == 0)
    mode = DTRANS_MODE_UNSIGNED ;
  else if (stricmp(argv[3], "outside") == 0)
    mode = DTRANS_MODE_OUTSIDE ;
  else
  {
    print_usage() ;
    ErrorExit(ERROR_BADPARM, "unrecognized mode choice %s\n", argv[3]) ;
  }
  output_fname = argv[4] ;

  MRIScomputeMetricProperties(mris) ;
  MRIScomputeSecondFundamentalForm(mris) ;
  if (normalize > 0)
  {
    normalize = sqrt(mris->total_area) ;
    printf("normalizing surface distances by sqrt(%2.1f) = %2.1f\n", mris->total_area,normalize) ;
  }
  if (divide > 1)
  {
    int  i ;
    char fname[STRLEN], ext[STRLEN], base_name[STRLEN] ;
    LABEL *area_division ;

    FileNameExtension(output_fname, ext) ;
    FileNameRemoveExtension(output_fname, base_name) ;
    LabelMark(area, mris) ;
    MRIScopyMarksToAnnotation(mris) ;
    MRISsaveVertexPositions(mris, TMP_VERTICES) ;
    if (MRISreadVertexPositions(mris, divide_surf_name) != NO_ERROR)
      ErrorExit(ERROR_BADPARM, "%s: could not read vertex coords from %s", Progname, divide_surf_name) ;
    MRIScomputeSecondFundamentalForm(mris) ;
    MRISdivideAnnotationUnit(mris, 1, divide) ;
    MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
    MRIScomputeSecondFundamentalForm(mris) ;

    
    // MRISdivideAnnotationUnit sets the marked to be in [0,divide-1], make it [1,divide]
    // make sure they are oriented along original a/p direction
#define MAX_UNITS 100    
    {
      double cx[MAX_UNITS], cy[MAX_UNITS], cz[MAX_UNITS], min_a ;
      int    index, num[MAX_UNITS], new_index[MAX_UNITS], j, min_i ;
      VERTEX *v ;
      
      memset(num, 0, sizeof(num[0])*divide) ;
      memset(cx, 0, sizeof(cx[0])*divide) ;
      memset(cy, 0, sizeof(cy[0])*divide) ;
      memset(cz, 0, sizeof(cz[0])*divide) ;
      for (i = 0 ; i < area->n_points ; i++)
      {
        if (area->lv[i].vno < 0 || area->lv[i].deleted > 0)
          continue ;
        v = &mris->vertices[area->lv[i].vno] ;
        v->marked++ ;
        index = v->marked ;
        cx[index] += v->x ;
        cy[index] += v->y ;
        cz[index] += v->z ;
        num[index]++ ;
      }
      memset(new_index, 0, sizeof(new_index[0])*divide) ;
      for (i = 1 ; i <= divide ; i++)
        cy[i] /= num[i] ;

      // order them from posterior to anterior
      for (j = 1 ; j <= divide ; j++)
      {
        min_a = 1e10 ; min_i = 0 ;
        for (i = 1 ; i <= divide ; i++)
        {
          if (cy[i] < min_a)
          {
            min_a = cy[i] ;
            min_i = i ;
          }
        }
        cy[min_i] = 1e10 ;  // make it biggest so it won't be considered again
        new_index[j] = min_i ;
      }
      for (i = 0 ; i < area->n_points ; i++)
      {
        if (area->lv[i].vno < 0 || area->lv[i].deleted > 0)
          continue ;
        v = &mris->vertices[area->lv[i].vno] ;
        v->marked = new_index[v->marked] ;
      }
    }
    for (i = 1 ; i <= divide ; i++)
    {
      area_division = LabelFromMarkValue(mris, i) ;

      printf("performing distance transform on division %d with %d vertices\n", 
             i, area_division->n_points) ;
      if (output_label)
      {
        sprintf(fname, "%s%d.label", base_name, i) ;
        printf("writing %dth subdivision to %s\n", i, fname) ;
        LabelWrite(area_division, fname);
      }
      MRISdistanceTransform(mris, area_division, mode) ;
      sprintf(fname, "%s%d.%s", base_name, i, ext) ;
      if (normalize > 0)
        MRISmulVal(mris, 1.0/normalize) ;
      MRISwriteValues(mris, fname) ;
    }
  }
  else
  {
    MRISdistanceTransform(mris, area, mode) ;
    if (normalize > 0)
      MRISmulVal(mris, 1.0/normalize) ;
    MRISwriteValues(mris, output_fname) ;
  }

  msec = TimerStop(&then) ;
  fprintf(stderr,"distance transform took %2.1f minutes\n", (float)msec/(60*1000.0f));

  exit(0) ;
  return(0) ;  /* for ansi */
}
int
main(int argc, char *argv[]) {
  char   **av, fname[STRLEN] ;
  int    ac, nargs, i ;
  MRI    *mri_flash[MAX_IMAGES], *mri_T1, *mri_PD ;
  char   *in_fname, *out_PD_fname, *out_T1_fname ;
  int          msec, minutes, seconds, nvolumes ;
  struct timeb start ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_estimate_tissue_parms.c,v 1.9 2011/03/02 00:04:15 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;
  parms.dt = 1e-6 ;
  parms.tol = 1e-5 ;
  parms.momentum = 0.0 ;
  parms.niterations = 20 ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 4)
    usage_exit(1) ;

  out_T1_fname = argv[argc-2] ;
  out_PD_fname = argv[argc-1] ;
  FileNameOnly(out_T1_fname, fname) ;
  FileNameRemoveExtension(fname, fname) ;
  strcpy(parms.base_name, fname) ;

  nvolumes = 0 ;
  for (i = 1 ; i < argc-2 ; i++) {
    if (argv[i][0] == '-') {
      if (!stricmp(argv[i]+1, "te"))
        te = atof(argv[i+1]) ;
      else if (!stricmp(argv[i]+1, "tr"))
        tr = atof(argv[i+1]) ;
      else if (!stricmp(argv[i]+1, "fa"))
        fa = RADIANS(atof(argv[i+1])) ;
      else
        ErrorExit(ERROR_BADPARM, "%s: unsupported MR parameter %s",
                  Progname, argv[i]+1) ;
      i++ ;  /* skip parameter */
      continue ;
    }

    in_fname = argv[i] ;
    printf("reading %s...", in_fname) ;

    mri_flash[nvolumes] = MRIread(in_fname) ;
    if (!mri_flash[nvolumes])
      ErrorExit(Gerror, "%s: MRIread(%s) failed", Progname, in_fname) ;
    if (tr > 0) {
      mri_flash[nvolumes]->tr = tr ;
      tr = 0 ;
    }
    if (te > 0) {
      mri_flash[nvolumes]->te = te ;
      te = 0 ;
    }
    if (fa > 0) {
      mri_flash[nvolumes]->flip_angle = fa ;
      fa = 0 ;
    }
    printf("TE = %2.2f, TR = %2.2f, alpha = %2.2f\n", mri_flash[nvolumes]->te,
           mri_flash[nvolumes]->tr, DEGREES(mri_flash[nvolumes]->flip_angle)) ;
    mri_flash[nvolumes]->flip_angle = mri_flash[nvolumes]->flip_angle;
    if (conform) {
      MRI *mri_tmp ;

      printf("embedding and interpolating volume\n") ;
      mri_tmp = MRIconform(mri_flash[nvolumes]) ;
      /*      MRIfree(&mri_src) ;*/
      mri_flash[nvolumes] = mri_tmp ;
    }
    if (FZERO(mri_flash[nvolumes]->tr) ||
        FZERO(mri_flash[nvolumes]->flip_angle))
      ErrorExit(ERROR_BADPARM, "%s: invalid TR or FA for image %d:%s",
                Progname, nvolumes, in_fname) ;
    nvolumes++ ;
  }
  printf("using %d FLASH volumes to estimate tissue parameters.\n", nvolumes) ;
  mri_T1 = MRIclone(mri_flash[0], NULL) ;
  mri_PD = MRIclone(mri_flash[0], NULL) ;


  {
    double   sse, last_T1, last_PD, total_rms, avg_rms ;
    int      x, y, z, width, height, depth, total_vox, ignored, nvox ;
    struct timeb first_slice ;

    Progname = argv[0] ;
    ErrorInit(NULL, NULL, NULL) ;
    DiagInit(NULL, NULL, NULL) ;

    TimerStart(&first_slice) ;

    last_T1 = last_PD = 1000 ;
    sse = 0.0 ;
    width = mri_T1->width ;
    height = mri_T1->height ;
    depth = mri_T1->depth ;
    total_vox = width*depth*height ;
#if 0
    estimateVoxelParameters(mri_flash, nvolumes, width/2, height/2, depth/2,
                            mri_T1, mri_PD, last_T1, last_PD) ;
#endif
    if (Gdiag_no == 999) {
      x = 130 ;
      y = 124 ;
      z = 74 ; /* CSF */
      computeErrorSurface("error_surf_csf.dat",mri_flash,nvolumes,x,y,z,500,3000,500,3000);
      x = 161 ;
      y = 157 ;
      z = 63 ;  /* wm */
      computeErrorSurface("error_surf_wm.dat",mri_flash,nvolumes,x,y,z,250,3000,250,3000);
      x = 166 ;
      y = 153 ;
      z = 63 ;  /* gm */
      computeErrorSurface("error_surf_gm.dat",mri_flash,nvolumes,x,y,z,250,3000,250,3000);
    }
    avg_rms = 0 ;
    for (ignored = z = 0 ; z < depth ; z++) {
      if (z > 0)
        printf("z = %d, avg rms=%2.1f, T1=%2.0f, PD=%2.0f...\n",
               z, avg_rms, last_T1, last_PD) ;
#if 0
      if (z > 0 && z*width*height - ignored > 0) {
        int processed = z*width*height - ignored, hours ;

        msec = TimerStop(&first_slice) ;
        seconds = nint((float)msec/1000.0f) ;
        minutes = seconds / 60 ;
        seconds = seconds % 60 ;
        hours = minutes / 60 ;
        minutes = minutes % 60 ;
        printf("%02d:%02d:%02d total processing time ... ",
               hours,minutes,seconds);
        msec = (int)((float)(total_vox-ignored)*msec/(float)processed) ;
        seconds = nint((float)msec/1000.0f) ;
        minutes = seconds / 60 ;
        seconds = seconds % 60 ;
        hours = minutes / 60 ;
        minutes = minutes % 60 ;
        printf("estimate %02d:%02d:%02d remaining.\n", hours,minutes, seconds);
      }
#endif
      if (write_iterations > 0 && z > 0 && !(z%write_iterations)) {
        printf("writing T1 esimates to %s...\n", out_T1_fname) ;
        printf("writing PD estimates to %s...\n", out_PD_fname) ;
        MRIwrite(mri_T1, out_T1_fname) ;
        MRIwrite(mri_PD, out_PD_fname) ;
        printf("writing residuals to %s...\n", residual_name) ;
        if (residual_name) {
          MRI *mri_res, *mri_res_total = NULL ;
          for (i = 0 ; i < nvolumes ; i++) {

            mri_res = compute_residuals(mri_flash[i], mri_T1, mri_PD) ;
            sprintf(fname, "%s%d.mgh", residual_name, i) ;
#if 0
            MRIwrite(mri_res, fname) ;
#endif
            if (!mri_res_total) {
              mri_res_total = MRIcopy(mri_res, NULL) ;
            } else {
              MRIsadd(mri_res, mri_res_total, mri_res_total) ;
            }

            MRIfree(&mri_res) ;
          }
          MRIsscalarMul(mri_res_total, mri_res_total, 1.0/(float)nvolumes) ;
          MRIssqrt(mri_res_total, mri_res_total) ;
          sprintf(fname, "%s.mgh", residual_name) ;
          MRIwrite(mri_res_total, fname) ;
        }
      }

      nvox = 0 ;
      total_rms = 0 ;
      for (y = 0 ; y < height ; y++) {
#if 0
        if (y%32 == 0 && nvox > 0)
          printf("z = %d, y = %d, avg rms=%2.1f, T1=%2.0f, PD=%2.0f...\n",
                 z, y, total_rms/(double)nvox, last_T1, last_PD) ;
#endif
        for (x = 0 ; x < width ; x++) {
#if 0
          for (i = 0 ; i < nvolumes ; i++)
            if (MRISvox(mri_flash[i],x,y,z) > thresh)
              break ;
          if (i >= nvolumes)
#else
          if (no_valid_data(mri_flash, nvolumes, x, y, z, thresh))
#endif
          {
            ignored++ ;
            MRISvox(mri_T1, x, y, z) = MRISvox(mri_PD, x, y, z) = 0 ;
            /*            last_T1 = last_PD = 1000 ;*/
            continue ;
          }
#if 0
          sse = findInitialParameters(mri_flash, nvolumes, x, y, z,
                                      last_PD-1000, last_PD+1000,
                                      last_T1-1000, last_T1+1000,
                                      &last_PD, &last_T1, 10) ;
#endif
#if 0
          sse = findInitialParameters(mri_flash, nvolumes, x, y, z,
                                      last_PD-100, last_PD+100,
                                      last_T1-100, last_T1+100,
                                      &last_PD, &last_T1, 10) ;
          if (last_T1 <= MIN_T1 || last_PD <= 0) {
            ignored++ ;
            MRISvox(mri_T1, x, y, z) = MRISvox(mri_PD, x, y, z) = 0 ;
            /*            last_T1 = last_PD = 1000 ;*/
            continue ;
          }
#endif
          sse = estimateVoxelParameters(mri_flash, nvolumes, x, y, z,
                                        mri_T1, mri_PD, nsteps) ;
          nvox++ ;
          last_T1 = MRISvox(mri_T1, x, y, z) ;
          last_PD = MRISvox(mri_PD, x, y, z) ;
          total_rms += sqrt(sse/nvolumes) ;
          if (!finite(total_rms))
            DiagBreak() ;
        }
      }
      avg_rms = total_rms / nvox ;
      if (!finite(avg_rms))
        DiagBreak() ;
    }
  }


  printf("writing T1 esimates to %s...\n", out_T1_fname) ;
  printf("writing PD estimates to %s...\n", out_PD_fname) ;
  MRIwrite(mri_T1, out_T1_fname) ;
  MRIwrite(mri_PD, out_PD_fname) ;
  if (residual_name) {
    MRI *mri_res_total = NULL ;

    for (i = 0 ; i < nvolumes ; i++) {
      MRI *mri_res ;

      mri_res = compute_residuals(mri_flash[i], mri_T1, mri_PD) ;
#if 0
      sprintf(fname, "%s%d.mgh", residual_name, i) ;
      MRIwrite(mri_res, fname) ;
#endif
      if (!mri_res_total) {
        mri_res_total = MRIcopy(mri_res, NULL) ;
      } else {
        MRIsadd(mri_res, mri_res_total, mri_res_total) ;
      }
      MRIfree(&mri_res) ;
    }
    MRIsscalarMul(mri_res_total, mri_res_total, 1.0/(float)nvolumes) ;
    MRIssqrt(mri_res_total, mri_res_total) ;
    sprintf(fname, "%s.mgh", residual_name) ;
    MRIwrite(mri_res_total, fname) ;
  }
  MRIfree(&mri_T1) ;
  MRIfree(&mri_PD) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("parameter estimation took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
int
main(int argc, char *argv[]) {
  char   **av, fname[STRLEN] ;
  int    ac, nargs ;
  char   *reg_fname, *in_fname, *out_stem, *cp ;
  int    msec, minutes, seconds, nvox, float2int ;
  struct timeb start ;
  MRI_SURFACE *mris_lh_white, *mris_rh_white, *mris_lh_pial, *mris_rh_pial ;
  MRI         *mri_aseg, *mri_seg, *mri_pial, *mri_tmp, *mri_ribbon, *mri_in, *mri_cortex, 
    *mri_subcort_gm, *mri_wm, *mri_csf ;
  MATRIX      *m_regdat ;
  float       intensity, betplaneres, inplaneres ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_compute_volume_fractions.c,v 1.9 2012/11/07 18:58:02 greve Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }
  if (argc < 4)
    usage_exit(1) ;
  if (!strlen(sdir)) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ;
    strcpy(sdir, cp) ;
  }
  reg_fname = argv[1] ; in_fname = argv[2] ;
  out_stem = argv[3] ; Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  if (stricmp(reg_fname, "identity.nofile") == 0)
  {
    printf("using identity transform\n") ;
    m_regdat = NULL ;
    inplaneres = betplaneres = intensity = 1 ;
    float2int = 0 ;
    if (subject == NULL)
      subject = "unknown" ;
  }
  else
  {
    char *saved_subject = subject ;
    printf("reading registration file %s\n", reg_fname) ;
    regio_read_register(reg_fname, &subject, &inplaneres,
                        &betplaneres, &intensity,  &m_regdat,
                        &float2int);
    
    if (saved_subject)  // specified on cmdline
      subject = saved_subject ;
    m_regdat = regio_read_registermat(reg_fname) ;
    if (m_regdat == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not load registration file from %s", Progname,reg_fname) ;
  }
  printf("Format is %s\n",fmt);
    
  sprintf(fname, "%s/%s/surf/lh.white", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_lh_white = MRISread(fname) ;
  if (mris_lh_white == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load lh white surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/rh.white", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_rh_white = MRISread(fname) ;
  if (mris_rh_white == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load rh white surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/lh.pial", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_lh_pial = MRISread(fname) ;
  if (mris_lh_pial == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load lh pial surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/rh.pial", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_rh_pial = MRISread(fname) ;
  if (mris_rh_pial == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load rh pial surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/mri/aseg.mgz", sdir, subject) ;
  printf("reading volume %s\n", fname) ;
  mri_aseg = MRIread(fname) ;
  if (mri_aseg == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load aseg volume from %s", Progname,fname) ;

  printf("reading movable volume %s\n", in_fname) ;
  mri_in = MRIread(in_fname) ;
  if (mri_in == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load input volume from %s", Progname,in_fname) ;
 
  nvox = (int)ceil(256/resolution); 
  mri_pial = MRIalloc(nvox, nvox, nvox, MRI_UCHAR) ;
  MRIsetResolution(mri_pial, resolution, resolution, resolution) ;

  mri_pial->xstart = -resolution*mri_pial->width/2.0 ;
  mri_pial->xend = resolution*mri_pial->width/2.0 ;
  mri_pial->ystart = -resolution*mri_pial->height/2.0 ;
  mri_pial->yend = resolution*mri_pial->height/2.0 ;
  mri_pial->zstart = -resolution*mri_pial->depth/2.0 ;
  mri_pial->zend = resolution*mri_pial->depth/2 ;
  mri_pial->c_r = mri_aseg->c_r ; mri_pial->c_a = mri_aseg->c_a ; mri_pial->c_s = mri_aseg->c_s ;
  MRIreInitCache(mri_pial) ; 

  printf("filling interior of lh pial surface...\n") ;
  MRISfillInterior(mris_lh_pial, resolution, mri_pial) ;
  mri_seg = MRIclone(mri_pial, NULL) ;
  mri_tmp = MRIclone(mri_pial, NULL) ;
  printf("filling interior of rh pial surface...\n") ;
  MRISfillInterior(mris_rh_pial, resolution, mri_tmp) ;
  MRIcopyLabel(mri_tmp, mri_pial, 1) ;
  MRIclear(mri_tmp) ;
  printf("filling interior of lh white matter surface...\n") ;
  MRISfillWhiteMatterInterior(mris_lh_white, mri_aseg, mri_seg, resolution,
                              WM_VAL, SUBCORT_GM_VAL, CSF_VAL);
  printf("filling interior of rh white matter surface...\n") ;
  MRISfillWhiteMatterInterior(mris_rh_white, mri_aseg, mri_tmp, resolution,
                              WM_VAL, SUBCORT_GM_VAL, CSF_VAL);
  MRIcopyLabel(mri_tmp, mri_seg, WM_VAL) ;
  MRIcopyLabel(mri_tmp, mri_seg, SUBCORT_GM_VAL) ;
  MRIcopyLabel(mri_tmp, mri_seg, CSF_VAL) ;
  MRIfree(&mri_tmp) ;
  
  mri_ribbon = MRInot(mri_seg, NULL) ;
  MRIcopyLabel(mri_seg, mri_pial, CSF_VAL) ;
  MRIreplaceValuesOnly(mri_pial, mri_pial, CSF_VAL, 0) ;
  MRIand(mri_ribbon, mri_pial, mri_ribbon, 1) ;
  MRIbinarize(mri_ribbon, mri_ribbon, 1, 0, GM_VAL) ;
  MRIcopyLabel(mri_ribbon, mri_seg, GM_VAL) ;
  MRIreplaceValuesOnly(mri_seg, mri_seg, CSF_VAL, 0) ;
  add_aseg_structures_outside_ribbon(mri_seg, mri_aseg, mri_seg, WM_VAL, SUBCORT_GM_VAL, CSF_VAL) ;


  {
    MATRIX *m_conformed_to_epi_vox2vox, *m_seg_to_conformed_vox2vox,
           *m_seg_to_epi_vox2vox ;

    if (m_regdat == NULL)    // assume identity transform
      m_seg_to_epi_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_in) ;
    else
    {
      m_conformed_to_epi_vox2vox = MRIvoxToVoxFromTkRegMtx(mri_in, mri_aseg, m_regdat);
      m_seg_to_conformed_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_aseg) ;
      
      m_seg_to_epi_vox2vox = MatrixMultiply(m_conformed_to_epi_vox2vox, m_seg_to_conformed_vox2vox, NULL) ;
      MatrixFree(&m_regdat) ; MatrixFree(&m_conformed_to_epi_vox2vox) ; 
      MatrixFree(&m_seg_to_conformed_vox2vox);

    }
    printf("seg to EPI vox2vox matrix:\n") ;
    MatrixPrint(Gstdout, m_seg_to_epi_vox2vox) ;
    mri_cortex = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, MRI_FLOAT) ;
    MRIcopyHeader(mri_in, mri_cortex) ;
    mri_subcort_gm = MRIclone(mri_cortex, NULL) ;
    mri_wm = MRIclone(mri_cortex, NULL) ;
    mri_csf = MRIclone(mri_cortex, NULL) ;
    printf("computing partial volume fractions...\n") ;
    MRIcomputePartialVolumeFractions(mri_in, m_seg_to_epi_vox2vox, mri_seg, mri_wm, mri_subcort_gm, mri_cortex, mri_csf,
                                     WM_VAL, SUBCORT_GM_VAL, GM_VAL, 0) ;
  }
  
  sprintf(fname, "%s.wm.%s", out_stem,fmt) ;
  printf("writing wm %% to %s\n", fname) ;
  MRIwrite(mri_wm, fname) ;

  sprintf(fname, "%s.subcort_gm.%s", out_stem,fmt) ;
  printf("writing subcortical gm %% to %s\n", fname) ;
  MRIwrite(mri_subcort_gm, fname) ;

  sprintf(fname, "%s.cortex.%s", out_stem, fmt) ;
  printf("writing cortical gm %% to %s\n", fname) ;
  MRIwrite(mri_cortex, fname) ;
  
  sprintf(fname, "%s.csf.%s", out_stem,fmt) ;
  printf("writing csf %% to %s\n", fname) ;
  MRIwrite(mri_csf, fname) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("volume fraction calculation took %d minutes"
          " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #23
0
int
main(int argc, char *argv[]) {
  char   **av ;
  int    label, ac, nargs ;
  int          msec, minutes, seconds/*, wrong, total, correct*/ ;
  struct timeb start ;
  MRI    *mri_T1, *mri_labeled ;
  FILE   *log_fp ;
  HISTOGRAM *histo ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_label_histo.c,v 1.5 2011/03/02 00:04:22 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 4)
    usage_exit(1) ;


  mri_T1 = MRIread(argv[1]) ;
  if (!mri_T1)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname,
              argv[1]) ;
  mri_labeled = MRIread(argv[2]) ;
  if (!mri_labeled)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname,
              argv[2]) ;

  if (log_fname) {
    log_fp = fopen(log_fname, "a+") ;
    if (!log_fp)
      ErrorExit(ERROR_BADFILE, "%s: could not open %s for writing",
                Progname, log_fname) ;
  } else
    log_fp = NULL ;


  label = atoi(argv[3]) ;
  printf("generating histogram for label %d...\n", label) ;
  histo = MRIhistogramLabel(mri_T1, mri_labeled, label, 0) ;

  HISTOplot(histo, argv[4]) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;

  if (DIAG_VERBOSE_ON)
    fprintf(stderr, "overlap calculation took %d minutes and %d seconds.\n",
            minutes, seconds) ;

  exit(0) ;
  return(0) ;
}
Пример #24
0
int
main(int argc, char *argv[]) {
  TRANSFORM    *transform = NULL ;
  char         **av, fname[STRLEN], *gca_fname, *subject_name, *cp ;
  int          ac, nargs, i, n ;
  int          msec, minutes, seconds, nsubjects ;
  struct timeb start ;
  GCA          *gca ;
  MRI          *mri_parc, *mri_T1, *mri_PD ;
  FILE         *fp ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_ca_tissue_parms.c,v 1.8 2011/03/02 00:04:14 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
    if (argc < 3)
      usage_exit(1) ;
  }


  gca_fname = argv[1] ;
  nsubjects = argc-2 ;
  printf("computing average tissue parameters on %d subject\n",
         nsubjects) ;

  n = 0 ;

  printf("reading GCA from %s...\n", gca_fname) ;
  gca = GCAread(gca_fname) ;

  for (i = 0 ; i < nsubjects ; i++) {
    subject_name = argv[i+2] ;
    printf("processing subject %s, %d of %d...\n", subject_name,i+1,
           nsubjects);
    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, parc_dir) ;
    if (DIAG_VERBOSE_ON)
      printf("reading parcellation from %s...\n", fname) ;
    mri_parc = MRIread(fname) ;
    if (!mri_parc)
      ErrorExit(ERROR_NOFILE, "%s: could not read parcellation file %s",
                Progname, fname) ;

    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name) ;
    if (DIAG_VERBOSE_ON)
      printf("reading co-registered T1 from %s...\n", fname) ;
    mri_T1 = MRIread(fname) ;
    if (!mri_T1)
      ErrorExit(ERROR_NOFILE, "%s: could not read T1 data from file %s",
                Progname, fname) ;

    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, PD_name) ;
    if (DIAG_VERBOSE_ON)
      printf("reading co-registered T1 from %s...\n", fname) ;
    mri_PD = MRIread(fname) ;
    if (!mri_PD)
      ErrorExit(ERROR_NOFILE, "%s: could not read PD data from file %s",
                Progname, fname) ;


    if (xform_name) {
      /*      VECTOR *v_tmp, *v_tmp2 ;*/

      sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, xform_name) ;
      printf("reading xform from %s...\n", fname) ;
      transform = TransformRead(fname) ;
      if (!transform)
        ErrorExit(ERROR_NOFILE, "%s: could not read xform from %s",
                  Progname, fname) ;
#if 0
      v_tmp = VectorAlloc(4,MATRIX_REAL) ;
      *MATRIX_RELT(v_tmp,4,1)=1.0 ;
      v_tmp2 = MatrixMultiply(lta->xforms[0].m_L, v_tmp, NULL) ;
      printf("RAS (0,0,0) -->\n") ;
      MatrixPrint(stdout, v_tmp2) ;
#endif

      if (transform->type == LINEAR_RAS_TO_RAS) {
        MATRIX *m_L ;
        m_L = ((LTA *)transform->xform)->xforms[0].m_L ;
        MRIrasXformToVoxelXform(mri_parc, mri_T1, m_L,m_L) ;
      }
#if 0
      v_tmp2 = MatrixMultiply(lta->xforms[0].m_L, v_tmp, v_tmp2) ;
      printf("voxel (0,0,0) -->\n") ;
      MatrixPrint(stdout, v_tmp2) ;
      VectorFree(&v_tmp) ;
      VectorFree(&v_tmp2) ;
      test(mri_parc, mri_T1, mri_PD, lta->xforms[0].m_L) ;
#endif
    }
    if (histo_parms)
      GCAhistogramTissueStatistics(gca,mri_T1,mri_PD,mri_parc,transform,histo_parms);
#if 0
    else
      GCAaccumulateTissueStatistics(gca, mri_T1, mri_PD, mri_parc, transform) ;
#endif

    MRIfree(&mri_parc) ;
    MRIfree(&mri_T1) ;
    MRIfree(&mri_PD) ;
  }
  GCAnormalizeTissueStatistics(gca) ;

  if (log_fname) {
    printf("writing tissue parameters to %s\n", log_fname) ;
    fp = fopen(log_fname, "w") ;
    for (n = 1 ; n < MAX_GCA_LABELS ; n++) {
      GCA_TISSUE_PARMS *gca_tp ;

      gca_tp = &gca->tissue_parms[n] ;
      if (gca_tp->total_training <= 0)
        continue ;
      fprintf(fp, "%d  %f  %f\n", n, gca_tp->T1_mean, gca_tp->PD_mean) ;
    }
    fclose(fp) ;
  }

  if (write_flag)
    GCAwrite(gca, gca_fname) ;
  GCAfree(&gca) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("tissue parameter statistic calculation took %d minutes"
         " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #25
0
int
main(int argc, char *argv[])
{
  char         *gca_fname, *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ;
  MRI          *mri_in, *mri_norm = NULL, *mri_tmp, *mri_ctrl = NULL ;
  GCA          *gca ;
  int          ac, nargs, nsamples, msec, minutes, seconds;
  int          i, struct_samples, norm_samples = 0, n, input, ninputs ;
  struct timeb start ;
  GCA_SAMPLE   *gcas, *gcas_norm = NULL, *gcas_struct ;
  TRANSFORM    *transform = NULL ;
  char         cmdline[CMD_LINE_LEN], line[STRLEN], *cp, subject[STRLEN], sdir[STRLEN], base_name[STRLEN] ;
  FILE         *fp ;

  make_cmd_version_string
    (argc, argv,
     "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $",
     "$Name: stable5 $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $",
     "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  setRandomSeed(-1L) ;
  Progname = argv[0] ;

  DiagInit(NULL, NULL, NULL) ;
  ErrorInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 6)
    ErrorExit
      (ERROR_BADPARM,
       "usage: %s [<options>] <longitudinal time point file> <in vol> <atlas> <transform file> <out vol> \n",
       Progname) ;
  in_fname = argv[2] ;
  gca_fname = argv[3] ;
  xform_fname = argv[4] ;
  out_fname = argv[5] ;

  transform = TransformRead(xform_fname) ;
  if (transform == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ;
  if (read_ctrl_point_fname)
  {
    mri_ctrl = MRIread(read_ctrl_point_fname) ;
    if (mri_ctrl == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read precomputed control points from %s", 
                Progname, read_ctrl_point_fname) ;
  }
  TimerStart(&start) ;
  printf("reading atlas from '%s'...\n", gca_fname) ;
  fflush(stdout) ;

  gca = GCAread(gca_fname) ;
  if (gca == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not open GCA %s.\n",Progname, gca_fname) ;
  GCAregularizeConditionalDensities(gca, .5) ;

  FileNamePath(argv[1], sdir) ;
  cp = strrchr(sdir, '/') ; 
  if (cp)
  {
    strcpy(base_name, cp+1) ;
    *cp = 0 ;  // remove last component of path, which is base subject name
  }
  ninputs = 0 ;
  fp = fopen(argv[1], "r") ;
  if (fp == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read time point file %s", argv[1]) ;

  do
  {
    cp = fgetl(line, STRLEN-1, fp) ;
    if (cp != NULL && strlen(cp) > 0)
    {
      subjects[ninputs] = (char *)calloc(strlen(cp)+1, sizeof(char)) ;
      strcpy(subjects[ninputs], cp) ;
      ninputs++ ;
    }
  } while (cp != NULL && strlen(cp) > 0) ;
  fclose(fp) ;
  printf("processing %d timepoints in SUBJECTS_DIR %s...\n", ninputs, sdir) ;
  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(subject, "%s.long.%s", subjects[input], base_name) ;
    printf("reading subject %s - %d of %d\n", subject, input+1, ninputs) ;
    sprintf(fname, "%s/%s/mri/%s", sdir, subject, in_fname) ;
    mri_tmp = MRIread(fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s",
                Progname, fname) ;
    MRImakePositive(mri_tmp, mri_tmp) ;
    if (mri_tmp && ctrl_point_fname && !mri_ctrl)
    {
      mri_ctrl = MRIallocSequence(mri_tmp->width, mri_tmp->height, 
                                  mri_tmp->depth,MRI_FLOAT, nregions*2) ; // labels and means
      MRIcopyHeader(mri_tmp, mri_ctrl) ;
    }
    if (input == 0)
    {
      mri_in =
        MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                         mri_tmp->type, ninputs) ;
      if (!mri_in)
        ErrorExit(ERROR_NOMEMORY,
                  "%s: could not allocate input volume %dx%dx%dx%d",
                  mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ;
      MRIcopyHeader(mri_tmp, mri_in) ;
    }

    if (mask_fname)
    {
      int i ;
      MRI *mri_mask ;

      mri_mask = MRIread(mask_fname) ;
      if (!mri_mask)
        ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
                  Progname, mask_fname) ;

      for (i = 1 ; i < WM_MIN_VAL ; i++)
        MRIreplaceValues(mri_mask, mri_mask, i, 0) ;
      MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
      MRIfree(&mri_mask) ;
    }
    MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
    MRIfree(&mri_tmp) ;
  }
  MRIaddCommandLine(mri_in, cmdline) ;

  GCAhistoScaleImageIntensitiesLongitudinal(gca, mri_in, 1) ;

  {
    int j ;

    gcas = GCAfindAllSamples(gca, &nsamples, NULL, 1) ;
    printf("using %d sample points...\n", nsamples) ;
    GCAcomputeSampleCoords(gca, mri_in, gcas, nsamples, transform) ;
    if (sample_fname)
      GCAtransformAndWriteSamples
        (gca, mri_in, gcas, nsamples, sample_fname, transform) ;

    for (j = 0 ; j < 1 ; j++)
    {
      for (n = 1 ; n <= nregions ; n++)
      {
        for (norm_samples = i = 0 ; i < NSTRUCTURES ; i++)
        {
          if (normalization_structures[i] == Gdiag_no)
            DiagBreak() ;
          printf("finding control points in %s....\n",
                 cma_label_to_name(normalization_structures[i])) ;
          gcas_struct = find_control_points(gca, gcas, nsamples, &struct_samples, n,
                                            normalization_structures[i], mri_in, transform, min_prior,
                                            ctl_point_pct) ;
          discard_unlikely_control_points(gca, gcas_struct, struct_samples, mri_in, transform,
                                          cma_label_to_name(normalization_structures[i])) ;
          if (mri_ctrl && ctrl_point_fname) // store the samples
            copy_ctrl_points_to_volume(gcas_struct, struct_samples, mri_ctrl, n-1) ;
          if (i)
          {
            GCA_SAMPLE *gcas_tmp ;
            gcas_tmp = gcas_concatenate(gcas_norm, gcas_struct, norm_samples, struct_samples) ;
            free(gcas_norm) ;
            norm_samples += struct_samples ;
            gcas_norm = gcas_tmp ;
          }
          else
          {
            gcas_norm = gcas_struct ; norm_samples = struct_samples ;
          }
        }
        
        printf("using %d total control points "
                 "for intensity normalization...\n", norm_samples) ;
        if (normalized_transformed_sample_fname)
          GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples,
                                      normalized_transformed_sample_fname,
                                      transform) ;
        mri_norm = GCAnormalizeSamplesAllChannels(mri_in, gca, gcas_norm, file_only ? 0 :norm_samples,
                                                  transform, ctl_point_fname, bias_sigma) ;
        if (Gdiag & DIAG_WRITE)
        {
          char fname[STRLEN] ;
          sprintf(fname, "norm%d.mgz", n) ;
          printf("writing normalized volume to %s...\n", fname) ;
          MRIwrite(mri_norm, fname) ;
          sprintf(fname, "norm_samples%d.mgz", n) ;
          GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples,
                                      fname, transform) ;
          
        }
        MRIcopy(mri_norm, mri_in) ;  /* for next pass through */
        MRIfree(&mri_norm) ;
      }
    }
  }

  // now do cross-time normalization to bring each timepoint closer to the mean at each location
  {
    MRI   *mri_frame1, *mri_frame2, *mri_tmp ;
    double rms_before, rms_after ;
    int    i ;

    mri_tmp = MRIcopy(mri_in, NULL) ;
    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_before = MRIrmsDiff(mri_frame1, mri_frame2) ;
    printf("RMS before = %2.2f\n", rms_before) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
    for (i = 50 ; i <= 50 ; i += 25)
    {
      MRIcopy(mri_tmp, mri_in) ;
      normalize_timepoints_with_samples(mri_in, gcas_norm, norm_samples, i) ;
      mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
      mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
      rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
      MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
      printf("RMS after (%d) = %2.2f\n", i, rms_after) ;
    }
  }
  {
    MRI   *mri_frame1, *mri_frame2 ;
    double rms_after ;
    int    i ;

    mri_tmp = MRIcopy(mri_in, NULL) ;
    for (i = 10 ; i <= 10 ; i += 10)
    {
      MRIcopy(mri_tmp, mri_in) ;
      normalize_timepoints(mri_in, 2.0, i) ;
      mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
      mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
      rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
      MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
      printf("RMS after intensity cohering = %2.2f\n", rms_after) ;
    }
  }

  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(fname, "%s/%s.long.%s/mri/%s", sdir, subjects[input], base_name, out_fname) ;
    printf("writing normalized volume to %s...\n", fname) ;
    if (MRIwriteFrame(mri_in, fname, input)  != NO_ERROR)
      ErrorExit(ERROR_BADFILE, "%s: could not write normalized volume to %s",Progname, fname);
  }

  if (ctrl_point_fname)
  {
    printf("writing control points to %s\n", ctrl_point_fname) ;
    MRIwrite(mri_ctrl, ctrl_point_fname) ;
    MRIfree(&mri_ctrl) ;
  }
  MRIfree(&mri_in) ;

  printf("freeing GCA...") ;
  if (gca)
    GCAfree(&gca) ;
  printf("done.\n") ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("normalization took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  if (diag_fp)
    fclose(diag_fp) ;
  exit(0) ;
  return(0) ;
}
Пример #26
0
int
main(int argc, char *argv[])
{
  char   **av, *in_fname;
  int    ac, nargs, i, j,  x, y, z, width, height, depth;
  MRI    *mri_flash[MAX_IMAGES], *mri_label, *mri_mask;
  int index;
  int    msec, minutes, seconds, nvolumes, nvolumes_total ;
  struct timeb start ;
  float max_val, min_val, value;
  float *LDAweight = NULL;
  float **LDAmeans = NULL; /* Centroid for each considered class */
  float *classSize =NULL; /* relative size of each class */
  MATRIX **SWs; /* Within class scatter-matrix for each considered class */
  MATRIX *AdjMatrix; /* Adjacency matrix of all classes */

  FILE *fp;

  int num_classes;
  double cnr;


  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_ms_compute_CNR.c,v 1.10 2011/03/02 00:04:55 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 2)
    usage_exit(1) ;

  printf("command line parsing finished\n");

  if (label_fname == NULL)
  {
    printf("Use -label option to specify file for segmentation \n");
    usage_exit(0);
  }


  if (have_weight == 1 && weight_fname == NULL)
  {
    printf("Use -weight option to specify file for input LDA weights \n") ;
    usage_exit(0);
  }

  if (have_weight == 1 && synth_fname == NULL)
  {
    printf("Use -synth option to specify file for output synthesized volume \n") ;
    usage_exit(0);
  }


  if (ldaflag)
  {
    MINLABEL = MIN(class1, class2);
    MAXLABEL = MAX(class1, class2);
  }

  num_classes = MAXLABEL - MINLABEL + 1;

  printf("Total of %d classes considered in LDA training\n", num_classes);

  if (num_classes <= 1)
  {
    printf("Need to specify at least two classes to evaluate CNR\n");
    usage_exit(0);
  }

  //////////////////////////////////////////////////////////////////////////////////
  /*** Read in the input multi-echo volumes ***/
  nvolumes = 0 ;
  for (i = 1 ; i < argc; i++)
  {
    in_fname = argv[i] ;
    printf("reading %s...\n", in_fname) ;

    mri_flash[nvolumes] = MRIread(in_fname) ;
    if (mri_flash[nvolumes] == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume %s",
                Progname, in_fname) ;
    /* conform will convert all data to UCHAR, which will reduce data resolution*/
    printf("%s read in. \n", in_fname) ;
    if (conform)
    {
      MRI *mri_tmp ;

      printf("embedding and interpolating volume\n") ;
      mri_tmp = MRIconform(mri_flash[nvolumes]) ;
      mri_flash[nvolumes] = mri_tmp ;
    }

    /* Change all volumes to float type for convenience */
    if (mri_flash[nvolumes]->type != MRI_FLOAT)
    {
      printf("Volume %d type is %d\n", nvolumes+1, mri_flash[nvolumes]->type);
      MRI *mri_tmp;
      printf("Change data to float type \n");
      mri_tmp = MRIchangeType(mri_flash[nvolumes], MRI_FLOAT, 0, 1.0, 1);
      MRIfree(&mri_flash[nvolumes]);
      mri_flash[nvolumes] = mri_tmp; //swap
    }

    nvolumes++ ;
  }

  printf("All data read in\n");

  ///////////////////////////////////////////////////////////////////////////
  nvolumes_total = nvolumes ;   /* all volumes read in */

  for (i = 0 ; i < nvolumes ; i++)
  {
    for (j = i+1 ; j < nvolumes ; j++)
    {
      if ((mri_flash[i]->width != mri_flash[j]->width) ||
          (mri_flash[i]->height != mri_flash[j]->height) ||
          (mri_flash[i]->depth != mri_flash[j]->depth))
        ErrorExit(ERROR_BADPARM, "%s:\nvolumes %d (type %d) and %d (type %d) don't match (%d x %d x %d) vs (%d x %d x %d)\n",
                  Progname, i, mri_flash[i]->type, j, mri_flash[j]->type, mri_flash[i]->width,
                  mri_flash[i]->height, mri_flash[i]->depth,
                  mri_flash[j]->width, mri_flash[j]->height, mri_flash[j]->depth) ;
    }
  }

  width = mri_flash[0]->width;
  height = mri_flash[0]->height;
  depth = mri_flash[0]->depth;

  if (label_fname != NULL)
  {
    mri_label = MRIread(label_fname);
    if (!mri_label)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, label_fname);

    if ((mri_label->width != mri_flash[0]->width) ||
        (mri_label->height != mri_flash[0]->height) ||
        (mri_label->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: label volume size doesn't match data volumes\n", Progname);

    /* if(mri_label->type != MRI_UCHAR)
       ErrorExit(ERROR_BADPARM, "%s: label volume is not UCHAR type \n", Progname); */
  }

  if (mask_fname != NULL)
  {
    mri_mask = MRIread(mask_fname);
    if (!mri_mask)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, mask_fname);

    if ((mri_mask->width != mri_flash[0]->width) ||
        (mri_mask->height != mri_flash[0]->height) ||
        (mri_mask->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: mask volume size doesn't macth data volumes\n", Progname);

    if (mri_mask->type != MRI_UCHAR)
      ErrorExit(ERROR_BADPARM, "%s: mask volume is not UCHAR type \n", Progname);
  }
  else
  {
    mri_mask = MRIalloc(mri_flash[0]->width, mri_flash[0]->height, mri_flash[0]->depth, MRI_UCHAR);
    MRIcopyHeader(mri_flash[0], mri_mask);

    /* Simply set mask to be 1 everywhere */
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++)
        {
          MRIvox(mri_mask, x, y,z) = 1;
        }
  }


  if (debug_flag && window_flag)
  {
    /* Limit LDA to a local window */
    printf("Local window size = %d\n", window_size);
    window_size /= 2;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++)
        {
          if (MRIvox(mri_mask, x, y,z) == 0) continue;

          if (z < (Gz - window_size) || z >(Gz + window_size)
              || y <(Gy - window_size) || y > (Gy + window_size)
              || x < (Gx - window_size) || x > (Gx + window_size))
            MRIvox(mri_mask, x, y,z) = 0;
        }

  }

  LDAweight = (float *)calloc(nvolumes_total, sizeof(float));

  /* Allocate memory */
  LDAmeans = (float **)malloc(num_classes*sizeof(float *));
  SWs = (MATRIX **)malloc(num_classes*sizeof(MATRIX *));
  classSize = (float *)malloc(num_classes*sizeof(float));
  for (i=0; i< num_classes; i++)
  {
    LDAmeans[i] = (float *)malloc(nvolumes_total*sizeof(float));
    SWs[i] = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL);
    if (SWs[i] == NULL || LDAmeans[i] == NULL)
      ErrorExit(ERROR_BADPARM, "%s: unable to allocate required memory \n", Progname);
  }

  if (ldaflag)
  {
    AdjMatrix = (MATRIX *)MatrixAlloc(num_classes, num_classes, MATRIX_REAL);

    /* The diagnoal entries of AdjMatrix is set to zero initially */
    for (i=1; i <= num_classes;i++)
      for (j=i; j <= num_classes; j++)
      {
        AdjMatrix->rptr[i][j] = 0.0;
        AdjMatrix->rptr[j][i] = 0.0;
      }

    AdjMatrix->rptr[class1-MINLABEL +1][class2-MINLABEL+1] = 1.0;
    AdjMatrix->rptr[class1-MINLABEL +1][class1-MINLABEL+1] = 1.0;
    AdjMatrix->rptr[class2-MINLABEL +1][class2-MINLABEL+1] = 1.0;
    AdjMatrix->rptr[class2-MINLABEL +1][class1-MINLABEL+1] = 1.0;
  }
  else if (MINLABEL <=2 && MAXLABEL >= 76)
  {
    printf("Manually set adjacent matrix \n");

    AdjMatrix = (MATRIX *)MatrixAlloc(num_classes, num_classes, MATRIX_REAL);

    /* The diagnoal entries of AdjMatrix is set to zero initially */
    for (i=1; i <= num_classes;i++)
      for (j=i; j <= num_classes; j++)
      {
        AdjMatrix->rptr[i][j] = 0.0;
        AdjMatrix->rptr[j][i] = 0.0;
      }

    for (index = 0; index < CNR_pairs; index++)
    {
      i = ilist[index] - MINLABEL;
      j = jlist[index] - MINLABEL;

      AdjMatrix->rptr[i+1][j+1] = 1.0;
      AdjMatrix->rptr[j+1][i+1] = 1.0;
    }

    /* left-hemisphere */
    /*
    AdjMatrix->rptr[2+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[17+1-MINLABEL][18+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[3+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[5+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[4+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[18+1-MINLABEL][2+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[18+1-MINLABEL][3+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[18+1-MINLABEL][5+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[18+1-MINLABEL][4+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][11+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][4+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][12+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][2+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][3+1-MINLABEL] = 1.0;
    */

    /* right-hemisphere */
    /*
    AdjMatrix->rptr[53+1-MINLABEL][41+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][54+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][42+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][44+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][43+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[54+1-MINLABEL][41+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[54+1-MINLABEL][42+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[54+1-MINLABEL][44+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[54+1-MINLABEL][43+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][50+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][43+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][51+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][41+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][42+1-MINLABEL] = 1.0;

    for(i=1; i < num_classes;i++)
      for(j=i+1; j <= num_classes; j++){
    if(AdjMatrix->rptr[i][j] > 0.5)
    AdjMatrix->rptr[j][i] = AdjMatrix->rptr[i][j];
    else
    AdjMatrix->rptr[i][j] = AdjMatrix->rptr[j][i];
      }
    */

    /*    AdjMatrix->rptr[2+1-MINLABEL][3+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][10+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][11+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][12+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][13+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[2+1-MINLABEL][18+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[3+1-MINLABEL][12+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[3+1-MINLABEL][17+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[3+1-MINLABEL][18+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[4+1-MINLABEL][10+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[4+1-MINLABEL][11+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][11+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[10+1-MINLABEL][13+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[12+1-MINLABEL][13+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[12+1-MINLABEL][26+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[17+1-MINLABEL][18+1-MINLABEL] = 1.0;
    */
    /* right-hemisphere */
    /* AdjMatrix->rptr[41+1-MINLABEL][42+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][49+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][50+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][51+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][52+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][53+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[41+1-MINLABEL][54+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[42+1-MINLABEL][51+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[42+1-MINLABEL][53+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[42+1-MINLABEL][54+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[43+1-MINLABEL][49+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[43+1-MINLABEL][50+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][50+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[49+1-MINLABEL][52+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[51+1-MINLABEL][52+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[51+1-MINLABEL][58+1-MINLABEL] = 1.0;
    AdjMatrix->rptr[53+1-MINLABEL][54+1-MINLABEL] = 1.0;
    */
  }
  else
    AdjMatrix = ComputeAdjMatrix(mri_label, mri_mask, MINLABEL, MAXLABEL);
  /* AdjMatrix may need manual adjusted to avoid meaningless comparisons
   * such as computing CNR between left WM and right WM
   */


  for (i=1; i <= num_classes;i++)
    for (j=1; j <= num_classes; j++)
    {
      if (j==i) continue;
      /* the diagonal term will indicate whether the class is useful or not */
      AdjMatrix->rptr[i][i] +=  AdjMatrix->rptr[i][j] + AdjMatrix->rptr[j][i];
    }


  printf("Compute individual class statistics\n");
  /* Compute class means and covariance matrix */
  /* Note that here SWs will be covaraince matrix, not scatter matrix */
  for (i=0; i < num_classes; i++)
  {
    if (AdjMatrix->rptr[i+1][i+1] < 0.5) continue;
    computeClassStats(LDAmeans[i], SWs[i], &classSize[i], mri_flash, mri_label, mri_mask, nvolumes_total, MINLABEL + i);
  }
  printf("class statistics computed \n");

  if (fname != NULL)
    fp = fopen(fname, "w");
  else
    fp = 0;

  printf("compute pair-wise CNR/Mahalanobis distances \n");
  if (ldaflag)
  {
    for (i=0; i <num_classes-1;i++)
      for (j=i+1; j < num_classes; j++)
      {
        if (AdjMatrix->rptr[i+1][j+1] < 0.5) continue;
        cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i],  classSize[j], nvolumes_total, LDAweight, 1);
        if (fp)
          fprintf(fp, "%9.4f ", (float)cnr);

        printf("CNR of class %d and class %d is %g\n", i+MINLABEL, j+MINLABEL, cnr);

      }

    if (fp)
    {
      fprintf(fp, "\n");
      fclose(fp);
    }

  }
  else
  {

    for (index = 0; index < CNR_pairs; index++)
    {
      i = ilist[index] - MINLABEL;
      j = jlist[index] - MINLABEL;

      if (AdjMatrix->rptr[i+1][j+1] < 0.5) continue;
      if (i== (2-MINLABEL) && j == (3-MINLABEL) && nvolumes_total > 1)
        cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i],  classSize[j], nvolumes_total, LDAweight, 1);
      else
        cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i], classSize[j], nvolumes_total, 0, 0);

      if (fp)
        fprintf(fp, "%9.4f ", (float)cnr);

      printf("CNR of class %d and class %d is %g\n", i+MINLABEL, j+MINLABEL, cnr);

    }

    if (fp)
    {
      fprintf(fp, "\n");
      fclose(fp);
    }
  }

  /* output weights for optimize CNR for class 2 and class 3 */
  if (weight_fname != NULL)
  {
    output_weights_to_file(LDAweight, weight_fname, nvolumes_total);
  }

  free(classSize);

  for (i=0; i< num_classes; i++)
  {
    free(LDAmeans[i]);
    MatrixFree(&SWs[i]);
  }
  free(LDAmeans);
  free(SWs);
  MatrixFree(&AdjMatrix);

  if (nvolumes_total > 1 && ((MINLABEL <=2 && MAXLABEL >= 3) || ldaflag))
  {
    if (ldaflag)
    {
      printf("LDA weights for %d-%d are: \n", class1, class2);
    }
    else
    {
      printf("LDA weights for 2-3 are: \n");
    }
    for (i=0; i < nvolumes_total; i++)
    {
      printf("%g ", LDAweight[i]);
    }
    printf("\n");

    if (synth_fname != NULL)
    {
      /* linear projection of input volumes to a 1D volume */
      min_val = 10000.0;
      max_val = -10000.0;
      for (z=0; z < depth; z++)
        for (y=0; y< height; y++)
          for (x=0; x < width; x++)
          {
            if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

            value = 0.0;

            for (i=0; i < nvolumes_total; i++)
            {
              value += MRIFvox(mri_flash[i], x, y, z)*LDAweight[i];
            }



            if (max_val < value) max_val = value;
            if (min_val > value) min_val = value;

            /* Borrow mri_flash[0] to store the float values first */
            MRIFvox(mri_flash[0], x, y, z) = value;
          }

      printf("max_val = %g, min_val = %g \n", max_val, min_val);

      /* Scale output to [0, 255] */
      for (z=0; z < depth; z++)
        for (y=0; y< height; y++)
          for (x=0; x < width; x++)
          {
            if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

            value = (MRIFvox(mri_flash[0], x, y, z) - min_val)*255.0/(max_val - min_val) + 0.5; /* +0.5 for round-off */

            if (value > 255.0) value = 255.0;
            if (value < 0) value = 0;

            /* Borrow mri_flash[0] to store the float values first */
            MRIvox(mri_mask, x, y, z) = (BUFTYPE) value;
          }

      /* Output synthesized volume */
      MRIwrite(mri_mask, synth_fname);
    }
  }

  free(LDAweight);

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("LDA took %d minutes and %d seconds.\n", minutes, seconds) ;

  MRIfree(&mri_mask);

  MRIfree(&mri_label);


  for (i=0; i < nvolumes_total; i++)
  {
    MRIfree(&mri_flash[i]);
  }
  exit(0);
}
Пример #27
0
void TimerReset( TimerEvent_t *obj )
{
  TimerStop( obj );
  TimerStart( obj );
}
Пример #28
0
int
main(int argc, char *argv[]) {
  char   **av, *subject_name, *cp, *hemi, *surf_name, *annot_name, fname[STRLEN], *name ;
  int    ac, nargs, msec, minutes, label, seconds, i ;
  double area, total_area ;
  struct timeb start ;
  MRIS   *mris ;
  FILE   *log_fp ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_label_area.c,v 1.6 2011/03/02 00:04:32 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 6)
    usage_exit(1) ;


  subject_name = argv[1] ;
  hemi = argv[2] ;
  surf_name = argv[3] ;
  annot_name = argv[4] ;

  if (strlen(sdir) == 0) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in env or cmd line",Progname) ;
    strcpy(sdir, cp) ;
  }
  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject_name, hemi, surf_name) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface from %s",Progname,
              fname) ;

  MRIScomputeMetricProperties(mris) ;
#if 0
  if (in_label >= 0)
    MRIreplaceValues(mri, mri, in_label, out_label) ;
#endif

  if (compute_pct)
    total_area = mris->total_area ;
  else
    total_area = 1 ;

  if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read annot file %s", Progname, annot_name) ;

  for (i = 5 ; i < argc ; i++) {
    label = atoi(argv[i]) ;
    name = annotation_to_name(index_to_annotation(label), NULL) ;
    printf("processing label %s (%d)...\n", name, label) ;


    area = MRISannotArea(mris, label) ;
    if (log_fname) {
      char fname[STRLEN] ;

      sprintf(fname, log_fname, label) ;
      printf("logging to %s...\n", fname) ;
      log_fp = fopen(fname, "a+") ;
      if (!log_fp)
        ErrorExit(ERROR_BADFILE, "%s: could not open %s for writing",
                  Progname, fname) ;
    } else
      log_fp = NULL ;

    if (compute_pct) {
      printf("%2.3f mm^2 in label %d (%s), %%%2.6f of total cortical area (%2.2f)\n",
             area, label, name,
             100.0*(float)area/(float)total_area,
             total_area) ;
      if (log_fp) {
        fprintf(log_fp,"%2.6f\n", 100.0*area/(float)total_area) ;
        fclose(log_fp) ;
      }
    } else {
      printf("%2.0f mm^2 in label %s (%d)\n", area, name, label) ;
      if (log_fp) {
        fprintf(log_fp,"%f\n", area) ;
        fclose(log_fp) ;
      }
    }
  }

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;

  if (DIAG_VERBOSE_ON)
    printf("area calculation took %d minutes and %d seconds.\n",
           minutes, seconds) ;

  exit(0) ;
  return(0) ;
}
Пример #29
0
int
main(int argc, char *argv[]) {
  char   **av, *label_name, *vol_name, *out_name ;
  int    ac, nargs ;
  int    msec, minutes, seconds,  i  ;
  LABEL  *area ;
  struct timeb start ;
  MRI    *mri,  *mri_seg ;
  Real   xw, yw, zw, xv, yv, zv, val;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_label_vals.c,v 1.16 2015/08/24 18:22:05 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
    usage_exit(1) ;

  vol_name = argv[1] ;
  label_name = argv[2]  ;
  out_name = argv[3] ;

  mri = MRIread(vol_name) ;
  if (!mri)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, vol_name) ;
  if (scaleup_flag) {
    float scale, fov_x, fov_y, fov_z  ;

    scale = 1.0/MIN(MIN(mri->xsize, mri->ysize),mri->zsize) ;
    fprintf(stderr, "scaling voxel sizes up by %2.2f\n", scale) ;
    mri->xsize *= scale ;
    mri->ysize *= scale ;
    mri->zsize *= scale ;
    fov_x = mri->xsize * mri->width;
    fov_y = mri->ysize * mri->height;
    fov_z = mri->zsize * mri->depth;
    mri->xend = fov_x / 2.0;
    mri->xstart = -mri->xend;
    mri->yend = fov_y / 2.0;
    mri->ystart = -mri->yend;
    mri->zend = fov_z / 2.0;
    mri->zstart = -mri->zend;

    mri->fov = (fov_x > fov_y ? (fov_x > fov_z ? fov_x : fov_z) : (fov_y > fov_z ? fov_y : fov_z) );
  }

  if (segmentation_flag >= 0) {
    int x, y, z  ;
    VECTOR *v_seg, *v_mri ;
    MATRIX *m_seg_to_mri ;

    v_seg = VectorAlloc(4, MATRIX_REAL) ;
    v_mri = VectorAlloc(4, MATRIX_REAL) ;
    VECTOR_ELT(v_seg, 4) = 1.0 ;
    VECTOR_ELT(v_mri, 4) = 1.0 ;

    mri_seg = MRIread(argv[2]) ;
    if (!mri_seg)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, argv[2]) ;
    if (erode) {
      MRI *mri_tmp ;

      mri_tmp = MRIclone(mri_seg, NULL) ;
      MRIcopyLabel(mri_seg, mri_tmp, segmentation_flag) ;
      while (erode-- > 0)
        MRIerode(mri_tmp, mri_tmp) ;
      MRIcopy(mri_tmp, mri_seg) ;
      MRIfree(&mri_tmp) ;
    }

    m_seg_to_mri = MRIgetVoxelToVoxelXform(mri_seg, mri) ;
    for (x = 0  ; x  < mri_seg->width ; x++) {
      V3_X(v_seg) = x ;
      for (y = 0  ; y  < mri_seg->height ; y++) {
        V3_Y(v_seg) = y ;
        for (z = 0  ; z  < mri_seg->depth ; z++) {
          V3_Z(v_seg) = z ;
          if (MRIvox(mri_seg, x, y,  z) == segmentation_flag) {
            MatrixMultiply(m_seg_to_mri, v_seg, v_mri) ;
            xv = V3_X(v_mri) ;
            yv = V3_Y(v_mri) ;
            zv = V3_Z(v_mri) ;
            MRIsampleVolumeType(mri, xv,  yv, zv, &val, SAMPLE_NEAREST);
#if  0
            if (val < .000001) {
              val *= 1000000;
              printf("%f*0.000001\n", val);
            } else
#endif
              if (coords)
                printf("%2.1f %2.1f %2.1f %f\n", xv, yv, zv, val);
              else
                printf("%f\n", val);
          }
        }
      }
    }
    MatrixFree(&m_seg_to_mri) ;
    VectorFree(&v_seg) ;
    VectorFree(&v_mri) ;
  } else {
    if (cras == 1)
      fprintf(stderr,"using the label coordinates to be c_(r,a,s) != 0.\n");

    if (surface_dir) {
      MRI_SURFACE *mris ;
      char fname[STRLEN] ;
      sprintf(fname, "%s/%s.white", surface_dir, hemi) ;
      mris = MRISread(fname) ;
      if (mris == NULL)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s...\n", Progname,fname) ;
      sprintf(fname, "%s/%s.thickness", surface_dir, hemi) ;
      if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
        ErrorExit(ERROR_BADPARM, "%s: could not read thickness file %s...\n", Progname,fname) ;

      if (annot_prefix)   /* read an annotation in and print vals in it */
      {
#define MAX_ANNOT 10000
        int   vno, annot_counts[MAX_ANNOT], index ;
        VERTEX *v ;
        Real  xw, yw, zw, xv, yv, zv, val ;
        float annot_means[MAX_ANNOT] ;
        FILE  *fp ;

        memset(annot_means, 0, sizeof(annot_means)) ;
        memset(annot_counts, 0, sizeof(annot_counts)) ;
        if (MRISreadAnnotation(mris, label_name) != NO_ERROR)
          ErrorExit(ERROR_BADPARM, "%s: could not read annotation file %s...\n", Progname,fname) ;
        if (mris->ct == NULL)
          ErrorExit(ERROR_BADPARM, "%s: annot file does not contain a color table, specifiy one with -t ", Progname);
        for (vno = 0 ; vno < mris->nvertices ; vno++) {
          v = &mris->vertices[vno] ;
          if (v->ripflag)
            continue ;
          CTABfindAnnotation(mris->ct, v->annotation, &index) ;
          if (index >= 0 && index < mris->ct->nentries) {
            annot_counts[index]++ ;
            xw = v->x + v->curv*.5*v->nx ;
            yw = v->y + v->curv*.5*v->ny ;
            zw = v->z + v->curv*.5*v->nz ;
            if (cras == 1)
              MRIworldToVoxel(mri, xw, yw,  zw, &xv, &yv, &zv) ;
            else
              MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv);
            MRIsampleVolume(mri, xv, yv, zv, &val) ;
            annot_means[index] += val ;
            sprintf(fname, "%s-%s-%s.dat", annot_prefix, hemi, mris->ct->entries[index]->name) ;
            fp = fopen(fname, "a") ;
            fprintf(fp, "%f\n", val) ;
            fclose(fp) ;
          }
        }
      }
      else  /* read label in and print vals in it */
      {
        area = LabelRead(NULL, label_name) ;
        if (!area)
          ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",Progname, label_name) ;

      }
    } else {
      area = LabelRead(NULL, label_name) ;
      if (!area)
        ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",Progname, label_name) ;

      for (i = 0 ;  i  < area->n_points ; i++) {

        xw =  area->lv[i].x ;
        yw =  area->lv[i].y ;
        zw =  area->lv[i].z ;
        if (cras == 1)
          MRIworldToVoxel(mri, xw, yw,  zw, &xv, &yv, &zv) ;
        else
          MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv);
        MRIsampleVolumeType(mri, xv,  yv, zv, &val, SAMPLE_NEAREST);
#if 0
        if (val < .000001) {
          val *= 1000000;
          printf("%f*0.000001\n", val);
        } else
#endif
          printf("%f\n", val);
      }
    }
  }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;

  if (DIAG_VERBOSE_ON)
    fprintf(stderr, "label value extractiong took %d minutes and %d seconds.\n",
            minutes, seconds) ;

  exit(0) ;
  return(0) ;
}
Пример #30
0
void CleanupGlobals() 
{
	TimerStop();
}