Beispiel #1
0
	struct lisp_db *
ms_init_db()
{
	struct prefix p;
	struct db_node *dn;
	struct lisp_db *db;
	db = calloc(1, sizeof(struct lisp_db));

	//make new tree
	db->lisp_db4 = db_table_init(&ms_free_node);
	db->lisp_db6 = db_table_init(&ms_free_node);

	//assign 0.0.0.0/0 as root of ipv4 tree
	str2prefix("0.0.0.0/0",&p);
	apply_mask(&p);
	dn = db_node_get(db->lisp_db4,&p);
	assert(dn == (db->lisp_db4->top));
	dn->flags = ms_new_node_ex(_ROOT);

	//and 0::/0 as root of ipv6 tree
	str2prefix("0::/0",&p);
	apply_mask(&p);
	dn = db_node_get(db->lisp_db6,&p);
	assert(dn == (db->lisp_db6->top));
	dn->flags = ms_new_node_ex(_ROOT);

	return db;
}
Beispiel #2
0
void cRoberts( const unsigned char* src, unsigned char *dst, int width, int height, int xorder, int yorder ) {
	int x, y, k;
	int line = lineSize(width,4);

	for( y = 0 ; y < height-1 ; y++ )
		for( x = 0 ; x < width-1 ; x++ ) {
			k =xorder * apply_mask( &src[line*(y-1)+x-1], line, OPERADOR_ROBERTS_X, 2 );
			k+=yorder * apply_mask( &src[line*(y-1)+x-1], line, OPERADOR_ROBERTS_Y, 2 );
			dst[line*y+x]=toCharS(k);
		}
}
Beispiel #3
0
void cPrewitt( const unsigned char* src, unsigned char *dst, int width, int height, int xorder, int yorder ) {
	int x, y, k;
	int line = lineSize(width,4);

	for( y = 1 ; y < height-1 ; y++ )
		for( x = 1 ; x < width-1 ; x++ ) {
			k =xorder * apply_mask( &src[line*(y-1)+x-1], line, OPERADOR_PREWITT_X, 3 );
			k+=yorder * apply_mask( &src[line*(y-1)+x-1], line, OPERADOR_PREWITT_Y, 3 );
			dst[line*y+x]=toCharS(k);
		}
}
Beispiel #4
0
/**
 * cX - procesa la imagen con el operador X
 *		src	array de pixels ordenados (grayscale)
 *		dst	array de pixels final
 *		width	ancho (en pixels) de la imagen
 *		height	alto (en pixels) de la imagen
 *		xorder	orden de la derivada x
 *		yorder	orden de la derivada y
 */
void cSobel( const unsigned char* src, unsigned char *dst, int width, int height, int xorder, int yorder ) {
	int x, y, k;
	int line = lineSize(width,4);

	for( y = 1 ; y < height-1 ; y++ )
		for( x = 1 ; x < width-1 ; x++ ) {
			k=0;
			if( xorder != 0 )
				k =toCharS(apply_mask( &src[line*(y-1)+x-1], line, OPERADOR_SOBEL_X, 3 ));
			if( yorder != 0 )
				k+=toCharS(apply_mask( &src[line*(y-1)+x-1], line, OPERADOR_SOBEL_Y, 3 ));
			dst[line*y+x]=toCharS(k);
		}
}
Beispiel #5
0
// Called when an ARES socket is ready
static void process_ares(ph_job_t *job, ph_iomask_t why, void *data)
{
  ph_dns_channel_t *chan = data;
  ares_socket_t fd;
  ares_socket_t rfd = ARES_SOCKET_BAD;
  ares_socket_t wfd = ARES_SOCKET_BAD;

  fd = job->fd;

  if (why & PH_IOMASK_READ) {
    rfd = job->fd;
  }
  if (why & PH_IOMASK_WRITE) {
    wfd = job->fd;
  }

  pthread_mutex_lock(&chan->chanlock);
  ares_process_fd(chan->chan, rfd, wfd);
  if (ph_ht_lookup(&chan->sock_map, &fd, &job, false) == PH_OK &&
      ph_job_get_kmask(job) == 0) {
    // Didn't delete it, but didn't reschedule it, so do that now
    apply_mask(chan, job,
        job->mask ? job->mask : PH_IOMASK_READ);
  }
  pthread_mutex_unlock(&chan->chanlock);
}
Beispiel #6
0
/* called when ares wants to change the event mask */
static void sock_state_cb(void *data, ares_socket_t socket_fd,
                          int readable, int writable)
{
  ph_dns_channel_t *chan = data;
  ph_job_t *job;
  ph_iomask_t mask = 0;

  if (readable) {
    mask |= PH_IOMASK_READ;
  }
  if (writable) {
    mask |= PH_IOMASK_WRITE;
  }

  if (ph_ht_lookup(&chan->sock_map, &socket_fd, &job, false) != PH_OK) {
    ph_panic("job for socket %d was not found in ares sock_state_cb",
        socket_fd);
  }

  if (mask) {
    apply_mask(chan, job, mask);
  } else {
    ph_job_set_nbio(job, 0, NULL);
    // We're done with this guy, remove it
    ph_ht_del(&chan->sock_map, &socket_fd);
    ph_mem_free(mt.job, job);
  }
}
struct ospf_interface *
ospf_if_lookup_by_prefix (struct ospf *ospf, struct prefix_ipv4 *p)
{
  struct listnode *node;
  struct ospf_interface *oi;
  struct prefix ptmp;
  
  /* Check each Interface. */
  for (node = listhead (ospf->oiflist); node; nextnode (node))
    {
      if ((oi = getdata (node)) != NULL && oi->type != OSPF_IFTYPE_VIRTUALLINK)
	{
	  if ((oi->type == OSPF_IFTYPE_POINTOPOINT) &&
	      CONNECTED_DEST_HOST(oi->connected))
	    {
	      prefix_copy (&ptmp, oi->connected->destination);
	      ptmp.prefixlen = IPV4_MAX_BITLEN;
	    }
	  else
	    prefix_copy (&ptmp, oi->address);
	
	  apply_mask (&ptmp);
	  if (prefix_same (&ptmp, (struct prefix *) p))
	    return oi;
	}
    }
  return NULL;
}
Beispiel #8
0
/* Tie an interface address to its derived subnet list of addresses. */
int
if_subnet_add (struct interface *ifp, struct connected *ifc)
{
  struct route_node *rn;
  struct zebra_if *zebra_if;
  struct prefix cp;
  struct list *addr_list;

  assert (ifp && ifp->info && ifc);
  zebra_if = ifp->info;

  /* Get address derived subnet node and associated address list, while marking
     address secondary attribute appropriately. */
  cp = *ifc->address;
  apply_mask (&cp);
  rn = route_node_get (zebra_if->ipv4_subnets, &cp);

  if ((addr_list = rn->info))
    SET_FLAG (ifc->flags, ZEBRA_IFA_SECONDARY);
  else
    {
      UNSET_FLAG (ifc->flags, ZEBRA_IFA_SECONDARY);
      rn->info = addr_list = list_new ();
      route_lock_node (rn);
    }

  /* Tie address at the tail of address list. */
  listnode_add (addr_list, ifc);
  
  /* Return list element count. */
  return (addr_list->count);
}
Beispiel #9
0
void regular_graph_generator::make_2d(vle::devs::Executive &executive,
                                      const std::array<int, 2> &length,
                                      const std::array<bool, 2> &wrap,
                                      const utils::Array<std::string> &mask,
                                      int x_mask,
                                      int y_mask)
{
    if (length[0] * length[1] <= 0 or x_mask < 0 or y_mask < 0 or
        utils::numeric_cast<std::size_t>(x_mask) >= mask.columns() or
        utils::numeric_cast<std::size_t>(y_mask) >= mask.rows())
        throw vle::utils::ArgError(
            _("regular_graph_generator: bad parameters"));

    utils::Array<std::string> modelnames(length[0], length[1]);
    std::string name, classname;
    regular_graph_generator::node_metrics metrics{-1, -1, -1};

    m_metrics.vertices = length[0] * length[1];

    for (int c = 0; c != length[0]; ++c) {
        for (int r = 0; r != length[1]; ++r) {
            metrics.x = c;
            metrics.y = r;
            m_params.make_model(metrics, name, classname);
            executive.createModelFromClass(classname, name);
            modelnames(c, r) = name;
        }
    }

    if (not wrap[0] and not wrap[1])
        for (int c = 0; c != length[0]; ++c)
            for (int r = 0; r != length[1]; ++r)
                apply_mask(executive,
                           m_params,
                           modelnames,
                           c,
                           r,
                           length,
                           mask,
                           x_mask,
                           y_mask);
    else
        for (int c = 0; c != length[0]; ++c)
            for (int r = 0; r != length[1]; ++r)
                apply_wrap_mask(executive,
                                wrap,
                                m_params,
                                modelnames,
                                c,
                                r,
                                length,
                                mask,
                                x_mask,
                                y_mask);
}
Beispiel #10
0
void
get_rgb_with_masking(ImageInfo *ii, ImageInfo *mask,
                     int l, int s,
                     unsigned char *r, unsigned char *g, unsigned char *b)
{
    int f = (int)cached_image_get_pixel(mask->data_ci, l, s);
    if (!apply_mask(f, r, g, b)) {
        // not masked, show the regular image's pixel value
        cached_image_get_rgb(ii->data_ci, l, s, r, g, b);
    }
}
 void read_initial_conditions(const char* filename, int NUM, double** y_host, double** variable_host) {
    (*y_host) = (double*)malloc(NUM * NN * sizeof(double));
    (*variable_host) = (double*)malloc(NUM * sizeof(double));
    FILE *fp = fopen (filename, "rb");
    if (fp == NULL)
    {
        fprintf(stderr, "Could not open file: %s\\\n", filename);
        exit(-1);
    }
    double buffer[NN + 2];

    // load temperature and mass fractions for all threads (cells)
    for (int i = 0; i < NUM; ++i)
    {
        // read line from data file
        int count = fread(buffer, sizeof(double), NN + 2, fp);
        if (count != (NN + 2))
        {
            fprintf(stderr, "File (%s) is incorrectly formatted, %d doubles were expected but only %d were read.\\n", filename, NN + 1, count);
            exit(-1);
        }
        //apply mask if necessary
        apply_mask(&buffer[3]);
        //put into y_host
        (*y_host)[i * NN] = buffer[1];
#ifdef CONP
        (*variable_host)[i] = buffer[2];
#elif CONV
        double pres = buffer[2];
#endif
        for (int j = 0; j < NSP; j++)
        {
            (*y_host)[i * NN + j + 1] = buffer[j + 3];
        }

        // if constant volume, calculate density
#ifdef CONV
        double Yi[NSP];
        double Xi[NSP];

        for (int j = 1; j < NN; ++j)
        {
            Yi[j - 1] = (*y_host)[i * NN + j];
        }

        mass2mole (Yi, Xi);
        (*variable_host)[i] = getDensity ((*y_host)[i], pres, Xi);
#endif
    }
    fclose (fp);
}
Beispiel #12
0
ThumbnailData *get_thumbnail_data(ImageInfo *ii)
{
    assert(ii && ii->data_ci && ii->meta);

    int larger_dim = THUMB_SIZE*4;
    if (larger_dim > ii->meta->general->line_count)
        larger_dim = ii->meta->general->line_count;

    //printf("Larger size: %d\n", larger_dim);

    // Vertical and horizontal scale factors required to meet the
    // max_thumbnail_dimension part of the interface contract.
    int vsf = ceil (ii->nl / larger_dim);
    int hsf = ceil (ii->ns / larger_dim);
    // Overall scale factor to use is the greater of vsf and hsf.
    int sf = (hsf > vsf ? hsf : vsf);

    // Image sizes.
    int tsx = ii->meta->general->sample_count / sf;
    int tsy = ii->meta->general->line_count / sf;
    //printf("Sizes: %d, %d\n", tsx, tsy);

    // this will also calculate the image statistics (estimates)
    unsigned char *data = generate_thumbnail_data(ii, tsx, tsy);

    // now add the mask if we have one
    if (mask) {
        int i, j;
        unsigned char r, g, b;
        for (i=0; i<tsy; ++i) {
            for (j=0; j<tsx; ++j) {
                int f = (int)cached_image_get_pixel(mask->data_ci, i*sf, j*sf);
                if (apply_mask(f, &r, &g, &b)) {
                    assert(3*(i*tsx+j)+2 < 3*tsx*tsy);
                    data[3*(i*tsx+j)] = r;
                    data[3*(i*tsx+j)+1] = g;
                    data[3*(i*tsx+j)+2] = b;
                }
            }
        }
    }

    ThumbnailData *ret = MALLOC(sizeof(ThumbnailData));
    ret->size_x = tsx;
    ret->size_y = tsy;
    ret->data = data;

    return ret;
}
Beispiel #13
0
struct ospf_interface *ospf_if_lookup_by_prefix(struct ospf *ospf,
						struct prefix_ipv4 *p)
{
	struct listnode *node;
	struct ospf_interface *oi;

	/* Check each Interface. */
	for (ALL_LIST_ELEMENTS_RO(ospf->oiflist, node, oi)) {
		if (oi->type != OSPF_IFTYPE_VIRTUALLINK) {
			struct prefix ptmp;

			prefix_copy(&ptmp, CONNECTED_PREFIX(oi->connected));
			apply_mask(&ptmp);
			if (prefix_same(&ptmp, (struct prefix *)p))
				return oi;
		}
	}
	return NULL;
}
Beispiel #14
0
static s32 bgp_api_parse_aggregate_packet(WS_ENV * ws_env,u16 type, u8 * pre, u8 as_set, u8 summary_only)
{
    web_bgp_aggregate_info_t info;
    if( !str2prefix( (s8*)pre, &info.p ) )
        goto parse_packet_error ;

    apply_mask (&info.p);
    info.as_set = as_set;
    info.summary_only = summary_only ;

    if( socket_api_put(type,&info,sizeof(web_bgp_aggregate_info_t)) < 0)
        goto socket_api_put_error ;

    return WS_OK;
parse_packet_error:
    socket_api_close();
    return ws_send_soap_error(ws_env,"aggregate parse packet error!") ;
socket_api_put_error:
    socket_api_close();
    return ws_send_soap_error(ws_env,"send packet error!") ;
}
Beispiel #15
0
struct rnh *
zebra_lookup_rnh (struct prefix *p, vrf_id_t vrfid)
{
  struct route_table *table;
  struct route_node *rn;

  table = lookup_rnh_table(vrfid, PREFIX_FAMILY(p));
  if (!table)
    return NULL;

  /* Make it sure prefixlen is applied to the prefix. */
  apply_mask (p);

  /* Lookup route node.*/
  rn = route_node_lookup (table, p);
  if (!rn)
    return NULL;

  route_unlock_node (rn);
  return (rn->info);
}
Beispiel #16
0
struct rnh *
zebra_add_rnh (struct prefix *p, vrf_id_t vrfid)
{
  struct route_table *table;
  struct route_node *rn;
  struct rnh *rnh = NULL;

  if (IS_ZEBRA_DEBUG_NHT)
    {
      char buf[INET6_ADDRSTRLEN];
      prefix2str(p, buf, INET6_ADDRSTRLEN);
      zlog_debug("add rnh %s in vrf %d", buf, vrfid);
    }
  table = lookup_rnh_table(vrfid, PREFIX_FAMILY(p));
  if (!table)
    {
      zlog_debug("add_rnh: rnh table not found\n");
      return NULL;
    }

  /* Make it sure prefixlen is applied to the prefix. */
  apply_mask (p);

  /* Lookup (or add) route node.*/
  rn = route_node_get (table, p);

  if (!rn->info)
    {
      rnh = XCALLOC(MTYPE_RNH, sizeof(struct rnh));
      rnh->client_list = list_new();
      route_lock_node (rn);
      rn->info = rnh;
      rnh->node = rn;
    }

  route_unlock_node (rn);
  return (rn->info);
}
Beispiel #17
0
struct ospf_interface *
ospf_if_lookup_by_prefix (struct ospf *ospf, struct prefix_ipv4 *p)
{
  listnode node;
  struct ospf_interface *oi;
  struct prefix ptmp;
  
  /* Check each Interface. */
  for (node = listhead (ospf->oiflist); node; nextnode (node))
    {
      if ((oi = getdata (node)) != NULL && oi->type != OSPF_IFTYPE_VIRTUALLINK)
	{
	  prefix_copy (&ptmp, oi->address);

	  if (oi->type == OSPF_IFTYPE_POINTOPOINT)
  	      ptmp.prefixlen = IPV4_ALLOWABLE_BITLEN_P2P;
	
	  apply_mask (&ptmp);
	  if (prefix_same (&ptmp, (struct prefix *) p))
	    return oi;
	}
    }
  return NULL;
}
Beispiel #18
0
/* General fucntion for static route. */
int
zebra_static_ipv4 (struct vty *vty, int add_cmd,
		   char *dest_str, char *mask_str, char *gate_str,
		   char *distance_str)
{
  int ret;
  u_char distance;
  struct prefix p;
  struct in_addr gate;
  struct in_addr mask;
  char *ifname;
  
  ret = str2prefix (dest_str, &p);
  if (ret <= 0)
    {
      vty_out (vty, "%% Malformed address%s", VTY_NEWLINE);
      return CMD_WARNING;
    }

  /* Cisco like mask notation. */
  if (mask_str)
    {
      ret = inet_aton (mask_str, &mask);
      if (ret == 0)
	{
	  vty_out (vty, "%% Malformed address%s", VTY_NEWLINE);
	  return CMD_WARNING;
	}
      p.prefixlen = ip_masklen (mask);
    }

  /* Apply mask for given prefix. */
  apply_mask (&p);

  /* Administrative distance. */
  if (distance_str)
    distance = atoi (distance_str);
  else
    distance = ZEBRA_STATIC_DISTANCE_DEFAULT;

  /* Null0 static route.  */
  if (strncasecmp (gate_str, "Null0", strlen (gate_str)) == 0)
    {
      if (add_cmd)
	static_add_ipv4 (&p, NULL, NULL, distance, 0);
      else
	static_delete_ipv4 (&p, NULL, NULL, distance, 0);
      return CMD_SUCCESS;
    }

  /* When gateway is A.B.C.D format, gate is treated as nexthop
     address other case gate is treated as interface name. */
  ret = inet_aton (gate_str, &gate);
  if (ret)
    ifname = NULL;
  else
    ifname = gate_str;

  if (add_cmd)
    static_add_ipv4 (&p, ifname ? NULL : &gate, ifname, distance, 0);
  else
    static_delete_ipv4 (&p, ifname ? NULL : &gate, ifname, distance, 0);

  return CMD_SUCCESS;
}
Beispiel #19
0
void chmod_cmd (void)
{
    char buffer [BUF_TINY];
    char *fname;
    int i;
    struct stat sf_stat;
    Dlg_head *ch_dlg;

    do {			/* do while any files remaining */
        ch_dlg = init_chmod ();
        if (current_panel->marked)
            fname = next_file ();	/* next marked file */
        else
            fname = selection (current_panel)->fname;	/* single file */

        if (mc_stat (fname, &sf_stat) != 0) {	/* get status of file */
            destroy_dlg (ch_dlg);
            break;
        }

        c_stat = sf_stat.st_mode;
        mode_change = 0;	/* clear changes flag */

        /* set check buttons */
        for (i = 0; i < PERMISSIONS; i++) {
            check_perm[i].check->state = (c_stat & check_perm[i].mode) ? 1 : 0;
            check_perm[i].selected = 0;
        }

        /* Set the labels */
        c_fname = name_trunc (fname, 21);
        add_widget (ch_dlg, label_new (FY+2, FX+2, c_fname));
        c_fown = name_trunc (get_owner (sf_stat.st_uid), 21);
        add_widget (ch_dlg, label_new (FY+6, FX+2, c_fown));
        c_fgrp = name_trunc (get_group (sf_stat.st_gid), 21);
        add_widget (ch_dlg, label_new (FY+8, FX+2, c_fgrp));
        g_snprintf (buffer, sizeof (buffer), "%o", c_stat);
        statl = label_new (FY+4, FX+2, buffer);
        add_widget (ch_dlg, statl);

        run_dlg (ch_dlg);	/* retrieve an action */

        /* do action */
        switch (ch_dlg->ret_value) {
        case B_ENTER:
            if (mode_change)
                if (mc_chmod (fname, c_stat) == -1)
                    message (1, MSG_ERROR, _(" Cannot chmod \"%s\" \n %s "),
                             fname, unix_error_string (errno));
            need_update = 1;
            break;

        case B_CANCEL:
            end_chmod = 1;
            break;

        case B_ALL:
        case B_MARKED:
            and_mask = or_mask = 0;
            and_mask = ~and_mask;

            for (i = 0; i < PERMISSIONS; i++) {
                if (check_perm[i].selected || ch_dlg->ret_value == B_ALL) {
                    if (check_perm[i].check->state & C_BOOL)
                        or_mask |= check_perm[i].mode;
                    else
                        and_mask &= ~check_perm[i].mode;
                }
            }

            apply_mask (&sf_stat);
            break;

        case B_SETMRK:
            and_mask = or_mask = 0;
            and_mask = ~and_mask;

            for (i = 0; i < PERMISSIONS; i++) {
                if (check_perm[i].selected)
                    or_mask |= check_perm[i].mode;
            }

            apply_mask (&sf_stat);
            break;
        case B_CLRMRK:
            and_mask = or_mask = 0;
            and_mask = ~and_mask;

            for (i = 0; i < PERMISSIONS; i++) {
                if (check_perm[i].selected)
                    and_mask &= ~check_perm[i].mode;
            }

            apply_mask (&sf_stat);
            break;
        }

        if (current_panel->marked && ch_dlg->ret_value!=B_CANCEL) {
            do_file_mark (current_panel, c_file, 0);
            need_update = 1;
        }
        destroy_dlg (ch_dlg);
    } while (current_panel->marked && !end_chmod);
    chmod_done ();
}
Beispiel #20
0
int main_sense(int argc, char* argv[])
{
	struct sense_conf conf = sense_defaults;

	double start_time = timestamp();

	bool admm = false;
	bool ist = false;
	bool use_gpu = false;
	bool l1wav = false;
	bool lowrank = false;
	bool randshift = true;
	int maxiter = 30;
	float step = 0.95;
	float lambda = 0.;

	float restrict_fov = -1.;
	const char* pat_file = NULL;
	const char* traj_file = NULL;
	const char* image_truth_file = NULL;
	bool im_truth = false;
	bool scale_im = false;

	bool hogwild = false;
	bool fast = false;
	float admm_rho = iter_admm_defaults.rho;

	int c;
	while (-1 != (c = getopt(argc, argv, "Fq:l:r:s:i:u:o:O:f:t:cT:Imghp:Sd:H"))) {
		switch(c) {

		case 'H':
			hogwild = true;
			break;

		case 'F':
			fast = true;
			break;

		case 'I':
			ist = true;
			break;

		case 'T':
			im_truth = true;
			image_truth_file = strdup(optarg);
			assert(NULL != image_truth_file);
			break;

		case 'd':
			debug_level = atoi(optarg);
			break;

		case 'r':
			lambda = atof(optarg);
			break;

		case 'O':
			conf.rwiter = atoi(optarg);
			break;

		case 'o':
			conf.gamma = atof(optarg);
			break;

		case 's':
			step = atof(optarg);
			break;

		case 'i':
			maxiter = atoi(optarg);
			break;

		case 'l':
			if (1 == atoi(optarg)) {

				l1wav = true;
				lowrank = false;

			} else
			if (2 == atoi(optarg)) {

				l1wav = false;
				lowrank = false;

			} else
			if (3 == atoi(optarg)) {

				lowrank = true;
				l1wav = false;

			} else {

				usage(argv[0], stderr);
				exit(1);
			}
			break;

		case 'q':
			conf.cclambda = atof(optarg);
			break;

		case 'c':
			conf.rvc = true;
			break;

		case 'f':
			restrict_fov = atof(optarg);
			break;

		case 'm':
			admm = true;
			break;

		case 'u':
			admm_rho = atof(optarg);
			break;

		case 'g':
			use_gpu = true;
			break;

		case 'p':
			pat_file = strdup(optarg);
			break;

		case 't':
			assert(0);
			break;

		case 'S':
			scale_im = true;
			break;

		case 'h':
			usage(argv[0], stdout);
			help();
			exit(0);

		default:
			usage(argv[0], stderr);
			exit(1);
		}
	}

	if (argc - optind != 3) {

		usage(argv[0], stderr);
		exit(1);
	}

	long map_dims[DIMS];
	long pat_dims[DIMS];
	long img_dims[DIMS];
	long ksp_dims[DIMS];
	long max_dims[DIMS];


	// load kspace and maps and get dimensions

	complex float* kspace = load_cfl(argv[optind + 0], DIMS, ksp_dims);
	complex float* maps = load_cfl(argv[optind + 1], DIMS, map_dims);

	md_copy_dims(DIMS, max_dims, ksp_dims);
	max_dims[MAPS_DIM] = map_dims[MAPS_DIM];

	md_select_dims(DIMS, ~COIL_FLAG, pat_dims, ksp_dims);
	md_select_dims(DIMS, ~COIL_FLAG, img_dims, max_dims);

	for (int i = 0; i < 4; i++) {	// sizes2[4] may be > 1
		if (ksp_dims[i] != map_dims[i]) {
		
			fprintf(stderr, "Dimensions of kspace and sensitivities do not match!\n");
			exit(1);
		}
	}


	assert(1 == ksp_dims[MAPS_DIM]);

	(use_gpu ? num_init_gpu : num_init)();

	// print options

	if (use_gpu)
		debug_printf(DP_INFO, "GPU reconstruction\n");

	if (map_dims[MAPS_DIM] > 1) 
		debug_printf(DP_INFO, "%ld maps.\nESPIRiT reconstruction.\n", map_dims[MAPS_DIM]);

	if (l1wav)
		debug_printf(DP_INFO, "l1-wavelet regularization\n");

	if (ist)
		debug_printf(DP_INFO, "Use IST\n");

	if (im_truth)
		debug_printf(DP_INFO, "Compare to truth\n");



	// initialize sampling pattern

	complex float* pattern = NULL;
	long pat_dims2[DIMS];

	if (NULL != pat_file) {

		pattern = load_cfl(pat_file, DIMS, pat_dims2);

		// FIXME: check compatibility
	} else {

		pattern = md_alloc(DIMS, pat_dims, CFL_SIZE);
		estimate_pattern(DIMS, ksp_dims, COIL_DIM, pattern, kspace);
	}


	
	// print some statistics

	size_t T = md_calc_size(DIMS, pat_dims);
	long samples = (long)pow(md_znorm(DIMS, pat_dims, pattern), 2.);
	debug_printf(DP_INFO, "Size: %ld Samples: %ld Acc: %.2f\n", T, samples, (float)T / (float)samples); 

	fftmod(DIMS, ksp_dims, FFT_FLAGS, kspace, kspace);
	fftmod(DIMS, map_dims, FFT_FLAGS, maps, maps);


	// apply fov mask to sensitivities

	if (-1. != restrict_fov) {

		float restrict_dims[DIMS] = { [0 ... DIMS - 1] = 1. };
		restrict_dims[0] = restrict_fov;
		restrict_dims[1] = restrict_fov;
		restrict_dims[2] = restrict_fov;

		apply_mask(DIMS, map_dims, maps, restrict_dims);
	}
Beispiel #21
0
int			event_match(t_event elem1, t_event elem2, t_event *mask)
{
	apply_mask((char *)&event1, (char *)mask, sizeof(t_event));
	apply_mask((char *)&event2, (char *)mask, sizeof(t_event));
	return ((ft_memcmp((char *)&elem1, (char *)&elem2, sizeof(t_event)) != 0));
}
Beispiel #22
0
	void *
cli_start_communication(void *context)
{
	char line[2048];
	char *params[100];
	char *token;
	uint32_t rid;
	int i = 0;

	while (fgets(line, sizeof line, stdin) != NULL) {
		line[strlen(line)-1] = '\0';
		token = strtok (line, " ");

		while (token != NULL) {
			params[i++] = token;
			token = strtok (NULL, " ,");
		}

		if (!i)
			continue;

		/* == GET  a mapping */
		/* Map-Request <eid> <nonce> */
		if (strcasecmp("map-request", params[0]) == 0 && i == 3) {
			rid = cli_request_add(params[1], (uint64_t)atoi(params[2]));
			generic_process_request(rid, &cli_fct);
		}
		/* == Stop the CLI */
		/* quit */
		if (strcasecmp("quit", params[0]) == 0) {
			cli_fct.stop_communication(NULL);
			return (NULL);
		}
		/* == Register a new mapping */
		/* example:
		   =======
		   map-register 6.6.6.6/24  version 65 A true TTL 56 -rloc address 127.0.0.1 priority 1 weight 100 m_priority 255 m_priority 0 reachable false -rloc address6 fe80::226:bbff:fe0e:882c priority 2  weight 100 m_priority 255 m_priority 0 reachable true
		   map-register 1.2.3.4/32 ACT 2 TTL 5 A true
		   map-request 6.6.6.6 123567
		   map-request 1.2.3.4 098765
		  */
		/* Map-Register <eid>  */
		if (strcasecmp("map-register", params[0]) == 0) {
			void *_mapping;
			struct prefix p1;
			struct mapping_flags *mflags;
			struct map_entry *entry = NULL;
			int j = 1;

			printf("p1:%s\n", params[j]);
			str2prefix (params[j], &p1);
			apply_mask(&p1);
			_mapping = generic_mapping_new(&p1);
			j++;
			int prev = 0;
			int count = 0;
			void *ptr = NULL;
			mflags = calloc(1, sizeof(struct mapping_flags));


			while (j < i - 1) {
					if (0 == strcasecmp(params[j], "-rloc")) {
					j++;
					if (prev && count > 0) {
						printf("ADD RLOC\n");
						assert(entry != NULL);
						generic_mapping_add_rloc(_mapping, entry);
						prev = 0;
					}
					printf("new rloc\n");
					entry = calloc(1, sizeof(struct map_entry));
					printf("%p\n", entry);
					continue;
				}else if (0 == strcasecmp(params[j], "priority")) {
					entry->priority = atoi(params[j+1]);
				}else if (0 == strcasecmp(params[j], "m_priority")) {
					entry->m_priority = atoi(params[j+1]);
				}else if (0 == strcasecmp(params[j], "weight")) {
					entry->weight = atoi(params[j+1]);
				}else if (0 == strcasecmp(params[j], "m_weight")) {
					entry->m_weight = atoi(params[j+1]);
				}else if (0 == strcasecmp(params[j], "reachable")) {
					entry->r = (strcasecmp(params[j+1], "true")==0);
				}else if (0 == strcasecmp(params[j], "local")) {
					entry->L = (strcasecmp(params[j+1], "true")==0);
				}else if (0 == strcasecmp(params[j], "rloc-probing")) {
					entry->p = (strcasecmp(params[j+1], "true")==0);
				}else if (0 == strcasecmp(params[j], "address")) {
					entry->rloc.sa.sa_family = AF_INET;
					ptr = &(entry->rloc.sin.sin_addr);
				}else if (0 == strcasecmp(params[j], "address6")) {
					entry->rloc.sa.sa_family = AF_INET6;
					ptr = &entry->rloc.sin6.sin6_addr;
				} /* mapping flags*/
				else if (0 == strcasecmp(params[j], "act")) {
					mflags->act = atoi(params[j+1]);
				}else if (0 == strcasecmp(params[j], "a")) {
					mflags->A = (strcasecmp(params[j+1], "true")==0);
				}else if (0 == strcasecmp(params[j], "version")) {
					mflags->version = atoi(params[j+1]);
				}else if (0 == strcasecmp(params[j], "ttl")) {
					mflags->ttl = atoi(params[j+1]);
				}
				/* an RLOC */
				if (ptr) {
					count++;
					inet_pton(entry->rloc.sa.sa_family, params[j+1], ptr);
					ptr = NULL;
				}

				//printf("%s -> %s\n", params[j], params[j+1]);
				j = j+2;
				prev = 1;
			}

			if (prev && count > 0) {
				printf("ADD RLOC\n");
				generic_mapping_add_rloc(_mapping, entry);
				prev = 0;
			}

			generic_mapping_set_flags(_mapping, mflags);
		}

		if (strcasecmp("map-database", params[0]) == 0) {
			assert(ms_db->lisp_db4);
			assert(ms_db->lisp_db6);
			list_db(ms_db->lisp_db4);
			list_db(ms_db->lisp_db6);
		}
		if (strcasecmp("reload", params[0]) == 0) {
			reconfigure();
		}

		if (strcasecmp("help", params[0]) == 0) {
			printf("""\t•map-database\n");
			printf("\t•map-register\n");
			printf("\t\tExample:\n \t\t\t map-register 6.6.6.6/24  version 65 A true TTL 56 \\ \n \t\t\t-rloc address 127.0.0.1 priority 1 weight 100 m_priority 255 m_priority 0 reachable false \\ \n \t\t\t -rloc address6 fe80::226:bbff:fe0e:882c priority 2 weight 100 m_priority 255 m_priority 0 reachable true\n");
			printf("\t•map-request\n");
			printf("\t\ttexample:\n \t\t\tmap-request 6.6.6.6 123567\n");
			printf("\t•reload\n");
		}
	}
	return (NULL);
}
Beispiel #23
0
void
ospf6_interface_connected_route_update (struct interface *ifp)
{
  struct ospf6_interface *oi;
  struct ospf6_route *route;
  struct connected *c;
  struct listnode *node, *nnode;

  oi = (struct ospf6_interface *) ifp->info;
  if (oi == NULL)
    return;

  /* reset linklocal pointer */
  oi->linklocal_addr = ospf6_interface_get_linklocal_address (ifp);

  /* if area is null, do not make connected-route list */
  if (oi->area == NULL)
    return;

  /* update "route to advertise" interface route table */
  ospf6_route_remove_all (oi->route_connected);

  for (ALL_LIST_ELEMENTS (oi->interface->connected, node, nnode, c))
    {
      if (c->address->family != AF_INET6)
        continue;

      CONTINUE_IF_ADDRESS_LINKLOCAL (IS_OSPF6_DEBUG_INTERFACE, c->address);
      CONTINUE_IF_ADDRESS_UNSPECIFIED (IS_OSPF6_DEBUG_INTERFACE, c->address);
      CONTINUE_IF_ADDRESS_LOOPBACK (IS_OSPF6_DEBUG_INTERFACE, c->address);
      CONTINUE_IF_ADDRESS_V4COMPAT (IS_OSPF6_DEBUG_INTERFACE, c->address);
      CONTINUE_IF_ADDRESS_V4MAPPED (IS_OSPF6_DEBUG_INTERFACE, c->address);

      /* apply filter */
      if (oi->plist_name)
        {
          struct prefix_list *plist;
          enum prefix_list_type ret;
          char buf[128];

          prefix2str (c->address, buf, sizeof (buf));
          plist = prefix_list_lookup (AFI_IP6, oi->plist_name);
          ret = prefix_list_apply (plist, (void *) c->address);
          if (ret == PREFIX_DENY)
            {
              if (IS_OSPF6_DEBUG_INTERFACE)
                zlog_debug ("%s on %s filtered by prefix-list %s ",
			    buf, oi->interface->name, oi->plist_name);
              continue;
            }
        }

      route = ospf6_route_create ();
      memcpy (&route->prefix, c->address, sizeof (struct prefix));
      apply_mask (&route->prefix);
      route->type = OSPF6_DEST_TYPE_NETWORK;
      route->path.area_id = oi->area->area_id;
      route->path.type = OSPF6_PATH_TYPE_INTRA;
      route->path.cost = oi->cost;
      route->nexthop[0].ifindex = oi->interface->ifindex;
      inet_pton (AF_INET6, "::1", &route->nexthop[0].address);
      ospf6_route_add (route, oi->route_connected);
    }

  /* create new Link-LSA */
  OSPF6_LINK_LSA_SCHEDULE (oi);
  OSPF6_INTRA_PREFIX_LSA_SCHEDULE_TRANSIT (oi);
  OSPF6_INTRA_PREFIX_LSA_SCHEDULE_STUB (oi->area);
}
Beispiel #24
0
Datei: chmod.c Projekt: BrEacK/mc
void
chmod_cmd (void)
{
    chmod_i18n ();

    do
    {                           /* do while any files remaining */
        vfs_path_t *vpath;
        Dlg_head *ch_dlg;
        struct stat sf_stat;
        char *fname;
        int result;
        unsigned int i;

        do_refresh ();

        mode_change = FALSE;
        need_update = FALSE;
        end_chmod = FALSE;
        c_file = 0;

        if (current_panel->marked != 0)
            fname = next_file ();       /* next marked file */
        else
            fname = selection (current_panel)->fname;   /* single file */

        vpath = vfs_path_from_str (fname);

        if (mc_stat (vpath, &sf_stat) != 0)
        {
            vfs_path_free (vpath);
            break;
        }

        c_stat = sf_stat.st_mode;

        ch_dlg = init_chmod (fname, &sf_stat);

        /* do action */
        result = run_dlg (ch_dlg);

        switch (result)
        {
        case B_ENTER:
            if (mode_change && mc_chmod (vpath, c_stat) == -1)
                message (D_ERROR, MSG_ERROR, _("Cannot chmod \"%s\"\n%s"),
                         fname, unix_error_string (errno));
            need_update = TRUE;
            break;

        case B_CANCEL:
            end_chmod = TRUE;
            break;

        case B_ALL:
        case B_MARKED:
            and_mask = or_mask = 0;
            and_mask = ~and_mask;

            for (i = 0; i < check_perm_num; i++)
                if (check_perm[i].selected || result == B_ALL)
                {
                    if (check_perm[i].check->state & C_BOOL)
                        or_mask |= check_perm[i].mode;
                    else
                        and_mask &= ~check_perm[i].mode;
                }

            apply_mask (&sf_stat);
            break;

        case B_SETMRK:
            and_mask = or_mask = 0;
            and_mask = ~and_mask;

            for (i = 0; i < check_perm_num; i++)
                if (check_perm[i].selected)
                    or_mask |= check_perm[i].mode;

            apply_mask (&sf_stat);
            break;

        case B_CLRMRK:
            and_mask = or_mask = 0;
            and_mask = ~and_mask;

            for (i = 0; i < check_perm_num; i++)
                if (check_perm[i].selected)
                    and_mask &= ~check_perm[i].mode;

            apply_mask (&sf_stat);
            break;
        }

        if (current_panel->marked != 0 && result != B_CANCEL)
        {
            do_file_mark (current_panel, c_file, 0);
            need_update = TRUE;
        }

        vfs_path_free (vpath);

        destroy_dlg (ch_dlg);
    }
    while (current_panel->marked != 0 && !end_chmod);

    chmod_done ();
}
Beispiel #25
0
CPLErr JPEG_Codec::DecompressJPEG(buf_mgr &dst, buf_mgr &isrc)
#endif

{
    int nbands = img.pagesize.c;
    // Locals, clean up after themselves
    jpeg_decompress_struct cinfo;
    MRFJPEGStruct sJPEGStruct;
    struct jpeg_error_mgr sJErr;
    BitMask mask(img.pagesize.x, img.pagesize.y);
    RLEC3Packer packer;
    mask.set_packer(&packer);

    memset(&cinfo, 0, sizeof(cinfo));
    // Pass the mask address to the decompressor
    sJPEGStruct.mask = &mask;

    struct jpeg_source_mgr src;

    cinfo.err = jpeg_std_error( &sJErr );
    sJErr.error_exit = errorExit;
    sJErr.emit_message = emitMessage;
    cinfo.client_data = (void *) &(sJPEGStruct);

    src.next_input_byte = (JOCTET *)isrc.buffer;
    src.bytes_in_buffer = isrc.size;
    src.term_source = stub_source_dec;
    src.init_source = stub_source_dec;
    src.skip_input_data = skip_input_data_dec;
    src.fill_input_buffer = fill_input_buffer_dec;
    src.resync_to_restart = jpeg_resync_to_restart;

    jpeg_create_decompress(&cinfo);

    if (setjmp(sJPEGStruct.setjmpBuffer)) {
        CPLError(CE_Failure, CPLE_AppDefined, "MRF: Error reading JPEG page");
        jpeg_destroy_decompress(&cinfo);
        return CE_Failure;
    }

    cinfo.src = &src;
    jpeg_set_marker_processor(&cinfo, JPEG_APP0 + 3, MaskProcessor);
    jpeg_read_header(&cinfo, TRUE);

    /* In some cases, libjpeg needs to allocate a lot of memory */
    /* http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf */
    if( jpeg_has_multiple_scans(&(cinfo)) )
    {
        /* In this case libjpeg will need to allocate memory or backing */
        /* store for all coefficients */
        /* See call to jinit_d_coef_controller() from master_selection() */
        /* in libjpeg */
        vsi_l_offset nRequiredMemory = 
            static_cast<vsi_l_offset>(cinfo.image_width) *
            cinfo.image_height * cinfo.num_components *
            ((cinfo.data_precision+7)/8);
        /* BLOCK_SMOOTHING_SUPPORTED is generally defined, so we need */
        /* to replicate the logic of jinit_d_coef_controller() */
        if( cinfo.progressive_mode )
            nRequiredMemory *= 3;

#ifndef GDAL_LIBJPEG_LARGEST_MEM_ALLOC
#define GDAL_LIBJPEG_LARGEST_MEM_ALLOC (100 * 1024 * 1024)
#endif

        if( nRequiredMemory > GDAL_LIBJPEG_LARGEST_MEM_ALLOC &&
            CPLGetConfigOption("GDAL_ALLOW_LARGE_LIBJPEG_MEM_ALLOC", nullptr) == nullptr )
        {
                CPLError(CE_Failure, CPLE_NotSupported,
                    "Reading this image would require libjpeg to allocate "
                    "at least " CPL_FRMT_GUIB " bytes. "
                    "This is disabled since above the " CPL_FRMT_GUIB " threshold. "
                    "You may override this restriction by defining the "
                    "GDAL_ALLOW_LARGE_LIBJPEG_MEM_ALLOC environment variable, "
                    "or recompile GDAL by defining the "
                    "GDAL_LIBJPEG_LARGEST_MEM_ALLOC macro to a value greater "
                    "than " CPL_FRMT_GUIB,
                    static_cast<GUIntBig>(nRequiredMemory),
                    static_cast<GUIntBig>(GDAL_LIBJPEG_LARGEST_MEM_ALLOC),
                    static_cast<GUIntBig>(GDAL_LIBJPEG_LARGEST_MEM_ALLOC));
                jpeg_destroy_decompress(&cinfo);
                return CE_Failure;
        }
    }

    // Use float, it is actually faster than the ISLOW method by a tiny bit
    cinfo.dct_method = JDCT_FLOAT;

    //
    // Tolerate different input if we can do the conversion
    // Gray and RGB for example
    // This also means that a RGB MRF can be read as grayscale and vice versa
    // If libJPEG can't convert it will throw an error
    //
    if (nbands == 3 && cinfo.num_components != nbands)
        cinfo.out_color_space = JCS_RGB;
    if (nbands == 1 && cinfo.num_components != nbands)
        cinfo.out_color_space = JCS_GRAYSCALE;

    const int datasize = ((cinfo.data_precision == 8) ? 1 : 2);
    if( cinfo.image_width > static_cast<unsigned>(INT_MAX / (nbands * datasize)) )
    {
        CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG decompress buffer overflow");
        jpeg_destroy_decompress(&cinfo);
        return CE_Failure;
    }
    int linesize = cinfo.image_width * nbands * datasize;

    // We have a mismatch between the real and the declared data format
    // warn and fail if output buffer is too small
    if (linesize > static_cast<int>(INT_MAX / cinfo.image_height)) {
        CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG decompress buffer overflow");
        jpeg_destroy_decompress(&cinfo);
        return CE_Failure;
    }
    if (linesize*cinfo.image_height != dst.size) {
        CPLError(CE_Warning, CPLE_AppDefined, "MRF: read JPEG size is wrong");
        if (linesize*cinfo.image_height > dst.size) {
            CPLError(CE_Failure, CPLE_AppDefined, "MRF: JPEG decompress buffer overflow");
            jpeg_destroy_decompress(&cinfo);
            return CE_Failure;
        }
    }

    struct jpeg_progress_mgr sJProgress;
    sJProgress.progress_monitor = ProgressMonitor;
    cinfo.progress = &sJProgress;

    jpeg_start_decompress(&cinfo);

    // Decompress, two lines at a time is what libjpeg does
    while (cinfo.output_scanline < cinfo.image_height) {
        char *rp[2];
        rp[0] = (char *)dst.buffer + linesize*cinfo.output_scanline;
        rp[1] = rp[0] + linesize;
        // if this fails, it calls the error handler
        // which will report an error
        if( jpeg_read_scanlines(&cinfo, JSAMPARRAY(rp), 2) == 0 )
        {
            jpeg_destroy_decompress(&cinfo);
            return CE_Failure;
        }
    }
    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);

    // Apply the mask
    if (datasize == 1)
      apply_mask(sJPEGStruct, reinterpret_cast<char *>(dst.buffer), img.pagesize.c);
    else
      apply_mask(sJPEGStruct, reinterpret_cast<GUInt16 *>(dst.buffer), img.pagesize.c);

    return CE_None;
}
Beispiel #26
0
int show_line(FILE *stream, struct name_list **acl_names,  acl_t acl,
              acl_entry_t *acl_ent, const char *acl_mask,
              struct name_list **dacl_names, acl_t dacl,
	      acl_entry_t *dacl_ent, const char *dacl_mask)
{
	acl_tag_t tag_type;
	const char *tag, *name;
	char acl_perm[ACL_PERMS+1], dacl_perm[ACL_PERMS+1];

	if (acl) {
		acl_get_tag_type(*acl_ent, &tag_type);
		name = (*acl_names)->name;
	} else {
		acl_get_tag_type(*dacl_ent, &tag_type);
		name = (*dacl_names)->name;
	}

	switch(tag_type) {
		case ACL_USER_OBJ:
			tag = "USER";
			break;
		case ACL_USER:
			tag = "user";
			break;
		case ACL_GROUP_OBJ:
			tag = "GROUP";
			break;
		case ACL_GROUP:
			tag = "group";
			break;
		case ACL_MASK:
			tag = "mask";
			break;
		case ACL_OTHER:
			tag = "other";
			break;
		default:
			return -1;
	}

	memset(acl_perm, ' ', ACL_PERMS);
	acl_perm[ACL_PERMS] = '\0';
	if (acl_ent) {
		acl_perm_str(*acl_ent, acl_perm);
		if (tag_type != ACL_USER_OBJ && tag_type != ACL_OTHER &&
		    tag_type != ACL_MASK)
			apply_mask(acl_perm, acl_mask);
	}
	memset(dacl_perm, ' ', ACL_PERMS);
	dacl_perm[ACL_PERMS] = '\0';
	if (dacl_ent) {
		acl_perm_str(*dacl_ent, dacl_perm);
		if (tag_type != ACL_USER_OBJ && tag_type != ACL_OTHER &&
		    tag_type != ACL_MASK)
			apply_mask(dacl_perm, dacl_mask);
	}

	fprintf(stream, "%-5s  %*s  %*s  %*s\n",
	        tag, -names_width, name,
	        -(int)ACL_PERMS, acl_perm,
		-(int)ACL_PERMS, dacl_perm);

	if (acl_names) {
		acl_get_entry(acl, ACL_NEXT_ENTRY, acl_ent);
		(*acl_names) = (*acl_names)->next;
	}
	if (dacl_names) {
		acl_get_entry(dacl, ACL_NEXT_ENTRY, dacl_ent);
		(*dacl_names) = (*dacl_names)->next;
	}
	return 0;
}
Beispiel #27
0
int main_pics(int argc, char* argv[])
{
	// Initialize default parameters

	struct sense_conf conf = sense_defaults;



	bool use_gpu = false;

	bool randshift = true;
	unsigned int maxiter = 30;
	float step = -1.;

	// Start time count

	double start_time = timestamp();

	// Read input options
	struct nufft_conf_s nuconf = nufft_conf_defaults;
	nuconf.toeplitz = false;

	float restrict_fov = -1.;
	const char* pat_file = NULL;
	const char* traj_file = NULL;
	bool scale_im = false;
	bool eigen = false;
	float scaling = 0.;

	unsigned int llr_blk = 8;

	const char* image_truth_file = NULL;
	bool im_truth = false;

	const char* image_start_file = NULL;
	bool warm_start = false;

	bool hogwild = false;
	bool fast = false;
	float admm_rho = iter_admm_defaults.rho;
	unsigned int admm_maxitercg = iter_admm_defaults.maxitercg;

	struct opt_reg_s ropts;
	ropts.r = 0;
	ropts.algo = CG;
	ropts.lambda = -1.;


	const struct opt_s opts[] = {

		{ 'l', true, opt_reg, &ropts, "1/-l2\t\ttoggle l1-wavelet or l2 regularization." },
		OPT_FLOAT('r', &ropts.lambda, "lambda", "regularization parameter"),
		{ 'R', true, opt_reg, &ropts, " <T>:A:B:C\tgeneralized regularization options (-Rh for help)" },
		OPT_SET('c', &conf.rvc, "real-value constraint"),
		OPT_FLOAT('s', &step, "step", "iteration stepsize"),
		OPT_UINT('i', &maxiter, "iter", "max. number of iterations"),
		OPT_STRING('t', &traj_file, "file", "k-space trajectory"),
		OPT_CLEAR('n', &randshift, "disable random wavelet cycle spinning"),
		OPT_SET('g', &use_gpu, "use GPU"),
		OPT_STRING('p', &pat_file, "file", "pattern or weights"),
		OPT_SELECT('I', enum algo_t, &ropts.algo, IST, "(select IST)"),
		OPT_UINT('b', &llr_blk, "blk", "Lowrank block size"),
		OPT_SET('e', &eigen, "Scale stepsize based on max. eigenvalue"),
		OPT_SET('H', &hogwild, "(hogwild)"),
		OPT_SET('F', &fast, "(fast)"),
		OPT_STRING('T', &image_truth_file, "file", "(truth file)"),
		OPT_STRING('W', &image_start_file, "<img>", "Warm start with <img>"),
		OPT_INT('d', &debug_level, "level", "Debug level"),
		OPT_INT('O', &conf.rwiter, "rwiter", "(reweighting)"),
		OPT_FLOAT('o', &conf.gamma, "gamma", "(reweighting)"),
		OPT_FLOAT('u', &admm_rho, "rho", "ADMM rho"),
		OPT_UINT('C', &admm_maxitercg, "iter", "ADMM max. CG iterations"),
		OPT_FLOAT('q', &conf.cclambda, "cclambda", "(cclambda)"),
		OPT_FLOAT('f', &restrict_fov, "rfov", "restrict FOV"),
		OPT_SELECT('m', enum algo_t, &ropts.algo, ADMM, "Select ADMM"),
		OPT_FLOAT('w', &scaling, "val", "scaling"),
		OPT_SET('S', &scale_im, "Re-scale the image after reconstruction"),
	};

	cmdline(&argc, argv, 3, 3, usage_str, help_str, ARRAY_SIZE(opts), opts);

	if (NULL != image_truth_file)
		im_truth = true;

	if (NULL != image_start_file)
		warm_start = true;


	long max_dims[DIMS];
	long map_dims[DIMS];
	long pat_dims[DIMS];
	long img_dims[DIMS];
	long coilim_dims[DIMS];
	long ksp_dims[DIMS];
	long traj_dims[DIMS];



	// load kspace and maps and get dimensions

	complex float* kspace = load_cfl(argv[1], DIMS, ksp_dims);
	complex float* maps = load_cfl(argv[2], DIMS, map_dims);


	complex float* traj = NULL;

	if (NULL != traj_file)
		traj = load_cfl(traj_file, DIMS, traj_dims);


	md_copy_dims(DIMS, max_dims, ksp_dims);
	md_copy_dims(5, max_dims, map_dims);

	md_select_dims(DIMS, ~COIL_FLAG, img_dims, max_dims);
	md_select_dims(DIMS, ~MAPS_FLAG, coilim_dims, max_dims);

	if (!md_check_compat(DIMS, ~(MD_BIT(MAPS_DIM)|FFT_FLAGS), img_dims, map_dims))
		error("Dimensions of image and sensitivities do not match!\n");

	assert(1 == ksp_dims[MAPS_DIM]);


	(use_gpu ? num_init_gpu : num_init)();

	// print options

	if (use_gpu)
		debug_printf(DP_INFO, "GPU reconstruction\n");

	if (map_dims[MAPS_DIM] > 1) 
		debug_printf(DP_INFO, "%ld maps.\nESPIRiT reconstruction.\n", map_dims[MAPS_DIM]);

	if (hogwild)
		debug_printf(DP_INFO, "Hogwild stepsize\n");

	if (im_truth)
		debug_printf(DP_INFO, "Compare to truth\n");



	// initialize sampling pattern

	complex float* pattern = NULL;

	if (NULL != pat_file) {

		pattern = load_cfl(pat_file, DIMS, pat_dims);

		assert(md_check_compat(DIMS, COIL_FLAG, ksp_dims, pat_dims));

	} else {

		md_select_dims(DIMS, ~COIL_FLAG, pat_dims, ksp_dims);
		pattern = md_alloc(DIMS, pat_dims, CFL_SIZE);
		estimate_pattern(DIMS, ksp_dims, COIL_DIM, pattern, kspace);
	}


	if ((NULL != traj_file) && (NULL == pat_file)) {

		md_free(pattern);
		pattern = NULL;
		nuconf.toeplitz = true;

	} else {

		// print some statistics

		long T = md_calc_size(DIMS, pat_dims);
		long samples = (long)pow(md_znorm(DIMS, pat_dims, pattern), 2.);

		debug_printf(DP_INFO, "Size: %ld Samples: %ld Acc: %.2f\n", T, samples, (float)T / (float)samples);
	}

	if (NULL == traj_file) {

		fftmod(DIMS, ksp_dims, FFT_FLAGS, kspace, kspace);
		fftmod(DIMS, map_dims, FFT_FLAGS, maps, maps);
	}

	// apply fov mask to sensitivities

	if (-1. != restrict_fov) {

		float restrict_dims[DIMS] = { [0 ... DIMS - 1] = 1. };
		restrict_dims[0] = restrict_fov;
		restrict_dims[1] = restrict_fov;
		restrict_dims[2] = restrict_fov;

		apply_mask(DIMS, map_dims, maps, restrict_dims);
	}