Exemple #1
1
int
nsm_adj_ok (struct ospf_neighbor *nbr)
{
  struct ospf_interface *oi;
  int next_state;
  int flag = 0;

  oi = nbr->oi;
  next_state = nbr->state;

  /* These netowork types must be adjacency. */
  if (oi->type == OSPF_IFTYPE_POINTOPOINT
      || oi->type == OSPF_IFTYPE_POINTOMULTIPOINT
      || oi->type == OSPF_IFTYPE_VIRTUALLINK)
    flag = 1;

  /* Router itself is the DRouter or the BDRouter. */
  if (IPV4_ADDR_SAME (&oi->address->u.prefix4, &DR (oi))
      || IPV4_ADDR_SAME (&oi->address->u.prefix4, &BDR (oi)))
    flag = 1;

  if (IPV4_ADDR_SAME (&nbr->address.u.prefix4, &DR (oi))
      || IPV4_ADDR_SAME (&nbr->address.u.prefix4, &BDR (oi)))
    flag = 1;

  if (nbr->state == NSM_TwoWay && flag == 1)
    next_state = NSM_ExStart;
  else if (nbr->state >= NSM_ExStart && flag == 0)
    next_state = NSM_TwoWay;

  return next_state;
}
Exemple #2
0
/*
 * The MX1ADS Board has only one usable LED,
 * so select only the timer led or the
 * cpu usage led
 */
void
mx1ads_leds_event(led_event_t ledevt)
{
	unsigned long flags;

	local_irq_save(flags);

	switch (ledevt) {
#ifdef CONFIG_LEDS_CPU
	case led_idle_start:
		DR(0) &= ~(1<<2);
		break;

	case led_idle_end:
		DR(0) |= 1<<2;
		break;
#endif

#ifdef CONFIG_LEDS_TIMER
	case led_timer:
		DR(0) ^= 1<<2;
#endif
	default:
		break;
	}
	local_irq_restore(flags);
}
int
ospf_dr_election (struct ospf_interface *oi)
{
  struct in_addr old_dr, old_bdr;
  int old_state, new_state;
  struct list *el_list;
  struct ospf_neighbor *dr, *bdr;

  /* backup current values. */
  old_dr = DR (oi);
  old_bdr = BDR (oi);
  old_state = oi->state;

  el_list = list_new ();

  /* List eligible routers. */
  ospf_dr_eligible_routers (oi->nbrs, el_list);

  /* First election of DR and BDR. */
  bdr = ospf_elect_bdr (oi, el_list);
  dr = ospf_elect_dr (oi, el_list);

  new_state = ospf_ism_state (oi);

  zlog_info ("DR-Election[1st]: Backup %s", inet_ntoa (BDR (oi)));
  zlog_info ("DR-Election[1st]: DR     %s", inet_ntoa (DR (oi)));

  if (new_state != old_state &&
      !(new_state == ISM_DROther && old_state < ISM_DROther))
    {
      ospf_elect_bdr (oi, el_list);
      ospf_elect_dr (oi, el_list); 

      new_state = ospf_ism_state (oi);

      zlog_info ("DR-Election[2nd]: Backup %s", inet_ntoa (BDR (oi)));
      zlog_info ("DR-Election[2nd]: DR     %s", inet_ntoa (DR (oi)));
    }

  list_delete (el_list);

  /* if DR or BDR changes, cause AdjOK? neighbor event. */
  if (!IPV4_ADDR_SAME (&old_dr, &DR (oi)) ||
      !IPV4_ADDR_SAME (&old_bdr, &BDR (oi)))
    ospf_dr_change (oi->ospf, oi->nbrs);

  if (oi->type == OSPF_IFTYPE_BROADCAST || oi->type == OSPF_IFTYPE_POINTOPOINT)
    {
      /* Multicast group change. */
      if ((old_state != ISM_DR && old_state != ISM_Backup) &&
	  (new_state == ISM_DR || new_state == ISM_Backup))
	ospf_if_add_alldrouters (oi->ospf, oi->address, oi->ifp->ifindex);
      else if ((old_state == ISM_DR || old_state == ISM_Backup) &&
	       (new_state != ISM_DR && new_state != ISM_Backup))
	ospf_if_drop_alldrouters (oi->ospf, oi->address, oi->ifp->ifindex);
    }

  return new_state;
}
Exemple #4
0
void csb536_cf_reset_pin(unsigned int on)
{
  if (on) {
    dbg("Setting CF RESET High\n");
    DR(3) |= (1 << CSB536_GPIO_RST);
  } else {
    dbg("Setting CF RESET Low\n");
    DR(3) &= ~(1 << CSB536_GPIO_RST);
  }
}
Exemple #5
0
void csb536_cf_power_pin(unsigned int on)
{
  if (on) {
    dbg("Setting CF POWER High\n");
    DR(3) |= (1 << CSB536_GPIO_VEN);
  } else {
    dbg("Setting CF POWER Low\n");
    DR(3) &= ~(1 << CSB536_GPIO_VEN);
  }
}
Exemple #6
0
static int
ospf_dr_election (struct ospf_interface *oi)
{
  struct in_addr old_dr, old_bdr;
  int old_state, new_state;
  struct list *el_list;
  struct ospf_neighbor *dr, *bdr;

  /* backup current values. */
  old_dr = DR (oi);
  old_bdr = BDR (oi);
  old_state = oi->state;

  el_list = list_new ();

  /* List eligible routers. */
  ospf_dr_eligible_routers (oi->nbrs, el_list);

  /* First election of DR and BDR. */
  bdr = ospf_elect_bdr (oi, el_list);
  dr = ospf_elect_dr (oi, el_list);

  new_state = ospf_ism_state (oi);

  zlog_info ("DR-Election[1st]: Backup %s", inet_ntoa (BDR (oi)));
  zlog_info ("DR-Election[1st]: DR     %s", inet_ntoa (DR (oi)));

  if (new_state != old_state &&
      !(new_state == ISM_DROther && old_state < ISM_DROther))
    {
      ospf_elect_bdr (oi, el_list);
      ospf_elect_dr (oi, el_list); 

      new_state = ospf_ism_state (oi);

      zlog_info ("DR-Election[2nd]: Backup %s", inet_ntoa (BDR (oi)));
      zlog_info ("DR-Election[2nd]: DR     %s", inet_ntoa (DR (oi)));
    }

  list_delete (el_list);

  /* if DR or BDR changes, cause AdjOK? neighbor event. */
  if (!IPV4_ADDR_SAME (&old_dr, &DR (oi)) ||
      !IPV4_ADDR_SAME (&old_bdr, &BDR (oi)))
    ospf_dr_change (oi->ospf, oi->nbrs);

  return new_state;
}
Exemple #7
0
int
nsm_twoway_received (struct ospf_neighbor *nbr)
{
  struct ospf_interface *oi;
  int next_state = NSM_TwoWay;

  oi = nbr->oi;

  /* These netowork types must be adjacency. */
  if (oi->type == OSPF_IFTYPE_POINTOPOINT ||
      oi->type == OSPF_IFTYPE_POINTOMULTIPOINT ||
      oi->type == OSPF_IFTYPE_VIRTUALLINK)
    next_state = NSM_ExStart;

  /* Router itself is the DRouter or the BDRouter. */
  if (IPV4_ADDR_SAME (&oi->address->u.prefix4, &DR (oi)) ||
      IPV4_ADDR_SAME (&oi->address->u.prefix4, &BDR (oi)))
    next_state = NSM_ExStart;

  /* Neighboring Router is the DRouter or the BDRouter. */
  if (IPV4_ADDR_SAME (&nbr->address.u.prefix4, &nbr->d_router) ||
      IPV4_ADDR_SAME (&nbr->address.u.prefix4, &nbr->bd_router))
    next_state = NSM_ExStart;

  return next_state;
}
Exemple #8
0
static int ospf_ism_state(struct ospf_interface *oi)
{
	if (IPV4_ADDR_SAME(&DR(oi), &oi->address->u.prefix4))
		return ISM_DR;
	else if (IPV4_ADDR_SAME(&BDR(oi), &oi->address->u.prefix4))
		return ISM_Backup;
	else
		return ISM_DROther;
}
Exemple #9
0
/* 10.4 of RFC2328, indicate whether an adjacency is appropriate with
 * the given neighbour
 */
static int
nsm_should_adj (struct ospf_neighbor *nbr)
{
  struct ospf_interface *oi = nbr->oi;

      /* These network types must always form adjacencies. */
  if (oi->type == OSPF_IFTYPE_POINTOPOINT
      || oi->type == OSPF_IFTYPE_POINTOMULTIPOINT
      || oi->type == OSPF_IFTYPE_VIRTUALLINK
      /* Router itself is the DRouter or the BDRouter. */
      || IPV4_ADDR_SAME (&oi->address->u.prefix4, &DR (oi))
      || IPV4_ADDR_SAME (&oi->address->u.prefix4, &BDR (oi))
      /* Neighboring Router is the DRouter or the BDRouter. */
      || IPV4_ADDR_SAME (&nbr->address.u.prefix4, &DR (oi))
      || IPV4_ADDR_SAME (&nbr->address.u.prefix4, &BDR (oi)))
    return 1;

  return 0;
}
void GLogicProcessor::renderDictSearchSanskrit(map<vector<int>,ulong>&searchResult,
                                          vector<OCRMatch>&dLine,
                                          GBitmap *lineImg32,
                                          GBitmap* letterAImg,
                                          GBitmap* letterBImg){
    
    int print=0;
    
    //проверяем ответы словаря на максимальную корреляцию, выбираем наилучшие гипотезы
    sort(dLine.begin(),dLine.end(),sortMatchW);
    //drawGrapeLine(dLine); exit(0);
    
    
    for(int n=0;n<dLine.size();n++){
        if(!dLine[n].correlation)continue;
        dLine[n].line.push_back(n);
        dLine[n].dIndex.push_back(2);
    }
    
    testStackLetterNew(dLine,dLine,lineImg32,letterAImg,letterBImg);
    //drawGrapeLine(dLine); exit(0);
    
    print=0;
    //убираем фразы и буквы внутри стыкованной фразы
    sort(dLine.begin(),dLine.end(),sortMatchX0);
    
    int limit;
    for(int n=0;n<dLine.size();n++){
        if(!dLine[n].correlation)continue;
        if(dLine[n].OCRIndex=='Z')continue;
        
        //print=0;if(n==13)print=1; if(!print)continue;
        DR("@@@@"<<n<<" Collect n="<<dLine[n].name<<" d="<<dLine[n].delimeter<<endl)
        
        for(int m=0;m<dLine.size();m++){
            if(!dLine[m].correlation)continue;
            if(dLine[m].OCRIndex=='Z')continue;
            //print=0;if(m==16)print=1;
            if(m==n)continue;
            if(dLine[m].xCenter>dLine[n].x0&&dLine[m].xCenter<dLine[n].x1){
                DR("n"<<n<<"="<<dLine[n].name<<" d="<<dLine[n].delimeter<<" c="<<dLine[n].correlation<<" m"<<m<<"="<<dLine[m].name
                   <<" c="<<dLine[m].correlation<<" xmC="<<dLine[m].xCenter<<" xnC="<<dLine[n].xCenter<<" xnX0="<<dLine[n].x0<<" xnX1="<<dLine[n].x1<<" wM="<<dLine[m].letterW<<" wN="<<dLine[n].letterW<<endl);
                
                if(dLine[n].letterW>dLine[m].letterW){
                    dLine[m].correlation=0;
                }else{
                    dLine[n].correlation=0;
                            break;
                }
            }
        }
    }

    
}//-------------------------------------------------------------------------------------------------------------
static uint32_t pipe_dev_read(void *opaque, target_phys_addr_t offset)
{
    PipeDevice *dev = (PipeDevice *)opaque;

    switch (offset) {
    case PIPE_REG_STATUS:
        DR("%s: REG_STATUS status=%d (0x%x)", __FUNCTION__, dev->status, dev->status);
        return dev->status;

    case PIPE_REG_CHANNEL:
        if (dev->signaled_pipes != NULL) {
            Pipe* pipe = dev->signaled_pipes;
            DR("%s: channel=0x%x wanted=%d", __FUNCTION__,
               pipe->channel, pipe->wanted);
            dev->wakes = pipe->wanted;
            pipe->wanted = 0;
            dev->signaled_pipes = pipe->next_waked;
            pipe->next_waked = NULL;
            if (dev->signaled_pipes == NULL) {
                goldfish_device_set_irq(&dev->dev, 0, 0);
                DD("%s: lowering IRQ", __FUNCTION__);
            }
            return pipe->channel;
        }
        DR("%s: no signaled channels", __FUNCTION__);
        return 0;

    case PIPE_REG_WAKES:
        DR("%s: wakes %d", __FUNCTION__, dev->wakes);
        return dev->wakes;

    case PIPE_REG_PARAMS_ADDR_HIGH:
        return dev->params_addr >> 32;

    case PIPE_REG_PARAMS_ADDR_LOW:
        return dev->params_addr & 0xFFFFFFFFUL;

    default:
        D("%s: offset=%d (0x%x)\n", __FUNCTION__, offset, offset);
    }
    return 0;
}
Exemple #12
0
struct ospf_neighbor *
ospf_elect_dr (struct ospf_interface *oi, struct list *el_list)
{
  struct list *dr_list;
  struct listnode *node;
  struct ospf_neighbor *nbr, *dr = NULL, *bdr = NULL;

  dr_list = list_new ();

  /* Add neighbors to the list. */
  for (node = listhead (el_list); node; nextnode (node))
    {
      nbr = getdata (node);

      /* neighbor declared to be DR. */
      if (NBR_IS_DR (nbr))
	listnode_add (dr_list, nbr);

      /* Preserve neighbor BDR. */
      if (IPV4_ADDR_SAME (&BDR (oi), &nbr->address.u.prefix4))
	bdr = nbr;
    }

  /* Elect Designated Router. */
  if (listcount (dr_list) > 0)
    dr = ospf_dr_election_sub (dr_list);
  else
    dr = bdr;

  /* Set DR to interface. */
  if (dr)
    {
      DR (oi) = dr->address.u.prefix4;
      dr->d_router = dr->address.u.prefix4;
    }
  else
      DR (oi).s_addr = 0;

  list_delete (dr_list);

  return dr;
}
Exemple #13
0
void ospf_nbr_state_message(struct ospf_neighbor *nbr, char *buf, size_t size)
{
	int state;
	struct ospf_interface *oi = nbr->oi;

	if (IPV4_ADDR_SAME(&DR(oi), &nbr->address.u.prefix4))
		state = ISM_DR;
	else if (IPV4_ADDR_SAME(&BDR(oi), &nbr->address.u.prefix4))
		state = ISM_Backup;
	else
		state = ISM_DROther;

	snprintf(buf, size, "%s/%s",
		 lookup_msg(ospf_nsm_state_msg, nbr->state, NULL),
		 lookup_msg(ospf_ism_state_msg, state, NULL));
}
void dump_hex(const void* data, size_t byte_count) {
    byte_count = std::min(byte_count, size_t(16));

    const uint8_t* p = reinterpret_cast<const uint8_t*>(data);

    std::string line;
    for (size_t i = 0; i < byte_count; ++i) {
        android::base::StringAppendF(&line, "%02x", p[i]);
    }
    line.push_back(' ');

    for (size_t i = 0; i < byte_count; ++i) {
        int c = p[i];
        if (c < 32 || c > 127) {
            c = '.';
        }
        line.push_back(c);
    }

    DR("%s\n", line.c_str());
}
Exemple #15
0
static void  dump_hex( const unsigned char*  ptr, size_t  len )
{
    int  nn, len2 = len;
    // Build a string instead of logging each character.
    // MAX chars in 2 digit hex, one space, MAX chars, one '\0'.
    char buffer[MAX_DUMP_HEX_LEN *2 + 1 + MAX_DUMP_HEX_LEN + 1 ], *pb = buffer;

    if (len2 > MAX_DUMP_HEX_LEN) len2 = MAX_DUMP_HEX_LEN;

    for (nn = 0; nn < len2; nn++) {
        sprintf(pb, "%02x", ptr[nn]);
        pb += 2;
    }
    sprintf(pb++, " ");

    for (nn = 0; nn < len2; nn++) {
        int  c = ptr[nn];
        if (c < 32 || c > 127)
            c = '.';
        *pb++ =  c;
    }
    *pb++ = '\0';
    DR("%s\n", buffer);
}
Exemple #16
0
void Trr2kNNNT
( UpperOrLower uplo,
  Orientation orientationOfD,
  T alpha, const DistMatrix<T>& A, const DistMatrix<T>& B,
           const DistMatrix<T>& C, const DistMatrix<T>& D,
  T beta,        DistMatrix<T>& E )
{
#ifndef RELEASE
    PushCallStack("internal::Trr2kNNNT");
    if( E.Height() != E.Width()  || A.Width()  != C.Width()  ||
        A.Height() != E.Height() || C.Height() != E.Height() ||
        B.Width()  != E.Width()  || D.Height() != E.Width()  ||
        A.Width()  != B.Height() || C.Width()  != D.Width() )
        throw std::logic_error("Nonconformal Trr2kNNNT");
#endif
    const Grid& g = E.Grid();

    DistMatrix<T> AL(g), AR(g),
                  A0(g), A1(g), A2(g);
    DistMatrix<T> BT(g),  B0(g),
                  BB(g),  B1(g),
                          B2(g);

    DistMatrix<T> CL(g), CR(g),
                  C0(g), C1(g), C2(g);
    DistMatrix<T> DL(g), DR(g),
                  D0(g), D1(g), D2(g);

    DistMatrix<T,MC,  STAR> A1_MC_STAR(g);
    DistMatrix<T,MR,  STAR> B1Trans_MR_STAR(g);
    DistMatrix<T,MC,  STAR> C1_MC_STAR(g);
    DistMatrix<T,VR,  STAR> D1_VR_STAR(g);
    DistMatrix<T,STAR,MR  > D1AdjOrTrans_STAR_MR(g);

    A1_MC_STAR.AlignWith( E );
    B1Trans_MR_STAR.AlignWith( E );
    C1_MC_STAR.AlignWith( E );
    D1_VR_STAR.AlignWith( E );
    D1AdjOrTrans_STAR_MR.AlignWith( E );

    LockedPartitionRight( A, AL, AR, 0 );
    LockedPartitionDown
    ( B, BT,
         BB, 0 );
    LockedPartitionRight( C, CL, CR, 0 );
    LockedPartitionRight( D, DL, DR, 0 );
    while( AL.Width() < A.Width() )
    {
        LockedRepartitionRight
        ( AL, /**/ AR,
          A0, /**/ A1, A2 );
        LockedRepartitionDown
        ( BT,  B0,
         /**/ /**/
               B1,
          BB,  B2 );
        LockedRepartitionRight
        ( CL, /**/ CR,
          C0, /**/ C1, C2 );
        LockedRepartitionRight
        ( CL, /**/ CR,
          C0, /**/ C1, C2 );

        //--------------------------------------------------------------------//
        A1_MC_STAR = A1;
        C1_MC_STAR = C1;
        B1Trans_MR_STAR.TransposeFrom( B1 );
        D1_VR_STAR = D1;
        if( orientationOfD == ADJOINT )
            D1AdjOrTrans_STAR_MR.AdjointFrom( D1_VR_STAR );
        else
            D1AdjOrTrans_STAR_MR.TransposeFrom( D1_VR_STAR );
        LocalTrr2k
        ( uplo, TRANSPOSE, 
          alpha, A1_MC_STAR, B1Trans_MR_STAR, 
                 C1_MC_STAR, D1AdjOrTrans_STAR_MR,
          beta,  E );
        //--------------------------------------------------------------------//

        SlideLockedPartitionRight
        ( DL,     /**/ DR,
          D0, D1, /**/ D2 );
        SlideLockedPartitionRight
        ( CL,     /**/ CR,
          C0, C1, /**/ C2 );
        SlideLockedPartitionDown
        ( BT,  B0,
               B1,
         /**/ /**/
          BB,  B2 );
        SlideLockedPartitionRight
        ( AL,     /**/ AR,
          A0, A1, /**/ A2 );
    }
#ifndef RELEASE
    PopCallStack();
#endif
}
void CODE50(char far *COM)
{static char RR;
 static char RX;
 static int R1,R2,B2,IS;


 static char BD;
 static char DD;
 static unsigned int DDD;

 static long *RR1;
 static long *RR2;
 static long *REZ;
 static long RREZ;
 static unsigned long URREZ;
 static unsigned long URREZ_AL;
 static unsigned long URREZ_WORK;
 static unsigned long URREZ2;
 static unsigned long URREZ3;
 static unsigned int FLA;
 static unsigned long uRREZ;

 static unsigned long *URR1;
 static unsigned long *URR2;
 static unsigned long ADRESS;
	static long double F_W1;
 static long double F_W2;
 static long double F_W3;
 static long double F_W4;
 static unsigned long R_1;
 static unsigned long R_2;
 static unsigned long DEL_DEL;
 static int psw_cc;
#define B1 B2
#define I2 RX
#define X2 R2


 GET_OPERAND_RX;
 FORWARD_PSW;
 /*FORW_PSW();*/
 switch(COM[0])
	 {
		case 0x50:
//							if (ADRESs&0x3)
//							 {RQ_PRG=6;
//								RETURN=1;
//								break;
//							 }
//              Chk_adrw;
//							PUT_WORD(ADRESS,R[R1]);                  /* ST */
				T();
				break;
		case 0x51:
				T00(COM[0]);
				break;
		case 0x52:
				T00(COM[0]);
				break;
		case 0x53:
				T00(COM[0]);
				break;
		case 0x54:
				// if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;
				//URR1=&R[R1];URREZ=GET_WORD(ADRESS);       /* N  */
				//*(URR1)=*(URR1)&URREZ;
				//R[R1]&=GET_WORD(ADRESS);
#ifdef DTA_370
				URREZ=GET_WORD(ADRESS);
				Dtaret;
				if ((R[R1]&=URREZ)==0) PSW_CC=0;
				else PSW_CC=1;
#else
				if ((R[R1]&=GET_WORD(ADRESS))==0) PSW_CC=0;
				else PSW_CC=1;
#endif
				//T();
				break;
		case 0x55:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;
				URR1=&R[R1];URREZ=GET_WORD(ADRESS);        /*  CL */
				Dtaret;
				URR2=&URREZ;
				if (*(URR1)==*(URR2)) PSW_CC=0;
				else if (*(URR1) < *(URR2)) PSW_CC=1;
						 else PSW_CC=2;
				//T();
				break;
		case 0x56:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;
				URREZ=GET_WORD(ADRESS);       /* O */
				Dtaret;
				if ((R[R1]|=URREZ)==0) PSW_CC=0;
				else PSW_CC=1;
				//T();
				break;
		case 0x57:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;
				URREZ=GET_WORD(ADRESS);       /* X */
				Dtaret;
				if ((R[R1]^=URREZ)==0) PSW_CC=0;
				else PSW_CC=1;
				//T();
				break;
		case 0x58:
				if (ADRESs&0x3)
//							 {RQ_PRG=6;
//								RETURN=1;
//								break;
//							 }
//
//        Chk_adrw;
//#ifdef DTA_370
//				URREZ=GET_WORD(ADRESS);
//				Dtaret;
//				R[R1]=URREZ;
//				break;            /* L */
//#else
//				R[R1]=GET_WORD(ADRESS);break;            /* L */
//#endif
				T();
		case 0x59:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;
				RREZ=GET_WORD(ADRESS);        /* C */
				Dtaret;
				if (((signed long)(R[R1]))==RREZ) PSW_CC=0;
				///else
				///	{FLA=_FLAGS;
				///	 if (FLA&0x0080) /*<0*/   PSW_CC=1;
				///	 else            /*>0*/   PSW_CC=2;
				///	}
				else if (((signed long)(R[R1]))<RREZ) PSW_CC=1;
						 else PSW_CC=2;
				break;
		case 0x5a:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;
				RR1=&R[R1];

        RREZ=GET_WORD(ADRESS);        /* A */
//        if (TraceOutCmd)
//        {
//         fprintf(TraceOutCmd,"REG =%lx ADR=%lx VAl =%lx ",*RR1,ADRESS,RREZ);
//        }
				Dtaret;
				*(RR1)+=RREZ;
#include "ds360sr.c"
				//T();
				break;
		case 0x5b:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;
				RR1=&R[R1];RREZ=GET_WORD(ADRESS);        /* S */
				Dtaret;
				*(RR1)+= -RREZ;
#include "ds360sr.c"
				//T();
				break;
		case 0x5c:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }																							 /* M */
				Chk_adrw;
				R1&=0xfe;
				uRREZ=GET_WORD(ADRESS);
				Dtaret;
				MR(&R[R1],&R[R1+1],&uRREZ);
				//T();
				break;
		case 0x5d:                                           /* D */
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;
				R1&=0xfe;
				DEL_DEL=GET_WORD(ADRESS);
				Dtaret;
				DR(&R[R1],&R[R1+1],&DEL_DEL);
				//T();


				break;
		case 0x5e:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
				Chk_adrw;																	/* AL */
#ifdef DTA_370
				RREZ=(signed long)GET_WORD(ADRESS);
				Dtaret;
				((signed long)R[R1])+=RREZ;
#else
				((signed long)R[R1])+=(signed long)GET_WORD(ADRESS);
#endif
#include "DS360ALR.C"
				//T();
				break;
		case 0x5f:
				//if (ADRESs&0x3)
				//			 {RQ_PRG=6;
				//				RETURN=1;
				//				break;
				//			 }
																				/* SL */
			 Chk_adrw;
#ifdef DTA_370
				RREZ=(signed long)GET_WORD(ADRESS);
				Dtaret;
				((signed long)R[R1])+=(-RREZ);
#else

				((signed long)R[R1])+=(-(signed long)GET_WORD(ADRESS));
#endif

#include "DS360ALR.C"
				//T();
				break;

	 }
}
Exemple #18
0
/// normalisation the strArray   //In GBitset y coordinate start from bottom of image  :)
void GBitset::stringNormalisation(){
	int print=0;
	int iTop=0,iLeft=0; //for page layout coordinate
    
	for (int index=0;index<strArray[0].size(); index++){
		DR("//1_strArray[0]["<<index<<"].LimY0="<<strArray[0][index].LimY0-border<<" LimY1="<<strArray[0][index].LimY1-border<<" border="<<border
           <<" y0="<<strArray[0][index].y0-border<<" y1="<<strArray[0][index].y1-border<<END);
			int y0=nrows-strArray[0][index].LimY0-border;
			int y1=nrows-strArray[0][index].LimY1-border;
			DR("//1_LimY0="<<y0<<" LimY1="<<y1<<" nrows="<<nrows<<" border="<<border<<END);
			if(y0<0||y0>nrows)y0=0;
				if(y1<0||y1>nrows)y1=nrows;
					strArray[0][index].LimY0=y0;
					strArray[0][index].LimY1=y1;
					
					y0=nrows-strArray[0][index].y1-border;
					y1=nrows-strArray[0][index].y0-border;
					if(y0<0||y0>nrows)y0=0; if(y1<0||y1>nrows)y1=nrows;
						strArray[0][index].y0=y0;
						strArray[0][index].y1=y1;
						strArray[0][index].selectFlag=0;
						
						/*if(draw){
							//DT("//1_y0="<<y0<<" y1="<<y1<<" nrows="<<nrows<<" border="<<border<<END);
							cout<<"sttIn="<<index<<" y0_="<<inputData.y0<<" y1_="<<inputData.y1;
							DT(" LimY0="<<strArray[0][index].LimY0<<
							   " LimY1="<<strArray[0][index].LimY1<<" y0="<< strArray[0][index].y0<<" y1="<<strArray[0][index].y1<<END);
							if(strArray[0][index].LimY0<inputData.y0&&strArray[0][index].LimY1>inputData.y1){
								strArray[0][index].selectFlag=3;
								cout<<"find string "<<index<<END;
							}
							}
						*/
						 DR("//2_Y0="<<y0<<" Y1="<<y1<<" nrows="<<nrows<<" border="<<border<<END);
							
							for (int i=0;i<strArray[0][index].wordArray.size(); i++){  //word by word
								//if(strArray[0][index].wordArray[i].w){letterW+=strArray[0][index].wordArray[i].w;
								//	letterH+=strArray[0][index].wordArray[i].h;
								//	baseCount++;
								//}
								//if(mode==ALL_LETTER){
								    strArray[0][index].wordArray[i].y0=nrows-strArray[0][index].wordArray[i].y0+iTop-border;   
									strArray[0][index].wordArray[i].y1=nrows-strArray[0][index].wordArray[i].y1+iTop-border;
									int y0_=strArray[0][index].wordArray[i].y1;
								    strArray[0][index].wordArray[i].y1=strArray[0][index].wordArray[i].y0;
								    strArray[0][index].wordArray[i].y0=y0_;   //y0=y1 (important)
									strArray[0][index].wordArray[i].center.y=nrows-strArray[0][index].wordArray[i].center.y+iTop-border;
									strArray[0][index].wordArray[i].h=strArray[0][index].wordArray[i].y0-strArray[0][index].wordArray[i].y1;
									strArray[0][index].wordArray[i].x0=strArray[0][index].wordArray[i].x0+iLeft-border;
									strArray[0][index].wordArray[i].x1=strArray[0][index].wordArray[i].x1+iLeft-border;
									strArray[0][index].wordArray[i].w=strArray[0][index].wordArray[i].x1-strArray[0][index].wordArray[i].x0;
									strArray[0][index].wordArray[i].center.x=strArray[0][index].wordArray[i].center.x+iLeft-border;
									strArray[0][index].wordArray[i].blockIndex=-1;
									strArray[0][index].wordArray[i].yp0=nrows-strArray[0][index].wordArray[i].yp0+iTop-border;
									strArray[0][index].wordArray[i].yp1=nrows-strArray[0][index].wordArray[i].yp1+iTop-border;
									strArray[0][index].wordArray[i].xp0=strArray[0][index].wordArray[i].xp0+iLeft-border;
									strArray[0][index].wordArray[i].xp1=strArray[0][index].wordArray[i].xp1+iLeft-border;
									strArray[0][index].wordArray[i].name="*";
									strArray[0][index].wordArray[i].id=-1;
									
									
									/*if(draw){
										//cout<<"sttIn="<<i<<" y0="<<inData->y0<<" y1="<<inData->y1<<" x1="<<inData->x1<<" y1="<<inData->y1<<" c.x="<<strArray[0][index].wordArray[i].center.x<<" c.y="<<strArray[0][index].wordArray[i].center.y<<END;
										if(strArray[0][index].wordArray[i].center.x>inputData.x0&&
										   strArray[0][index].wordArray[i].center.x<inputData.x1&&
										   strArray[0][index].wordArray[i].center.y>inputData.y0&&
										   strArray[0][index].wordArray[i].center.y<inputData.y1){
											strArray[0][index].wordArray[i].selectFlag=3;
										}
										
									}
									*/
									//DT("strArray[0]["<<index<<"].wordArray["<<i<<"].x0="<<strArray[0][index].wordArray[i].x0<<END);
									//DT("strArray[0]["<<index<<"].wordArray["<<i<<"].y0="<<strArray[0][index].wordArray[i].y0<<END);
									//DT("strArray[0]["<<index<<"].wordArray["<<i<<"].center.x="<<strArray[0][index].wordArray[i].center.x<<END);
									//DT("strArray[0]["<<index<<"].wordArray["<<i<<"].center.y="<<strArray[0][index].wordArray[i].center.y<<END);
									//DT("strArray[0]["<<index<<"].wordArray["<<i<<"].x0="<<strArray[0][index].wordArray[i].xp0<<END);
									//DT("strArray[0]["<<index<<"].wordArray["<<i<<"].y0="<<strArray[0][index].wordArray[i].yp0<<END);
									//DT("strArray[0]["<<index<<"].wordArray["<<i<<"].center.x="<<strArray[0][index].wordArray[i].center.x<<END);
									//DT("strArray[0]["<<index<<"].wordArray["<<i<<"].center.y="<<strArray[0][index].wordArray[i].center.y<<END);
								//}
								
								
							//}
							}
							
							
							//DT("//2_strArray[0]["<<index<<"].LimY0="<<strArray[0][index].LimY0<<" LimY1="<<strArray[0][index].LimY1<<END);
							
			}
    
    // Алгоритм обработки высоты строк
    
    // Задача:
    // разбиение строк текста на группы с одинаковой высотой и усреднение высот строк внутри группы.
    // Можно применять итерационно, несколько раз.
    
    int DeltaHStr=2;	// допуск высоты строки м.б. задан в pix или в %
    int NStrok=(int)strArray[0].size(); 		// количество строк в печа
    int m,n;		// переменные
    int p;			// переменная количества строк в группе
    int HStr; 		// переменная высоты строки
    
    // массив исходной высоты строк.
    vector<int>HStrIn; HStrIn.resize(strArray[0].size());
    //заполняем исходный массив
    for ( n=0; n < NStrok; n++ ){
        HStrIn[n]=strArray[0][n].y1-strArray[0][n].y0;  //cout<<HStrIn[n]<<" ";
    }
    //int HStrIn[16] = {0};
    // выходной массив усредненной высоты строк.
    vector<int>HStrOut;   HStrOut.resize(strArray[0].size());

    
    // проверка допуска высоты строки
    if(DeltaHStr<1) DeltaHStr=0;  if(DeltaHStr>16) DeltaHStr=16;
    
    // В двойном цикле сравниваем высоту каждой строки с высотой каждой строки в пределах
    // допуска и усредняем высоты тех строк, которые попали в допуск (каждая строка формирует
    // свою личную группу). Полученное среднее каждой строки - это и есть новая усредненная
    // высота строки.
    
    // цикл перебора строк
    //p=1;
    for ( n=0; n < NStrok; n++ ){
        HStr=0; p=0;
        // цикл сборки групп строк
        for ( m=0; m < NStrok; m++ ){
            // проверка допуска высоты строки
            if((HStrIn[m]<=HStrIn[n]+DeltaHStr) && (HStrIn[m]>=HStrIn[n]-DeltaHStr))
                // подсчет количества строк попавших в допуск
            {HStr=HStr+HStrIn[m];  p++;}
        } // for m
        // усреднение высоты строки
        if(p!=0) HStrOut[n]=HStr/p;
		///cout<<p<<" ";
    } // for n
    ///cout<<endl;
    
    // в выходном массив HStrOut[n] записана новая усредненная высота строки.    
    // записываем значение высоты строки в strArray
        for ( n=0; n < NStrok; n++ ){
           strArray[0][n].y1=strArray[0][n].y0+HStrOut[n];  //cout<<HStrOut[n]<<" ";
        }
        //exit(0);
}//_____________________________________________________________________________
Exemple #19
0
/** @brief Rodrigues' formula
 **
 ** @param R_pt  3x3 matrix - array of 9 double (in) .
 ** @param dR_pt 9x3 matrix - array of 27 double (in).
 ** @param om_pt 3   vector - array of 3 dobule (out).
 **/
VL_EXPORT
void
vl_rodrigues(double* R_pt, double* dR_pt, const double* om_pt)
{
  /*
    Let

       th = |om|,  r=w/th,
       sth=sin(th),  cth=cos(th),
       ^om = hat(om)

    Then the rodrigues formula is an expansion of the exponential
    function:

     rodrigues(om) = exp ^om = I + ^r sth + ^r^2 (1 - cth).

    The derivative can be computed by elementary means and
    results:

    d(vec rodrigues(om))    sth  d ^r    1 - cth  d (^r)^2
    -------------------- =  ---- ----- + -------  -------- +
          d om^T             th  d r^T     th      d r^T

                          sth                     1 - cth
          + vec^r (cth - -----) + vec^r^2 (sth - 2-------)r^T
                          th                         th
  */

#define OM(i)   om_pt[(i)]
#define R(i,j)  R_pt[(i)+3*(j)]
#define DR(i,j) dR_pt[(i)+9*(j)]
#undef small

  const double small = 1e-6 ;

  double th = sqrt( OM(0)*OM(0) +
                    OM(1)*OM(1) +
                    OM(2)*OM(2) ) ;

  if( th < small ) {
    R(0,0) = 1.0 ; R(0,1) = 0.0 ; R(0,2) = 0.0 ;
    R(1,0) = 0.0 ; R(1,1) = 1.0 ; R(1,2) = 0.0 ;
    R(2,0) = 0.0 ; R(2,1) = 0.0 ; R(2,2) = 1.0 ;

    if(dR_pt) {
      DR(0,0) = 0  ; DR(0,1) = 0   ; DR(0,2) = 0 ;
      DR(1,0) = 0  ; DR(1,1) = 0   ; DR(1,2) = 1 ;
      DR(2,0) = 0  ; DR(2,1) = -1  ; DR(2,2) = 0 ;

      DR(3,0) = 0  ; DR(3,1) = 0   ; DR(3,2) = -1 ;
      DR(4,0) = 0  ; DR(4,1) = 0   ; DR(4,2) = 0 ;
      DR(5,0) = 1  ; DR(5,1) = 0   ; DR(5,2) = 0 ;

      DR(6,0) = 0  ; DR(6,1) = 1   ; DR(6,2) = 0 ;
      DR(7,0) = -1 ; DR(7,1) = 0   ; DR(7,2) = 0 ;
      DR(8,0) = 0  ; DR(8,1) = 0   ; DR(8,2) = 0 ;
    }
    return ;
  }

  {
    double x = OM(0) / th ;
    double y = OM(1) / th ;
    double z = OM(2) / th ;

    double xx = x*x ;
    double xy = x*y ;
    double xz = x*z ;
    double yy = y*y ;
    double yz = y*z ;
    double zz = z*z ;

    const double yx = xy ;
    const double zx = xz ;
    const double zy = yz ;

    double sth  = sin(th) ;
    double cth  = cos(th) ;
    double mcth = 1.0 - cth ;

    R(0,0) = 1          - mcth * (yy+zz) ;
    R(1,0) =     sth*z  + mcth * xy ;
    R(2,0) =   - sth*y  + mcth * xz ;

    R(0,1) =   - sth*z  + mcth * yx ;
    R(1,1) = 1          - mcth * (zz+xx) ;
    R(2,1) =     sth*x  + mcth * yz ;

    R(0,2) =     sth*y  + mcth * xz ;
    R(1,2) =   - sth*x  + mcth * yz ;
    R(2,2) = 1          - mcth * (xx+yy) ;

    if(dR_pt) {
      double a =  sth / th ;
      double b = mcth / th ;
      double c = cth - a ;
      double d = sth - 2*b ;

      DR(0,0) =                         - d * (yy+zz) * x ;
      DR(1,0) =        b*y   + c * zx   + d * xy      * x ;
      DR(2,0) =        b*z   - c * yx   + d * xz      * x ;

      DR(3,0) =        b*y   - c * zx   + d * xy      * x ;
      DR(4,0) =     -2*b*x              - d * (zz+xx) * x ;
      DR(5,0) =  a           + c * xx   + d * yz      * x ;

      DR(6,0) =        b*z   + c * yx   + d * zx      * x ;
      DR(7,0) = -a           - c * xx   + d * zy      * x ;
      DR(8,0) =     -2*b*x              - d * (yy+xx) * x ;

      DR(0,1) =     -2*b*y              - d * (yy+zz) * y ;
      DR(1,1) =        b*x   + c * zy   + d * xy      * y ;
      DR(2,1) = -a           - c * yy   + d * xz      * y ;

      DR(3,1) =        b*x   - c * zy   + d * xy      * y ;
      DR(4,1) =                         - d * (zz+xx) * y ;
      DR(5,1) =        b*z   + c * xy   + d * yz      * y ;

      DR(6,1) = a            + c * yy   + d * zx      * y ;
      DR(7,1) =        b*z   - c * xy   + d * zy      * y ;
      DR(8,1) =     -2*b*y              - d * (yy+xx) * y ;

      DR(0,2) =     -2*b*z              - d * (yy+zz) * z ;
      DR(1,2) =  a           + c * zz   + d * xy      * z ;
      DR(2,2) =        b*x   - c * yz   + d * xz      * z ;

      DR(3,2) =  -a          - c * zz   + d * xy      * z ;
      DR(4,2) =     -2*b*z              - d * (zz+xx) * z ;
      DR(5,2) =        b*y   + c * xz   + d * yz      * z ;

      DR(6,2) =        b*x   + c * yz   + d * zx      * z ;
      DR(7,2) =        b*y   - c * xz   + d * zy      * z ;
      DR(8,2) =                         - d * (yy+xx) * z ;
    }
  }

#undef OM
#undef R
#undef DR

}
Exemple #20
0
void GLogicProcessor::buildOpenType(vector<OCRMatch>&line,vector<OCRMatch>&letterLine){

    //формируем массив букв OpenType с координатами соответсвующими позиции элемента стековой буквы
    //относительно родительской буквы
    int print=0;
        
    for(int i=0;i<line.size();i++){
        //cout<<"i="<<i<<" c="<<line[346].correlation<<endl;
        if(!line[i].correlation)continue;
        string name=line[i].name;
        line[i].setSize();
        //print=0; if(i==112)print=1; if(!print)continue;
        
        DR("line["<<i<<"].name="<<line[i].name<<"/ OCRIndex="<<line[i].OCRIndex<<endl)
        
        wstring wName=UTF_to_Unicode(line[i].name);
        if(line[i].OCRIndex=='Z'||line[i].OCRIndex=='S'){
            line[i].uni=wName[0];
            line[i].status=0;
            line[i].Character=0;
            letterLine.push_back(line[i]);
            continue;
        }
        
        int index=fontGMap->getHKey(name,8);
        
        TString strT; fontTable->getTStr(index,&strT);
        DR("name="<<strT[8]<<" OCRIndex = "<<strT[4]<<endl)
        if(strT.size()<5||(strT[1]!="tib"&&strT[1]!="eng"&&strT[1]!="skt")){continue; }
        string OCRIndex=strT[4];
        if(line[i].OCRIndex=='S')OCRIndex="S";
        if(wName.size()==1||OCRIndex=="Z"){
            //переводим все буквы в верхний регистр
            wName[0]=UniBigLetters[wName[0]];
            line[i].name=Unicode_to_UTF(wName);  DR("n="<<line[i].name<<" i="<<letterLine.size()<<endl)
            line[i].uni=wName[0];
            line[i].status=0;
            line[i].Character=0;
            line[i].OCRIndex=OCRIndex[0];
            letterLine.push_back(line[i]);
        }else{
        
            for(int j=0;j<wName.size();j++){
                OCRMatch match;
                wstring w;  w=wName[j];
                //переводим все буквы в верхний регистр
                w[0]=UniBigLetters[w[0]];
                DR("    OCRLetter  =  "<<Unicode_to_UTF(w)<<" / "<<OCRIndex[j])
                DR(" x0="<<line[i].x0<<" x1="<<line[i].x1<<" y0="<<line[i].y0<<" y1="<<line[i].y1<<endl)
                match.name=Unicode_to_UTF(w);
                match.correlation=line[i].correlation;
                match.letterIndex=line[i].letterIndex;
                match.OCRIndex=OCRIndex[j];
                match.uni=w[0];
                match.status=1;                     //помечаем букву как строительный элемент OpenType
                match.Character=100;                //помечаем букву как строительный элемент OpenType
                if(wName.size()==1){match.status=0; match.Character=0;} //помечаем букву как одиночную
                
                if(OCRIndex[j]=='A'&&OCRIndex.size()==1){
                    match.x0=line[i].xCenter-line[i].letterW/2;
                    match.x1=line[i].xCenter+line[i].letterW/2;
                    match.y0=line[i].yCenter-line[i].letterH/2;
                    match.y1=line[i].yCenter+line[i].letterH/2;
                    match.letterH=line[i].letterH;
                    match.letterW=line[i].letterW;
                }
                if(OCRIndex=="S"){   //режим распознавания в котором стеки не разбираем на OpenType
                    match.x0=line[i].x0;
                    match.x1=line[i].x1;
                    match.y0=line[i].y0;
                    match.y1=line[i].y1;
                    match.letterH=line[i].letterH;
                    match.letterW=line[i].letterW;
                    match.name=line[i].name;
                    match.wName=wName;
                    match.Character=0;
                    match.OCRIndex='S';
                    match.status=0;
                    for(int j=0;j<wName.size();j++){
                        wstring w;  w=wName[j];
                        //переводим все буквы в верхний регистр
                        w[0]=UniBigLetters[w[0]];
                        match.uni+=w[0];
                    }
                    match.setSize();
                    letterLine.push_back(match);
                    break;
                }
                if(OCRIndex[j]=='A'&&OCRIndex.size()>1){
                    match.x0=line[i].xCenter-line[i].letterW/2;
                    match.x1=line[i].xCenter+line[i].letterW/2;
                    if(OCRIndex[OCRIndex.size()-1]=='V'){
                        match.y0=line[i].yCenter-line[i].letterH/2+line[i].letterW*0.75;
                        match.y1=match.y0+line[i].letterH/(int)OCRIndex.size();
                    }else{
                        if((OCRIndex[1]=='W'||OCRIndex[1]=='R')&&OCRIndex.size()==2){
                            match.y0=line[i].yCenter-line[i].letterH/2;
                            match.y1=match.y0+line[i].letterH-20;
                        }else{
                            match.y0=line[i].yCenter-line[i].letterH/2;
                            match.y1=match.y0+line[i].letterH/(int)OCRIndex.size();                
                        }    
                    }
                    match.letterH=line[i].letterW;
                    match.letterW=line[i].letterW;
                }
                if(OCRIndex[j]=='B'||
                   OCRIndex[j]=='C'||
                   OCRIndex[j]=='D'||
                   OCRIndex[j]=='E'||
                   OCRIndex[j]=='F'||
                   OCRIndex[j]=='G'||
                   OCRIndex[j]=='H'){
                    
                    match.x0=line[i].xCenter-line[i].letterW/2;
                    match.x1=line[i].xCenter+line[i].letterW/2;
                    if(OCRIndex.size()>1){
                        match.y0=letterLine[letterLine.size()-1].y0+line[i].letterH/(int)OCRIndex.size();
                    }else{
                        match.y0=line[i].y0;
                    }
                    match.y1=match.y0+line[i].letterH/(int)OCRIndex.size();
                    
                    match.letterH=match.y1-match.y0;
                    match.letterW=line[i].letterW;
                }
                if(OCRIndex[j]=='R'){
                    
                    match.x0=line[i].xCenter-line[i].letterW/2;
                    match.x1=line[i].xCenter+line[i].letterW/2;
                    if(OCRIndex.size()>1){
                        if(OCRIndex[OCRIndex.size()-1]=='R'){
                            match.y0=line[i].y1-20;
                            match.y1=match.y0+20;
                        }else{
                            match.y0=letterLine[letterLine.size()-1].y1;
                            match.y1=match.y0+20;
                        }    
                    }else{
                        match.y0=line[i].y0;
                        match.y1=line[i].y1;
                        
                    }
                    match.letterH=match.y1-match.y0;
                    match.letterW=line[i].letterW;
                }
                if(OCRIndex[j]=='W'){
                    
                    match.x0=line[i].xCenter-line[i].letterW/2;
                    match.x1=line[i].xCenter+line[i].letterW/2;
                    if(OCRIndex.size()>1){
                        if(OCRIndex[OCRIndex.size()-1]=='W'){
                            match.y0=line[i].y1-20;
                            match.y1=match.y0+20;
                        }else{
                            match.y0=letterLine[letterLine.size()-1].y1;
                            match.y1=match.y0+20;
                        }    
                    }else{
                        match.y0=line[i].y0;
                        match.y1=line[i].y1;
                        
                    }
                    match.letterH=match.y1-match.y0;
                    match.letterW=line[i].letterW;
                }
                
                
                if(OCRIndex[j]=='V'||OCRIndex[j]=='Z'||OCRIndex[j]=='X'){
                    match.x0=line[i].xCenter-line[i].letterW/2;
                    match.x1=line[i].xCenter+line[i].letterW/2;
                    match.y0=line[i].yCenter-line[i].letterH/2;
                    match.y1=match.y0+20;
                    match.letterH=match.y1-match.y0;
                    match.letterW=line[i].letterW;
                    match.name=line[i].name;
                }
                DR(" x0="<<match.x0<<" x1="<<match.x1<<" y0="<<match.y0<<" y1="<<match.y1<<endl)
                DR(" letterLine.size()="<<letterLine.size()<<" @@@"<<match.name<<endl)
                match.setSize();
                letterLine.push_back(match);
                //дополняем массив похожими по начертанию буквами
                /* if(match.name=="ཞ"){
                 OCRMatch match_=match;
                 match_.name="ན";
                 match_.wName=UTF_to_Unicode("ན");
                 match_.uni=match_.wName[0];
                 match_.correlation-=5;
                 letterLine.push_back(match_);
                 }
                 */
            }
        }
    }
    
}
Exemple #21
0
//новая версия грамматического анализатора.
//текст реконструируется на основе вероятностного анализа результатов распознавания
//с применением взаимной корреляции частей разных букв. Слоги и слова реконструируются
//на основе вероятносного анализа корпуса тибетских текстов и правил построения тибетского шрифта.
void GLogicProcessor::letterAssociation(vector<stringOCR>*strArray,
                                      vector<OCRMatch>&matchLine,
                                      vector<OCRMatch>&dLine,
                                      GBitmap* lineImg32,
                                      string &mainString,
                                      int sizeLine,
                                      int lineIndex,
                                      int OCRMode){

    int print=0;
    TIME_START
    y0Base=strArray[0][lineIndex].LimY0;
    y1Base=strArray[0][lineIndex].LimY1;
    DR("@@@y0Base"<<y0Base<<" y1Base="<<y1Base<<" s="<<matchLine.size())
    
    GBitmap *letterAImg=GBitmap::create(lineImg32->columns(),lineImg32->rows(),BITMAP_32);
    GBitmap *letterBImg=GBitmap::create(lineImg32->columns(),lineImg32->rows(),BITMAP_32);

    
    
#ifdef MAIN_MODE
    
    //for(int i=0;i<matchLine.size();i++)if(matchLine[i].letterIndex==15650){cout<<"@@@@@";exit(0);}
    
    //drawGrapeLine(matchLine); exit(0);
    
    
    sort(matchLine.begin(),matchLine.end(),sortMatchX0);
    
    //cout<<"strArray[0].size()="<<strArray[0].size()<<" matchLine.size()="<<matchLine.size()<<endl;
    
    if(!matchLine.size()||!strArray[0].size())return;   //
    
    int count=0;
    //int maxH=45;
    //int maxCor=97;
    for(int i=0;i<matchLine.size();i++){
        matchLine[i].setSize();
        count=0;
        matchLine[i].correlationNew=0;
        /*
        if((matchLine[i].OCRIndex=='A'&&
           abs(matchLine[i].y0-y0Base)>3&&
           matchLine[i].correlation>maxCor&&
           matchLine[i].letterH>maxH)||
           (matchLine[i].OCRIndex=='A'&&
            matchLine[i].y0<y0Base-3&&
            matchLine[i].correlation>98)
           ){
            maxH=matchLine[i].letterH;
            maxCor=matchLine[i].correlation;
            y0Base=matchLine[i].y0; y1Base=y0Base+32;
        }
        */
        if(!matchLine[i].correlation)continue;
        matchLine[i].status=0;
    }
    //drawGrapeLine(matchLine); exit(0);
    
    compressMatch(matchLine);
    
    //drawGrapeLine(matchLine); exit(0);
    

    //на этом этапе в matchLine записано около 50 результатов на одну букву текста
    //заменяем одинаковые буквы на букву с наибольшей корреляцией и наибольшей общей площадью совпадающей с изображением на странице.
    //также для каждой гипотезы распознанной буквы проверяем перекрытие с соседними буквами
    //оставляем только те буквы, которые лучше описывают соответствующие площади буквы области изображения.
    letterNeighborsNew(matchLine,lineImg32,letterAImg,letterBImg);
    
    
    //drawGrapeLine(matchLine); exit(0);
    
#ifdef STACK_MODE    
    //saveMatch(matchLine,"/2_2.match");
#endif
    

    for(int i=0;i<matchLine.size();i++){
        if(matchLine[i].correlation){
          matchLine[i].status=0;
          if(matchLine[i].OCRIndex!=3&&matchLine[i].correlationNew)matchLine[i].correlation=matchLine[i].correlationNew;
          dLine.push_back(matchLine[i]);
        }
    }
    
    DR("done match processing line.size()="<<dLine.size())
    sort(dLine.begin(),dLine.end(),sortMatchX0);
    DR("@@@@@ SAVE MATCH")
#ifdef STACK_MODE    
    //saveMatch(dLine,"/2.match");
#endif    
#endif
    
#ifdef STACK_MODE    
    //readMatch(dLine,"/2.match");
#endif    
    
    //компрессия. Все одинаковые буквы в пределах габарита буквы
    //заменяются на одну букву с макcмимальной корреляцией
    compressMatch(dLine);

    //drawGrapeLine(dLine); exit(0);

    collectStackLetter(strArray,dLine, matchLine,lineImg32,letterAImg,letterBImg,lineIndex);
    //cout<<"COLLECT"; TIME_PRINT_
     //exit(0);
    //drawGrapeLine(dLine);exit(0);

    compressMatch(dLine);
    //drawGrapeLine(dLine);exit(0);

    //анализ готовых стеков.
    //проверяем есть ли над или под одиночной буквой коренные буквы или огласовки с высокой корреляцией.
    //если есть, то букву считаем частью стека и убираем как строительный блок OpenType.
    testStackLetter(dLine,lineImg32,letterAImg,letterBImg);
    
    //drawGrapeLine(dLine); exit(0);
    
    letterAImg->destroy();
    letterBImg->destroy();
    
#ifdef STACK_MODE    
    //saveMatch(line,"/2_1.match");
#endif    
    
    if(print){TIME_PRINT_}
    return;
 }
static void pipe_dev_write(void *opaque, target_phys_addr_t offset, uint32_t value)
{
    PipeDevice *s = (PipeDevice *)opaque;

    switch (offset) {
    case PIPE_REG_COMMAND:
        DR("%s: command=%d (0x%x)", __FUNCTION__, value, value);
        pipeDevice_doCommand(s, value);
        break;

    case PIPE_REG_SIZE:
        DR("%s: size=%d (0x%x)", __FUNCTION__, value, value);
        s->size = value;
        break;

    case PIPE_REG_ADDRESS:
        DR("%s: address=%d (0x%x)", __FUNCTION__, value, value);
        s->address = value;
        break;

    case PIPE_REG_CHANNEL:
        DR("%s: channel=%d (0x%x)", __FUNCTION__, value, value);
        s->channel = value;
        break;

    case PIPE_REG_PARAMS_ADDR_HIGH:
        s->params_addr = (s->params_addr & ~(0xFFFFFFFFULL << 32) ) |
                          ((uint64_t)value << 32);
        break;

    case PIPE_REG_PARAMS_ADDR_LOW:
        s->params_addr = (s->params_addr & ~(0xFFFFFFFFULL) ) | value;
        break;

    case PIPE_REG_ACCESS_PARAMS:
    {
        struct access_params aps;
        uint32_t cmd;

        
        if (s->params_addr == 0)
            break;

        cpu_physical_memory_read(s->params_addr, (void*)&aps,
                        sizeof(struct access_params));

        
        s->channel = aps.channel;
        s->size = aps.size;
        s->address = aps.address;
        cmd = aps.cmd;
        if ((cmd != PIPE_CMD_READ_BUFFER) && (cmd != PIPE_CMD_WRITE_BUFFER))
            break;

        pipeDevice_doCommand(s, cmd);
        aps.result = s->status;
        cpu_physical_memory_write(s->params_addr, (void*)&aps,
                    sizeof(struct access_params));
    }
    break;

    default:
        D("%s: offset=%d (0x%x) value=%d (0x%x)\n", __FUNCTION__, offset,
            offset, value, value);
        break;
    }
}
Exemple #23
0
void GLogicProcessor::testStackLetter(vector<OCRMatch>&line,GBitmap* lineImg32,GBitmap* letterAImg,GBitmap* letterBImg){
    
    int print=0;
    int index;
    int dX=32;
    int dX_=dX/3;
    int dCMax=12;
    string xKey; xKey=(char)0xE0; xKey+=(char)0xBC; xKey+=(char)0xB9;
    
    //стираем огласовки и приписные буквы
    for(int i=0;i<line.size();i++){
        if(line[i].OCRIndex=='V'||line[i].OCRIndex=='R'||line[i].OCRIndex=='X'){
            line[i].correlation=0;
        }
        if(line[i].OCRIndex=='W'&&line[i].name=="འ")line[i].OCRIndex='A';
        //else{
        //   line[i].correlation=line[i].correlationNew;
        //}
        //cout<<"i="<<i<<"letter->correlationNew="<<line[i].correlationNew<<endl;
    }
    
    
    int size=(int)line.size();
    
    
    //letterArea(line[54],letterAImg);
    //((GImageEditor*)inputData.imageEditor)->WriteImageData(letterAImg,"/_Image2OCR/_1Draw32.jpg",0); exit(0);
    
    //drawGrapeLine(line);exit(0);
    
    //    for(int i=0;i<size;i++){ //print=1;
    
    //        OCRMatch *letter=&line[i];
    //        if(!letter->correlation)continue;
    //if(letter->name!="རྕ")continue;
    //cout<<"letter.letter.size()="<<letter->letter.size()<<endl; exit(0);
    
    
    //((GImageEditor*)inputData.imageEditor)->WriteImageData(letterAImg,"/_Image2OCR/_1Draw32.jpg",0); exit(0);
    
    //        letterAImg->fillColumns32V(0, &line[i].s);  //стираем букву
    
    
    //    }
    
    
    for(int i=0;i<size;i++){
        
        OCRMatch *letter=&line[i];
        
        //cout<<i<<" "<<(char)letter->OCRIndex<<" "<<letter->correlation<<" "<<letter->name<<endl;
        
        if(!letter->correlation)continue;
        if(letter->OCRIndex=='V'||letter->OCRIndex=='W'||letter->OCRIndex=='R'||letter->OCRIndex=='X')continue; //пропускаем OpenType
        
        //проверяем, есть ли буквы более вероятные чем тестовая.
        //print=0; if(letter->name=="ལྷ")print=1;   if(!print)continue;
        //print=0; if(i==10)print=1;   if(!print)continue;
        //cout<<"i="<<i<<" c="<<line[117].correlation<<" n="<<line[117].name<<endl;
        //cout<<" i1="<<line[128].letter[0].letterIndex<<" i2="<<line[128].letter[1].letterIndex<<endl;
        
        letterAImg->fillColumns32V(0, &line[i].s);  //стираем букву
        //проверяем, есть ли буквы более вероятные чем тестовая.
        //inputData.start=111;
        
        line[i].drawPict32(letterAImg,MATRIX_BORDER,ADD_MODE);
        
        //((GImageEditor*)inputData.imageEditor)->WriteImageData(letterAImg,"/_Image2OCR/_1Draw32.jpg",0); exit(0);
        
        //letterLineArea(line[i],lineImg32,letterAImg); //подсчитываем количество пикселов в букве; рисуем ее в letterAImg
    
        
        //сначала проверяем букву на соответствие графическому изображению на странице.
        //в пределах габарита буквы +-dY проверяем количество нераспознанных черных пикселов
        OCRBox s=line[i].s;
        s.y0=MATRIX_BORDER; s.y1=lineImg32->rows()-MATRIX_BORDER;
        //inputData.start=111;
        float pAreaPage=lineImg32->pixelCount(&s);
        
        line[i].pCount=lineImg32->img32UnionLine(letterAImg, &s);
        
        line[i].correlationNew=(pAreaPage+1)/(line[i].pCount+1);
        //количество нераспознанных пикселов (без нуля)
        DR(i<<" pAreaPage="<<pAreaPage<<" pCount="<<line[i].pCount<<" cN="<<line[i].correlationNew<<" n="<<line[i].name
           <<" x0="<<s.x0<<" x1="<<s.x1<<endl)
        
        
        if(letter->OCRIndex=='Z'){ dX_=10;}
        //int xLimit=letter->xCenter+dX;
        //int xLimit_=letter->xCenter-dX;
        int dir=1;
        //int flagReplace;
        int count=0;

        
        while(dir!=-1){
            //if(!letter->correlationNew)break;
            index=i+1;
            if(count==1){
                dir=-1;
                index=i-1;
            }
            if(dir>0) {DR(" test right"<<endl);} else {DR(" test left"<<endl)}
            
            while(1){
                if(index==-1||index==line.size())break;
                if(!line[index].correlation){ index+=dir; continue;}
                if(!letter->letter.size()&&!line[index].letter.size()){index+=dir; continue;} //не сравниваем одиночные буквы
                
                //проверяем есть ли пересечение букв.
                OCRBox s;
                intArea(&letter->s,&line[index].s,&s);

                //if(index!=8){ index+=dir; continue;}
                //DR(" index="<<index<<" s.area="<<s.area<<" letter->area="<<letter->area<<" line[index].area="<<line[index].area<<endl);
                
                if(s.area<letter->area/5&&s.area<line[index].area/5){
                    //DR("no intersection"<<endl)
                    index+=dir;
                    continue;
                }
                //строим изображение тестовой буквы
                letterBImg->fillColumns32V(0, &line[index].s);  //стираем букву
                letterLineArea(line[index],lineImg32,letterBImg); //подсчитываем количество пикселов в букве; рисуем ее в letterBImg
                //((GImageEditor*)inputData.imageEditor)->WriteImageData(letterAImg,"/_Image2OCR/_1Draw32.jpg",0); exit(0);
                //проверяем есть ли пересечение двух букв по отношению к фокальным линиям изображения
                int pArea=letterAImg->img32Union(letterBImg,&s);
                if(!pArea&&letter->name!="ར"){ //(pArea<line[index].pCount/20&&pArea<line[i].pCount/20)
                    index+=dir;
                    continue;
                }
                float dC=(float)letter->correlation/line[index].correlation;
                float dP=((float)letter->pCount)/((float)line[index].pCount);
                float dPoint=letter->pCount-line[index].pCount;
                
                DR("//@@@*** Test_I letter A "<<letter->name<<" i="<<i<<" cI="<<letter->correlation<<" pCount="<<letter->pCount<<
                   " //  letter B "<<line[index].name<<" index="<<index
                   <<" cJ="<<line[index].correlation<<" pCount="<<line[index].pCount
                   <<"  //  dC="<<dC<<" dP="<<dP<<" dPoint/cN="<<dPoint/letter->pCount<<" pArea="<<pArea<<endl)
                
                if((dC>0.93&&dP>1.05)){  //неустойчивая проверка   dP>1.05  не менять
                    DR("remove J"<<endl);
                    line[index].correlation=0;
                    index+=dir;
                    continue;
                }
                if((dC>1&&dP>1)){  //неустойчивая проверка   dP>1.05  не менять
                    DR("remove J"<<endl);
                    line[index].correlation=0;
                    index+=dir;
                    continue;
                }
                if((dC>1.2&&dP>0.9)){
                    DR("remove J"<<endl);
                    line[index].correlation=0;
                    index+=dir;
                    continue;
                }
                if((dC>0.91&&dP>1.2)){
                    DR("remove J 1"<<endl);
                    line[index].correlation=0;
                    index+=dir;
                    continue;
                }
                if(dC<1.05&&dP<0.93){
                    DR("remove I _0"<<endl);
                    letter->correlation=0; dir=-1; break;
                }
                if(dC<0.95&&dP<1.05){
                    DR("remove I _1"<<endl);
                    letter->correlation=0; dir=-1; break;
                }
                if(dC<0.96&&dP<1){
                    DR("remove I _2"<<endl);
                    letter->correlation=0; dir=-1; break;
                }
                if(dC>0.98&&dP>0.98&&(letter->name.find(xKey)!=-1&&line[index].name.find(xKey)==-1)){
                    DR("remove J by X"<<endl);
                    line[index].correlation=0;
                    index+=dir;
                    continue;
                }
                if((letter->OCRIndex=='Z'||letter->OCRIndex=='N')&&(line[index].OCRIndex=='Z'||line[index].OCRIndex=='N')){
                    if(dC>1&&dP>0.95){
                        DR("remove J by Z"<<endl);
                        line[index].correlation=0;
                        index+=dir;
                        continue;
                    }else{
                        DR("remove I by Z"<<endl);
                        letter->correlation=0; dir=-1; break;
                    }
                }
                
                index+=dir;
            }
            count++;
        }
        //exit(0);
        //@@@@
        
        
    }
    
      
}
Exemple #24
0
void GLogicProcessor::renderDictSearch(map<vector<short>,int>&searchResult,
                                       vector<OCRMatch>&dLine,
                                       vector<OCRMatch>&originalMatch,
                                       vector<OCRMatch>&pageText){
    
    int print=0;
    DR(" searchResult.size()="<<searchResult.size()<<" dLine()="<<dLine.size())
    vector<OCRMatch>wordLine;
    
    //TIME_START
    
    //в dLine[] записаны пары букв из которых словарь собирал фразы
    //для окончательной сборки фразы нужны найденные с словаре фразы, составленные из оригинальных пар букв
    //также нужны сами пары букв для частей фразы на которые не найдены ответы словаря 
    //каждый OCRMatch содержит два массива, в которые записана информация о парах букв, составляющих фразу.
    // .line[] содержит индекс пар букв и возвращается заполненным в searchResult как результат работы словаря
    // .letter[] содержит копию пары букв по индексу line[] из исходного массива dLine[]
    for(int i=0;i<originalMatch.size();i++){
        originalMatch[i].setSize();
    }
    map<vector<short>,int>::iterator it;
    for (it = searchResult.begin(); it != searchResult.end(); ++it) {
        OCRMatch word;
        int in=abs(it->first[0]);   //знаком значения записано есть ли по мнению словаря разделитель слогов в этой паре
        word.x0=dLine[in].x0;
        word.y0=dLine[in].y0;
        word.xL0C=dLine[in].letter[0].xCenter;
        int d; int sizeStr=0;
        while(sizeStr<128){    
            d=it->first[sizeStr];  DR(d<<" ")
            if(d==32767)break;  //32767 маркирует конец строки
            word.line.push_back(d);
            sizeStr++;
        }

        d=abs(word.line[word.line.size()-1]);
        word.x1=dLine[d].x1;
        word.y1=dLine[d].y1;
        word.xL1C=dLine[d].letter[1].xCenter;

        word.correlation=0;
        int n;
        for(int i=0;i<sizeStr;i++){
            //DR(searchResult[i].line[j]<<" c="<<line[searchResult[i].line[j]].correlation;
            //DR(" searchResult["<<i<<"].line.size()="<<searchResult[i].line.size()<<" ind="<<searchResult[i].line[j])
            n=abs(it->first[i]); 
            word.wName+=dLine[n].wName[0];
            word.correlation+=dLine[n].correlation;
        }
        word.wName+=dLine[n].wName[1];
        word.correlation=word.correlation/sizeStr+(float)(sizeStr*100)/50+(float)(it->second)/5000;   //учитываем длину и вероятность фразы
        //word.correlation+=it->second;   //прибавляем к кореляции количество ответов словаря
        //word.correlation=word.line.size();
        //if(word.correlation<70)continue;
        word.name=Unicode_to_UTF(word.wName);  DR("Yagpo= "<<word.name<<" "<<endl)
        word.name=YagpoToUni(word.name);       DR("xL0C="<<word.xL0C<<"xL1C="<<word.xL1C<<" n="<<word.name<<endl);
        DR(word.name<<"/"<<"c="<<word.correlation<<" x0="<<word.x0<<" x1="<<word.x1<<" y0="<<word.y0<<" y1="<<word.y1<<endl)
        wordLine.push_back(word);
    }
    //drawGrapeLine(wordLine); exit(0);        //результаты словаря с записаными в разделители букв знаками препинания и расставленными слогами
    //drawGrapeLine(originalMatch); exit(0);   //результаты распознавания
    //drawGrapeLine(dLine); exit(0);           //пары букв с записанными в разделители букв знаками препинания
    
    //print=1;
    //добавляем распознанные пары букв 
    for(int i=0;i<dLine.size();i++){
        if(!dLine[i].correlation)continue; //значение уже записано
        OCRMatch word=dLine[i];
        word.name=Unicode_to_UTF(word.wName);  //DR("Yagpo= "<<word.name<<" ")
        word.name=YagpoToUni(word.name);
        word.line=dLine[i].line;
        word.line.push_back(i);
        wordLine.push_back(word);
        
    }
    

    
    for(int i=0;i<wordLine.size();i++){
        wordLine[i].status=0;
        wordLine[i].allMatchCount=1;
        wordLine[i].setSize();
        //DR(" wordLine[i]="<<wordLine[i].name<<" w="<<wordLine[i].letterW)
        
    }
    
    sort(wordLine.begin(),wordLine.end(),sortMatchX0);
    compressMatch(wordLine);
    
    //drawGrapeLine(wordLine); exit(0);
    
    //int count=(int)wordLine.size();
    //int step=0;
    print=0;


    //проверяем ответы словаря на здравый смысл. Пары букв из которых составлен ответ словаря не должны отменять
    //уверенно распознанные буквы
    //также убираем пустые значения
    vector<OCRMatch>wLine;
    for(int i=0;i<wordLine.size();i++){
        if(!wordLine[i].correlation)continue;
        wordLine[i].status=0;
        DR("wordLine["<<i<<"].name="<<wordLine[i].name<<endl);
        if(wordLine[i].line.size()>1){
            //для полученных фраз удобнее хранить исходные пары букв внутри фразы
            for(int j=0;j<wordLine[i].line.size();j++){
                DR(" ind="<<wordLine[i].line[j]<<" size="<<wordLine[i].line.size())
                DR(" n="<<dLine[abs(wordLine[i].line[j])].name<<" d="<<dLine[abs(wordLine[i].line[j])].letter[0].delimeter<<endl)
                wordLine[i].letter.push_back(dLine[abs(wordLine[i].line[j])].letter[0]);
                //wordLine[i].letter.push_back(dLine[abs(wordLine[i].line[j])].letter[1]);
                if(wordLine[i].line[j]<0){   //если в паре по мнению словаря есть разделитель слога (минус маркирует такие пары) /@@@
                    wordLine[i].letter[wordLine[i].letter.size()-1].delimeter=dLine[abs(wordLine[i].line[j])].letter[0].delimeter;
                    if(wordLine[i].letter[wordLine[i].letter.size()-1].delimeter=="")wordLine[i].letter[wordLine[i].letter.size()-1].delimeter="་";
                }
            }
            wordLine[i].letter.push_back(dLine[abs(wordLine[i].line[wordLine[i].line.size()-1])].letter[1]);
        }
        //if(wordLine[i].letter.size()==1){  //нормализуем одиночные пары букв
        //    wordLine[i].letter[0].delimeter=wordLine[i].delimeter;
       // }
        wLine.push_back(wordLine[i]);
    }
    //drawGrapeLine(wLine); exit(0);
    //полученные в результате подготовки в  renderDictSearch части фразы собираем в целые фразы
    //на этом этапе фразы собираются вместе ограничителями слогов и знаками препинания и примечаниями внутри фразы.
    sentenceConstructur(wLine);
    
    //drawGrapeLine(wLine); exit(0);

    //расставляем ограничители слогов (точки)
    print=0;
    string str;
    wstring delimeter;
    for(int n=0;n<originalMatch.size();n++){
        originalMatch[n].setSize();
    }
    print=0;
    for(int i=0;i<wLine.size();i++){
        if(!wLine[i].correlation)continue;
        DR(wLine[i].name<<endl)
        wLine[i].wName=L"";
        for(int n=0;n<wLine[i].letter.size();n++){
            str=wLine[i].letter[n].delimeter;  //cout<<"d="<<str;
            str=UnicodeToYagpo(str);
            delimeter=UTF_to_Unicode(str);
            wLine[i].wName+=wLine[i].letter[n].wName[0]+delimeter;
            DR(" n="<<wLine[i].letter[n].name<<"d="<<str<<"/"<<endl)
        }
        wLine[i].wName+=wLine[i].letter[wLine[i].letter.size()-1].wName[1];
        wLine[i].name=Unicode_to_UTF(wLine[i].wName);
        wLine[i].name=YagpoToUni(wLine[i].name);
        DR(" n="<<wLine[i].name<<endl)
        wLine[i].correlation+=3;  //создаем приоритет над парами без расставленных ограничителей слогов
        //добавляем результат к массиву исходных букв (результат распознавания включая все распознанные буквы и символы)
        //это позволит разобрать части фразы, не закрытые словарными ответами
        //x0=wLine[i].x0; x1=wLine[i].x1;
        //for(int n=0;n<dLine.size();n++){
        //    if(dLine[n].x0>=x0&&dLine[n].x1<=x1)dLine[n].correlation=0;
        //}
        //wLine[i].correlation=100;
        dLine.push_back(wLine[i]);
        //DR(wLine[i].name)
    }
    
    //добавляем все исходные графические элементы. Это нужно для распознования отдельно стоящих букв и знаков препинания
    for(int i=0;i<originalMatch.size();i++)dLine.push_back(originalMatch[i]);
    for(int i=0;i<dLine.size();i++)dLine[i].setSize();
    sort(dLine.begin(),dLine.end(),sortMatchXCenter);
    
    //drawGrapeLine(dLine); exit(0);
    
    
    print=0;
    //убираем фразы внутри стыкованной фразы
    int limit;
    for(int n=0;n<dLine.size();n++){
        if(!dLine[n].correlation)continue;
        if(dLine[n].y0>y1Base)dLine[n].correlation=0;
        
        //print=0;if(n==13)print=1; if(!print)continue;
        DR("@@@@"<<n<<" Collect n="<<dLine[n].name<<" d="<<dLine[n].delimeter<<endl)
        
        for(int m=0;m<dLine.size();m++){
          if(!dLine[m].correlation)continue;
          //print=0;if(m==16)print=1;
          if(m==n)continue;
          limit=12; 
          
          if(dLine[n].OCRIndex!='N'&&dLine[m].OCRIndex=='N')limit=0;  
          if(dLine[n].OCRIndex!='Z'&&dLine[m].OCRIndex=='Z')limit=0;
          if(dLine[n].OCRIndex=='N'&&dLine[m].OCRIndex=='N')limit=0;
          if(dLine[n].OCRIndex=='Z'&&dLine[m].OCRIndex=='Z')limit=4;
          if(dLine[n].OCRIndex=='Z'&&dLine[m].OCRIndex!='Z')limit=0;
          if(dLine[n].OCRIndex=='S'&&dLine[m].OCRIndex=='S')limit=0;
          
          if(dLine[m].xCenter>dLine[n].x0-limit&&dLine[m].xCenter<dLine[n].x1+limit){
          
              DR("n"<<n<<"="<<dLine[n].name<<" d="<<dLine[n].delimeter<<" c="<<dLine[n].correlation<<" m"<<m<<"="<<dLine[m].name
                 <<" c="<<dLine[m].correlation<<" xmC="<<dLine[m].xCenter<<" xnC="<<dLine[n].xCenter<<" xnX0="<<dLine[n].x0<<" xnX1="<<dLine[n].x1<<" wM="<<dLine[m].letterW<<" wN="<<dLine[n].letterW<<endl);
              
                  if(dLine[n].correlation>dLine[m].correlation){
                      if(dLine[n].letterW>dLine[m].letterW-limit||(dLine[n].letterW/dLine[m].letterW)>1.3){ DR(100)
                          DR("REMOVE M "<<m<<" cM="<<dLine[m].correlation<<" wM="<<dLine[m].letterW<<" cN="<<dLine[n].correlation<<" wN="<<dLine[n].letterW<<endl)
                          dLine[m].correlation=0;
                      }else{ DR(200)
                          if(dLine[n].correlation-dLine[m].correlation>5){   //предпочтение отдаем более широким буквам
                              dLine[m].correlation=0;
                              DR("REMOVE M1 "<<m<<" cN="<<dLine[n].correlation<<endl)
                          }else{
                              DR("REMOVE N "<<m<<" cN="<<dLine[n].correlation<<endl)
                              dLine[n].correlation=0;
                              break;
                          }    
                      }    
                  }else{
                      if(dLine[m].letterW>dLine[n].letterW-limit||(dLine[n].letterW/dLine[m].letterW)<1.3){
Exemple #25
0
static void pipe_dev_write(void *opaque, hwaddr offset, uint32_t value)
{
    PipeDevice *s = (PipeDevice *)opaque;

    switch (offset) {
    case PIPE_REG_COMMAND:
        DR("%s: command=%d (0x%x)", __FUNCTION__, value, value);
        pipeDevice_doCommand(s, value);
        break;

    case PIPE_REG_SIZE:
        DR("%s: size=%d (0x%x)", __FUNCTION__, value, value);
        s->size = value;
        break;

    case PIPE_REG_ADDRESS:
        DR("%s: address=%d (0x%x)", __FUNCTION__, value, value);
        uint64_set_low(&s->address, value);
        break;

    case PIPE_REG_ADDRESS_HIGH:
        DR("%s: address_high=%d (0x%x)", __FUNCTION__, value, value);
        uint64_set_high(&s->address, value);
        break;

    case PIPE_REG_CHANNEL:
        DR("%s: channel=%d (0x%x)", __FUNCTION__, value, value);
        uint64_set_low(&s->channel, value);
        break;

    case PIPE_REG_CHANNEL_HIGH:
        DR("%s: channel_high=%d (0x%x)", __FUNCTION__, value, value);
        uint64_set_high(&s->channel, value);
        break;

    case PIPE_REG_PARAMS_ADDR_HIGH:
        s->params_addr = (s->params_addr & ~(0xFFFFFFFFULL << 32) ) |
                          ((uint64_t)value << 32);
        break;

    case PIPE_REG_PARAMS_ADDR_LOW:
        s->params_addr = (s->params_addr & ~(0xFFFFFFFFULL) ) | value;
        break;

    case PIPE_REG_ACCESS_PARAMS:
    {
		int printData = matchMeInPidTid(cpu_single_env);
        struct access_params aps;
        struct access_params_64 aps64;
        uint32_t cmd;

        /* Don't touch aps.result if anything wrong */
        if (s->params_addr == 0)
            break;

        if (goldfish_guest_is_64bit()) {
            cpu_physical_memory_read(s->params_addr, (void*)&aps64,
                                     sizeof(aps64), printData, "pipe_reg_access_params_64");
        } else {
            cpu_physical_memory_read(s->params_addr, (void*)&aps,
                                     sizeof(aps), printData, "pipe_reg_access_params_els");
        }
        /* sync pipe device state from batch buffer */
        if (goldfish_guest_is_64bit()) {
            s->channel = aps64.channel;
            s->size = aps64.size;
            s->address = aps64.address;
            cmd = aps64.cmd;
        } else {
            s->channel = aps.channel;
            s->size = aps.size;
            s->address = aps.address;
            cmd = aps.cmd;
        }
        if ((cmd != PIPE_CMD_READ_BUFFER) && (cmd != PIPE_CMD_WRITE_BUFFER))
            break;

        pipeDevice_doCommand(s, cmd);
        if (goldfish_guest_is_64bit()) {
            aps64.result = s->status;
            cpu_physical_memory_write(s->params_addr, (void*)&aps64,
                                      sizeof(aps64), printData, "pipe_reg_acess_1_64");
        } else {
            aps.result = s->status;
            cpu_physical_memory_write(s->params_addr, (void*)&aps,
                                      sizeof(aps), printData, "pipe_reg_acess_1_else");
        }
    }
    break;

    default:
        D("%s: offset=%d (0x%x) value=%d (0x%x)\n", __FUNCTION__, offset,
            offset, value, value);
        break;
    }
}
Exemple #26
0
//новая версия грамматического анализатора.
//текст реконструируется на основе вероятностного анализа результатов распознавания
//с применением взаимной корреляции частей разных букв. Слоги и слова реконструируются
//на основе вероятносного анализа корпуса тибетских текстов и правил построения шрифта.
void GLogicProcessor::classification(vector<stringOCR>&strArray,
                                      vector<OCRMatch>&matchLine,
                                      GBitmap* lineImg32,
                                      string &mainString,
                                      int sizeLine,
                                      int lineIndex){

    int print=0;
    vector<OCRMatch>dLine;
    TIME_START
    y0Base=strArray[lineIndex].LimY0;
    y1Base=strArray[lineIndex].LimY1;
    DR("@@@y0Base"<<y0Base<<" y1Base="<<y1Base<<" s="<<matchLine.size())
    
    GBitmap *letterAImg=GBitmap::create(lineImg32->columns(),lineImg32->rows(),BITMAP_32);
    GBitmap *letterBImg=GBitmap::create(lineImg32->columns(),lineImg32->rows(),BITMAP_32);

    
    
#ifdef MAIN_MODE
    
    //for(int i=0;i<matchLine.size();i++)if(matchLine[i].letterIndex==15650){cout<<"@@@@@";exit(0);}
    
    //drawGrapeLine(matchLine); exit(0);
    
    
    sort(matchLine.begin(),matchLine.end(),sortMatchX0);
    
    //cout<<"strArray.size()="<<strArray[0].size()<<" matchLine.size()="<<matchLine.size()<<endl;
    
    if(!matchLine.size()||!strArray.size())return;   //
    
    for(int i=0;i<matchLine.size();i++){
        matchLine[i].correlationNew=0;
        if(!matchLine[i].correlation)continue;
        matchLine[i].status=0;
    }
    //drawGrapeLine(matchLine); exit(0);

    compressMatch(matchLine);
    //drawGrapeLine(matchLine); exit(0);


    //на этом этапе в matchLine записано около 50 результатов на одну букву текста
    //заменяем одинаковые буквы на букву с наибольшей корреляцией и наибольшей общей площадью совпадающей с изображением на странице.
    //также для каждой гипотезы распознанной буквы проверяем перекрытие с соседними буквами
    //оставляем только те буквы, которые лучше описывают соответствующие площади буквы области изображения.
    letterNeighborsNew(matchLine,lineImg32,letterAImg,letterBImg);

    //drawGrapeLine(matchLine); exit(0);
    
    
#ifdef STACK_MODE    
    //saveMatch(matchLine,"/2_2.match");
#endif
    

    for(int i=0;i<matchLine.size();i++){
        if(matchLine[i].correlation){
          matchLine[i].status=0;
          if(matchLine[i].OCRIndex!=3&&matchLine[i].correlationNew)matchLine[i].correlation=matchLine[i].correlationNew;
          dLine.push_back(matchLine[i]);
        }
    }
    
    DR("done match processing line.size()="<<dLine.size())
    sort(dLine.begin(),dLine.end(),sortMatchX0);
    DR("@@@@@ SAVE MATCH")
#ifdef STACK_MODE    
    //saveMatch(dLine,"/2.match");
#endif    
#endif
    
#ifdef STACK_MODE    
    //readMatch(dLine,"/2.match");
#endif    
    
    //компрессия. Все одинаковые буквы в пределах габарита буквы
    //заменяются на одну букву с макcмимальной корреляцией
    compressMatch(dLine);

    //drawGrapeLine(dLine); exit(0);

    collectStackLetter(strArray,dLine, matchLine,lineImg32,letterAImg,letterBImg,lineIndex);
    //cout<<"COLLECT"; TIME_PRINT_
     //exit(0);
    //drawGrapeLine(dLine);exit(0);

    compressMatch(dLine);
    //drawGrapeLine(dLine);exit(0);
    //анализ готовых стеков.
    //проверяем есть ли над или под одиночной буквой коренные буквы или огласовки с высокой корреляцией.
    //если есть, то букву считаем частью стека и убираем как строительный блок OpenType.
    //testStackLetter(dLine,lineImg32,letterAImg,letterBImg);
    
    //drawGrapeLine(dLine); exit(0);
    
    letterAImg->destroy();
    letterBImg->destroy();
    
    string strW;
    vector<uint>letterX;
    vector<OCRMatch>line;
    vector<OCRMatch>resultLine;
    map<vector<int>,ulong>searchResult;
    
    buildSearchString(dLine,line,letterX,strW);
    cout<<strW<<endl<<endl;
    //drawGrapeLine(line); exit(0);
    textCorpusGMap->getOCRStackKey(strW,letterX,searchResult, ANY_MATCH);
    //inputData.log<<" 2"<<endl;inputData.log.flush();
    for (int i=0;i<line.size();i++){
        if(!line[i].correlation)continue;                        //cout<<line[i].name;
        line[i].name=Unicode_to_UTF(line[i].wName);              //cout<<" -- "<<line[i].name;
        line[i].name=YagpoToUni(line[i].name);   //cout<<" -- "<<line[i].name<<endl;
        resultLine.push_back(line[i]);
    }
    //logicProcessor->drawGrapeLine(line); //exit(0);
    //inputData.log<<" 3"<<endl;inputData.log.flush();
    //renderDictSearch(searchResult,line,resultLine,matchLine);   //mainString+="<br>"+lineString+"original<br>";
    if(print){ cout<<"RENDER "; TIME_PRINT_ }
    strArray[lineIndex].line=dLine;   //сохраняем для вывода в HTML
    //logicProcessor->drawGrapeLine(dLine); //exit(0);
    //inputData.log<<" 4"<<endl;inputData.log.flush();

}
int main(int argc, char* argv[])
{
#ifdef MEMDEBUG
    atexit(&DumpUnfreed);
#endif

    if (argc < 3) myerror("Usage: corrnn datafile randfiles");

    dbgout = new std::ofstream("nn.debug");

    std::ifstream fin(argv[1]);
    std::ifstream randlistfin(argv[2]);

    std::vector<NCellData> data;

    dbg << "Read gals\n";
    Read(fin,minsep,binsize,data);
    NCell wholefield(data);

    dbg << "ngals = "<<data.size();

    dbg << "Read rand fields\n";
    int nrandfields;
    randlistfin >> nrandfields;
    if (!randlistfin) myerror("reading randlistfile ",argv[2]);
    if (!(nrandfields > 0)) myerror("no random fields");
    std::vector<std::vector<NCellData> > randdata(nrandfields);
    std::vector<NCell*> randfield(nrandfields);
    for(int i=0;i<nrandfields;++i) {
        std::string randfieldname;
        randlistfin >> randfieldname;
        if (!randlistfin) myerror("reading randlistfile ",argv[2]);
        std::ifstream randfin(randfieldname.c_str());
        Read(randfin,minsep,binsize,randdata[i]);
        randfield[i] = new NCell(randdata[i]);
    }

    dbg<<"nbins = "<<nbins<<": min,maxsep = "<<minsep<<','<<maxsep<<std::endl;

    std::vector<BinData2<1,1> > DD(nbins), RR(nbins), DR(nbins);

    Process2(DD,minsep,maxsep,minsepsq,maxsepsq,wholefield);
    for(int k=0;k<nbins;++k) DD[k].npair *= 2;

    for(int i=0;i<nrandfields;++i) {
        dbg<<"rand: i = "<<i<<std::endl;
        Process2(RR,minsep,maxsep,minsepsq,maxsepsq,*randfield[i]);
        Process11(DR,minsep,maxsep,minsepsq,maxsepsq,wholefield,*randfield[i]);
    }
    for(int k=0;k<nbins;++k) RR[k].npair *= 2;
    int ndr = nrandfields;
    int nrr = nrandfields;

#ifdef DOCROSSRAND
    for(int i=0;i<nrandfields;++i) {
        for(int j=i+1;j<nrandfields;++j) {
            dbg<<"j = "<<j<<std::endl;
            Process11(RR,minsep,maxsep,minsepsq,maxsepsq,
                      *randfield[i],*randfield[j]);
            ++nrr;
        }
    }
#endif
    dbg<<"done process DD,DR,RR data\n";

    for(int i=0;i<nbins;++i) {
        dbg<<"RR["<<i<<"] = "<<RR[i].npair<<", DD = "<<DD[i].npair<<", DR = "<<DR[i].npair<<std::endl;
        RR[i].npair /= nrr;
        DR[i].npair /= ndr;
    }
    dbg<<"done divide by number of realizations\n";

    std::ofstream fout("nn.out");
    WriteNN(fout,minsep,binsize,DD,DR,RR,nrr);
    dbg<<"done write"<<std::endl;

    if (dbgout && dbgout != &std::cout) 
    { delete dbgout; dbgout=0; }
    return 0;
}
Exemple #28
0
inline void
Trr2kTTTT
( UpperOrLower uplo,
  Orientation orientationOfA, Orientation orientationOfB,
  Orientation orientationOfC, Orientation orientationOfD, 
  T alpha, const DistMatrix<T>& A, const DistMatrix<T>& B,
           const DistMatrix<T>& C, const DistMatrix<T>& D,
  T beta,        DistMatrix<T>& E )
{
#ifndef RELEASE
    PushCallStack("internal::Trr2kTTTT");
    if( E.Height() != E.Width()  || A.Height() != C.Height() ||
        A.Width()  != E.Height() || C.Width()  != E.Height() ||
        B.Height() != E.Width()  || D.Height() != E.Width()  ||
        A.Height() != B.Width()  || C.Height() != D.Width() )
        throw std::logic_error("Nonconformal Trr2kTTTT");
#endif
    const Grid& g = E.Grid();

    DistMatrix<T> AT(g),  A0(g),
                  AB(g),  A1(g),
                          A2(g);
    DistMatrix<T> BL(g), BR(g),
                  B0(g), B1(g), B2(g);

    DistMatrix<T> CT(g),  C0(g),
                  CB(g),  C1(g),
                          C2(g);
    DistMatrix<T> DL(g), DR(g),
                  D0(g), D1(g), D2(g);

    DistMatrix<T,STAR,MC  > A1_STAR_MC(g);
    DistMatrix<T,VR,  STAR> B1_VR_STAR(g);
    DistMatrix<T,STAR,MR  > B1AdjOrTrans_STAR_MR(g);
    DistMatrix<T,STAR,MC  > C1_STAR_MC(g);
    DistMatrix<T,VR,  STAR> D1_VR_STAR(g);
    DistMatrix<T,STAR,MR  > D1AdjOrTrans_STAR_MR(g);

    A1_STAR_MC.AlignWith( E );
    B1_VR_STAR.AlignWith( E );
    B1AdjOrTrans_STAR_MR.AlignWith( E );
    C1_STAR_MC.AlignWith( E );
    D1_VR_STAR.AlignWith( E );
    D1AdjOrTrans_STAR_MR.AlignWith( E );

    LockedPartitionDown
    ( A, AT,
         AB, 0 );
    LockedPartitionRight( B, BL, BR, 0 );
    LockedPartitionDown
    ( C, CT,
         CB, 0 );
    LockedPartitionRight( D, DL, DR, 0 );
    while( AT.Height() < A.Height() )
    {
        LockedRepartitionDown
        ( AT,  A0,
         /**/ /**/
               A1,
          AB,  A2 );
        LockedRepartitionRight
        ( BL, /**/ BR,
          B0, /**/ B1, B2 );
        LockedRepartitionDown
        ( CT,  C0,
         /**/ /**/
               C1,
          CB,  C2 );
        LockedRepartitionRight
        ( DL, /**/ DR,
          D0, /**/ D1, D2 );

        //--------------------------------------------------------------------//
        A1_STAR_MC = A1;
        C1_STAR_MC = C1;
        B1_VR_STAR = B1;
        D1_VR_STAR = D1;
        if( orientationOfB == ADJOINT )
            B1AdjOrTrans_STAR_MR.AdjointFrom( B1_VR_STAR );
        else
            B1AdjOrTrans_STAR_MR.TransposeFrom( B1_VR_STAR );
        if( orientationOfD == ADJOINT )
            D1AdjOrTrans_STAR_MR.AdjointFrom( D1_VR_STAR );
        else
            D1AdjOrTrans_STAR_MR.TransposeFrom( D1_VR_STAR );
        LocalTrr2k
        ( uplo, orientationOfA, orientationOfC,
          alpha, A1_STAR_MC, B1AdjOrTrans_STAR_MR,
                 C1_STAR_MC, D1AdjOrTrans_STAR_MR,
          beta,  E );
        //--------------------------------------------------------------------//

        SlideLockedPartitionRight
        ( DL,     /**/ DR,
          D0, D1, /**/ D2 );
        SlideLockedPartitionDown
        ( CT,  C0,
               C1,
         /**/ /**/
          CB,  C2 );
        SlideLockedPartitionRight
        ( BL,     /**/ BR,
          B0, B1, /**/ B2 );
        SlideLockedPartitionDown
        ( AT,  A0,
               A1,
         /**/ /**/
          AB,  A2 );
    }
#ifndef RELEASE
    PopCallStack();
#endif
}
Exemple #29
0
void test_dr_dk ()
{
    static const struct {
        unsigned char keydata[KEYLENGTH];
        int usage_len;
        unsigned char usage[8];
    } derive_tests[] = {
        {
            {
                0xdc, 0xe0, 0x6b, 0x1f, 0x64, 0xc8, 0x57, 0xa1,
                0x1c, 0x3d, 0xb5, 0x7c, 0x51, 0x89, 0x9b, 0x2c,
                0xc1, 0x79, 0x10, 0x08, 0xce, 0x97, 0x3b, 0x92,
            },
            5, { 0x00, 0x00, 0x00, 0x01, 0x55 },
        },
        {
            {
                0x5e, 0x13, 0xd3, 0x1c, 0x70, 0xef, 0x76, 0x57,
                0x46, 0x57, 0x85, 0x31, 0xcb, 0x51, 0xc1, 0x5b,
                0xf1, 0x1c, 0xa8, 0x2c, 0x97, 0xce, 0xe9, 0xf2,
            },
            5, { 0x00, 0x00, 0x00, 0x01, 0xaa },
        },
        {
            {
                0x98, 0xe6, 0xfd, 0x8a, 0x04, 0xa4, 0xb6, 0x85,
                0x9b, 0x75, 0xa1, 0x76, 0x54, 0x0b, 0x97, 0x52,
                0xba, 0xd3, 0xec, 0xd6, 0x10, 0xa2, 0x52, 0xbc,
            },
            5, { 0x00, 0x00, 0x00, 0x01, 0x55 },
        },
        {
            {
                0x62, 0x2a, 0xec, 0x25, 0xa2, 0xfe, 0x2c, 0xad,
                0x70, 0x94, 0x68, 0x0b, 0x7c, 0x64, 0x94, 0x02,
                0x80, 0x08, 0x4c, 0x1a, 0x7c, 0xec, 0x92, 0xb5,
            },
            5, { 0x00, 0x00, 0x00, 0x01, 0xaa },
        },
        {
            {
                0xd3, 0xf8, 0x29, 0x8c, 0xcb, 0x16, 0x64, 0x38,
                0xdc, 0xb9, 0xb9, 0x3e, 0xe5, 0xa7, 0x62, 0x92,
                0x86, 0xa4, 0x91, 0xf8, 0x38, 0xf8, 0x02, 0xfb,
            },
            8, { 'k', 'e', 'r', 'b', 'e', 'r', 'o', 's' },
        },
        {
            {
                0xb5, 0x5e, 0x98, 0x34, 0x67, 0xe5, 0x51, 0xb3,
                0xe5, 0xd0, 0xe5, 0xb6, 0xc8, 0x0d, 0x45, 0x76,
                0x94, 0x23, 0xa8, 0x73, 0xdc, 0x62, 0xb3, 0x0e,
            },
            7, { 'c', 'o', 'm', 'b', 'i', 'n', 'e', },
        },
        {
            {
                0xc1, 0x08, 0x16, 0x49, 0xad, 0xa7, 0x43, 0x62,
                0xe6, 0xa1, 0x45, 0x9d, 0x01, 0xdf, 0xd3, 0x0d,
                0x67, 0xc2, 0x23, 0x4c, 0x94, 0x07, 0x04, 0xda,
            },
            5, { 0x00, 0x00, 0x00, 0x01, 0x55 },
        },
        {
            {
                0x5d, 0x15, 0x4a, 0xf2, 0x38, 0xf4, 0x67, 0x13,
                0x15, 0x57, 0x19, 0xd5, 0x5e, 0x2f, 0x1f, 0x79,
                0x0d, 0xd6, 0x61, 0xf2, 0x79, 0xa7, 0x91, 0x7c,
            },
            5, { 0x00, 0x00, 0x00, 0x01, 0xaa },
        },
        {
            {
                0x79, 0x85, 0x62, 0xe0, 0x49, 0x85, 0x2f, 0x57,
                0xdc, 0x8c, 0x34, 0x3b, 0xa1, 0x7f, 0x2c, 0xa1,
                0xd9, 0x73, 0x94, 0xef, 0xc8, 0xad, 0xc4, 0x43,
            },
            5, { 0x00, 0x00, 0x00, 0x01, 0x55 },
        },
        {
            {
                0x26, 0xdc, 0xe3, 0x34, 0xb5, 0x45, 0x29, 0x2f,
                0x2f, 0xea, 0xb9, 0xa8, 0x70, 0x1a, 0x89, 0xa4,
                0xb9, 0x9e, 0xb9, 0x94, 0x2c, 0xec, 0xd0, 0x16,
            },
            5, { 0x00, 0x00, 0x00, 0x01, 0xaa },
        },
    };
    int i;

    for (i = 0; i < ASIZE(derive_tests); i++) {
#define D (derive_tests[i])
        krb5_keyblock key;
        krb5_data usage;

        unsigned char drData[KEYBYTES];
        krb5_data dr;
        unsigned char dkData[KEYLENGTH];
        krb5_keyblock dk;

        key.length = KEYLENGTH, key.contents = D.keydata;
        usage.length = D.usage_len, usage.data = D.usage;
        dr.length = KEYBYTES, dr.data = drData;
        dk.length = KEYLENGTH, dk.contents = dkData;

        printf ("key:\t"); printkey (&key); printf ("\n");
        printf ("usage:\t"); printdata (&usage); printf ("\n");
        DR (&dr, &key, &usage);
        printf ("DR:\t"); printdata (&dr); printf ("\n");
        DK (&dk, &key, &usage);
        printf ("DK:\t"); printkey (&dk); printf ("\n\n");
    }
}
Exemple #30
0
// -----------------------------------------------------------------------------
int GBitsetMatrix::setMatrix_Lion(GBitMask32 *mask32,
										int xSrc0,
										int ySrc0,
										int xSrc1,
										int ySrc1,
										int dlt,
										int *maxX,
										int *maxY,
										int print) {
/**/

	int sx0,sy0,sx1,sy1;
	int x,y,m,n,t;                 //  ,p,d
	int LfAmSum,RgAmSum;
	int Lf,Rg,LfMem,RgMem, Delta;  //float Lf,Rg,LfMem,RgMem, Delta;
	int LfxP, RgxP, LfyP, RgyP;
	int MaxCorX=0,MaxCorY=0,AdrMaxCorX=0,AdrMaxCorY=0;
	int ch=0,correlation=0;     //    ,wVh M,
	//отключение в config.h всех DP  -  #define DR(x) //c_out<<x;
    //print=1;
	int printP=0;


#ifdef REPORT
	//cout_<<"Matrix_Lion_1@@ dlt="<<dlt<<" xSrc0="<<xSrc0<<" xSrc1="<<xSrc1<<" ySrc0="<<ySrc0<<" ySrc1="<<ySrc1<<" mask32.mHOn="<<mask32->mHOn;
#endif

#ifdef REPORT
	int color;
	if(dlt==0)color=0xff4040ff;  ////red
#ifdef DEBUGLVL_DRAW	
    if(print)drawDataRGB->put(xSrc0-32,ySrc0,0xff4040ff);    ////red
#endif
#endif	


	//static clock_t  tm_start1=clock();
	//clock_t  tm_end; double time;  DR(END); //DR(tm<<" "<<t);


/*
// константы для алгоритма подсчета единиц в 128 или в 64р словах
static const unsigned int constF[12]={              // 12  16
	0x33333333, 0x33333333, 0x33333333, 0x33333333,
	0x55555555, 0x55555555, 0x55555555, 0x55555555,
	0x0f0f0f0f, 0x0f0f0f0f, 0x0f0f0f0f, 0x0f0f0f0f  // ,
//	0x00000000, 0x00000000, 0x00000000, 0x00000000  // TEST
};

// переход в режим Assembler, загрузка констант
__asm {     //  movups (без требования выравнивания)
	// загрузка констант в регистр 64p ММХ ( считаем в байтах - int*4)
	movq            mm5, qword ptr constF+16;   // 55 Пересылка данных (64 бит)
	movq            mm6, qword ptr constF;      // 33 из/в регистр ММХ  MOVDQU-128
	movq            mm7, qword ptr constF+32;   // 0f

	// загрузка констант в регистр 128p SSE
	//  movups без требования выравнивания  ( MOVAPS должны быть выровнены )
#ifdef WIN32
	movups          xmm5, dqword ptr constF+16;  // 55  Пересылка данных (128 бит)
	movups          xmm6, dqword ptr constF;     // 33  + MOVDQU
	movups          xmm7, dqword ptr constF+32;  // 0f
//	movups          xmm2, dqword ptr constF+48;  // TEST
#else
	movups          xmm5, [constF+16];  // 55  Пересылка данных (128 бит)
	movups          xmm6, [constF];     // 33  + MOVDQU
	movups          xmm7, [constF+32];  // 0f
	//	movups          xmm2, dqword ptr constF+48;  // TEST
#endif

} // __asm
//Инструкция movq выполняется за шесть тактов, тогда как для pshufw требуется только два
*/

#ifdef MMX   
__asm {
		emms;
	} // emms; команда обеспечивает переход процессора от исполнения MMX-команд
	// к исполнению обычных команд с плавающей запятой:
	// она устанавливает значение 1 во всех разрядах слова состояния.
/**/
#endif


    
	////for ( int i=0; i<100000; i++ ){    //проверка быстродействия   3.5 sec
	
   	// заполнение массива кэша функции setMatrix_Point
	// в адесах где лежит 255 коэффициент корреляции (0-100) не занесен
	//unsigned char cacheCor[128*34];  // массив кэша коэффициента корреляции по области поиска максимума
	
    memset(cacheCor,255,4352);  //128*32

	
	// Задание области скольжение маски по смещению dlt или по координатам x,y
	if(dlt>0){
		sx0=xSrc0-dlt,    sx1=xSrc0+dlt;
		sy0=ySrc0-dlt,    sy1=ySrc0+dlt;
	}else{  //  dlt=-dlt
		sx0=xSrc0,        sx1=xSrc1;
		sy0=ySrc0,        sy1=ySrc1;
	    //			      mH=sy1 - sy0;
	} // if(dlt>0)
	
	AdrMaxCorX=sx0;
	AdrMaxCorY=sy0;
	
	int X,Y,X0,X1,Y0,Y1,Cor,maxCor,AdrCorX,AdrCorY;
	
	// выбор шага сетки первичного разбиения области поиска максимума коэффициента корреляции
	// высота h и ширина w области поиска максимума коэффициента корреляции
	int w=sx1-sx0;       int h=sy1-sy0;
	int maxwh=w;         if (h > w) { maxwh=h; }
	// stepwh=3 при maxwh<16 (сетка 4x4),  stepwh=4 при maxwh>=16 (сетка 5x5),  stepwh=5 maxwh>=32....          // (sx1-sx0)  (sy1-sy0)
	int stepwh=3 + maxwh/16;  // 4 + 16   // 4 + maxwh/16;
	int dx=64*w/stepwh;       int dy=64*h/stepwh;     // res<<8  *256
	//if (dx < 2) {dx=2;}      if (dy < 2) {dy=2;}
	if (dx < 128) {dx=128;}   if (dy < 128) {dy=128;}
	// int dx=20;             int dy=20;
	// количество узлов сетки stepwh по высоте и ширине одинакого, но величины шагов dx,dy, как правило разные
	DR("//maxwh="<<maxwh<<"  //stepwh="<<stepwh<<END); DR(END);
	//cout<<" "<<stepwh;
	
	// интервал поиска по сетке максимума коэффициента корреляции.
	int SX0=sx0*64;             int SX1=sx1*64;
	int SY0=sy0*64;             int SY1=sy1*64;
	
	// сдвиг периметра сетки к центру области поиска нам пол шага.
	int ddx=dx>>1;            int ddy=dy>>1; // /2
	X0=SX0 + ddx;             Y0=SY0 + ddy;
	X1=SX1 - ddx;             Y1=SY1 - ddy;
	
	DR(END);
	// формирование сетки (обычно 5x5), поиск максимума коэффициента корреляции в сетке
	maxCor=Cor=0;     t=0;
	for ( Y=Y0; Y <= Y1;  Y+=dy ) {   // || maxCor < 100
		//for ( Y=Y0+dy/2; Y <= Y1-dy/2;  Y+=dy ) {   // || maxCor < 100
		y=Y/64;   DR(END);            // p=y*w;  ///////////////////////////
		for ( X=X0; X <= X1; X+=dx ) {
		//for ( X=X0+dx/2; X <= X1-dx/2; X+=dx ) {
			x=X/64;                                        // res>>8  /256
			#ifdef REPORT
			  if(print){
				 /*
                 if(count_==134){int L=1; printP=1;}
                   else{printP=0;}
				 //cout<<"count="<<count_<<" Cor="<<Cor<<endl;
				 if(count_==135){int l=1;}				 				 
				 count_++;
				 */
			  }
			#endif
            
            ///cout_<<"Matrix_Lion_1@@q dlt="<<dlt<<" xSrc0="<<xSrc0<<" xSrc1="<<xSrc1<<" ySrc0="<<ySrc0<<" ySrc1="<<ySrc1<<" mask32.mHOn="<<mask32->mHOn<<endl;
            //cout_<<"Matrix_Lion_1@@q1 x="<<x<<" y="<<y<<" sx0="<<sx0<<" sy0="<<sy0<<" w="<<w<<endl;

			Cor=setMatrix_Point(mask32, x,y, sx0,sy0,w,&ch,printP); t+=1-ch;   //Cor=(Cor*2)/2;
  ///          Cor=(Cor+setMatrix_Point(mask32, x,y, sx0+1,sy0,w,&ch,printP))/2;   //Cor=(Cor+Cor1)/2;      //////////////////////////////
            //int Cor2=setMatrix_Point(mask32, x,y, sx0+2,sy0,w,&ch,printP);   Cor=(Cor+Cor1+Cor2)/3; //////////////////////////////
            
      ////      if ( Cor==-1 )  { correlation=0; AdrMaxCorX=x;  AdrMaxCorY=y; goto maxCorEND; }  /////////////////////////////////////////////////////////////////////////////////////////
            
			if ( Cor > maxCor ) { maxCor=Cor;     AdrCorX=x; AdrCorY=y; }
			if ( maxCor==100 ){correlation=maxCor; AdrMaxCorX=x;  AdrMaxCorY=y; goto maxCorEND;}
#ifdef DEBUGLVL_DRAW
            if(mask32->id==0){drawDataRGB->put(x-32,y,0xffcfcfc0);}
				else{drawDataRGB->put(x-32,y,0xf0ccffcc);}
#endif
#ifdef DEBUGLVL_GREY
				//if(mask32->id==0){drawData[0][y][x-32]/=2;}
				//else{drawData[0][y][x-32]*=0.9;}
#endif			
			DR(Cor<<" ,"<<x<<","<<y<<","<<"\t");
			///	DR(Cor<<","<<AdrCorX<<","<<AdrCorY<<"  "<<"\t");
		} // x
	} // y
	if ( maxCor<25 )  { correlation=1; goto maxCorEND; }   // correlation=maxCor;
	
	DR(END);
	DR("  maxCor="<<maxCor<<"   AdrCorX="<<AdrCorX<<"   AdrCorY="<<AdrCorY<<"   t="<<t<<END);
	
	
	
	// интервалы поиска X0-X1, Y0-Y1 для нахождения max коэф. корр. ( 2*dx на dy*2 ).
	X0=AdrCorX*64-dx;   if (X0<SX0) {X0=SX0;}    // if (X0<sx0) {X0=sx0;}
	X1=AdrCorX*64+dx;   if (X1>SX1) {X1=SX1;}    // if (X1>sx1) {X1=sx1;}
	Y0=AdrCorY*64-dy;   if (Y0<SY0) {Y0=SY0;}    // if (Y0<sy0) {Y0=sy0;}
	Y1=AdrCorY*64+dy;   if (Y1>SY1) {Y1=SY1;}    // if (Y1>sy1) {Y1=sy1;}
	/**/
	
	
	// интерактивное нахождение максимума функции коэффициента корреляции Lion
	// (поиск триадами float). Функция состоит из: блока перемножения масок
	// Off, ON и алгоритма подсчета единиц. Алгоритм находит максимум коэффициента
	// корреляции в прямоугольнмке с координатами sx0,sy0,sx1,sy1; 										int xSrc0,
	
	////////////////////////////////////////////////////////////////////////////////
	DR(END); DR(sx0<<" sx0 "); DR(sx1<<" sx1 "); DR(sy0<<" sy0 "); DR(sy1<<" sy1 "); DR(END);
	
	
	
	// алгоритм находит максимум коэффициента корреляции в пределах от sx0 ,sy0 до sx1,sy1
	
	// абсолютная точность итераций absolute Precision
	Delta=1;  // DR(END);DR(Delta<<" Delta ");DR(END);  // Delta=2-m;  if ( Delta< 1 ) Delta=1;
	// координаты старта поиска
	AdrMaxCorX=AdrCorX;  AdrMaxCorY=AdrCorY;   // t=0;
	
	// цикл чередования поиска по осям X и Y , максимума коэффициента корреляции
	for ( m=0; m<3; m++ ){
		
		// нахождение максимума коэффициента корреляции по оси X
		Lf=0;   Rg=X1-X0;   // интервал поиска X0-X1   // M*(X1-X0)/100;
		DR(END); DR(Lf<<" Lf "); DR(Rg<<" Rg "); DR(END);
		DR(END); DR("AdrMaxCorY="<<AdrMaxCorY<<END);
		for ( n=0; n<7; n++ ){  // 10
			
			LfMem=(Lf+Lf+Rg)/3;  LfxP=(LfMem+X0)/64;  // треть влево (Lf+Lf+Rg)/3; sx0
			// возврат коэффициента корреляции в точке LfxP, AdrMaxCorY.
			LfAmSum=setMatrix_Point(mask32, LfxP,AdrMaxCorY, sx0,sy0,w,&ch, printP); t+=1-ch;
			RgMem=(Lf+Rg+Rg)/3;  RgxP=(RgMem+X0)/64;  // треть вправо  (Lf+Rg+Rg)/3;
			// возврат коэффициента корреляции в точке RgxP, AdrMaxCorY.
			RgAmSum=setMatrix_Point(mask32, RgxP,AdrMaxCorY, sx0,sy0,w,&ch,printP); t+=1-ch;
			
			DR("  LfMem="<<LfMem<<"   RgMem="<<RgMem<<"   LfAmSum="<<LfAmSum<<"   RgAmSum="<<RgAmSum<<END);
			DR("  LfxP="<<LfxP<<"   RgxP="<<RgxP<<"   RgxP-LfxP="<<RgxP-LfxP<<"   t="<<t<<END);
			
			if ( LfAmSum < RgAmSum) { Lf=LfMem; } else { Rg=RgMem; }
			if ( abs(RgxP-LfxP)<Delta || RgAmSum-LfAmSum==0 ) break;   // fabs(Rg-Lf)
			///				 if ( abs(RgxP-LfxP)<Delta ) break;
			
		} // for n
		
		//  максимум коэффициента корреляции (correlation), его адрес
		MaxCorX=(LfAmSum + RgAmSum)/2;   AdrMaxCorX=(LfxP + RgxP)/2;
		DR("//MaxCorX="<<MaxCorX<<"  //AdrMaxCorX="<<AdrMaxCorX<<END); DR(END);
		
		///////	 if ( MaxCorY==MaxCorX || MaxCorY == 100 || MaxCorX==100 ) break;  // ОПОРНАЯ
		if ( MaxCorY==MaxCorX ) break;
		
		// нахождение максимума коэффициента корреляции по оси Y
		Lf=0;   Rg=Y1-Y0;   // интервал поиска Y0-Y1
		DR(END); DR("AdrMaxCorX="<<AdrMaxCorX<<END);
		for ( n=0; n<7; n++ ){ // 10
			
			LfMem=(Lf+Lf+Rg)/3;  LfyP=(LfMem+Y0)/64;  // треть влево (Lf+Lf+Rg)/3;
			// возврат коэффициента корреляции в точке AdrMaxCorX, LfyP.
			LfAmSum=setMatrix_Point(mask32, AdrMaxCorX,LfyP, sx0,sy0,w,&ch,printP); t+=1-ch;
			RgMem=(Lf+Rg+Rg)/3;  RgyP=(RgMem+Y0)/64;  // треть вправо  (Lf+Rg+Rg)/3;
			// возврат коэффициента корреляции в точке AdrMaxCorX, RgyP.
			RgAmSum=setMatrix_Point(mask32, AdrMaxCorX,RgyP, sx0,sy0,w,&ch,printP); t+=1-ch;
			
			DR("  LfMem="<<LfMem<<"   RgMem="<<RgMem<<"   LfAmSum="<<LfAmSum<<"   RgAmSum="<<RgAmSum<<END);
			DR("  LfyP="<<LfyP<<"   RgyP="<<RgyP<<"   RgyP-LfyP="<<RgyP-LfyP<<"   t="<<t<<END);
			// DR("//MaxCorX="<<MaxCorX<<"  //AdrMaxCorX="<<AdrMaxCorX<<END); DR(END);
			
			if ( LfAmSum < RgAmSum) { Lf=LfMem; } else { Rg=RgMem; }
			if ( abs(RgyP-LfyP)<Delta || RgAmSum-LfAmSum==0 ) break;   // fabs(Rg-Lf)
			///				 if ( abs(RgyP-LfyP)<Delta ) break;
			
		} // for n
		
		//  максимум коэффициента корреляции (correlation), его адрес
		MaxCorY=(LfAmSum + RgAmSum)/2;   AdrMaxCorY=(LfyP + RgyP)/2;
		DR("//MaxCorY="<<MaxCorY<<"  //AdrMaxCorY="<<AdrMaxCorY<<END); DR(END);
		
		//			 if ( RgxP-LfxP <= 1 && RgyP-LfyP<= 1 ) break;
		///////	     if ( MaxCorY==MaxCorX || MaxCorY == 100 || MaxCorX==100 ) break;  // ОПОРНАЯ
		if ( MaxCorY==MaxCorX ) break;
		
	} // for m
	
	/**/
	//int correlation=(MaxCorX+MaxCorY)/2;   ////// maxX=AdrAmMAX-border-32;   maxY=yP-border;
	correlation=MaxCorY;    if ( MaxCorX > MaxCorY ) { correlation=MaxCorX; }
	
	////////////////////////////////////////////////////////////////////////////////
#ifdef DEBUGLVL_DRAW
	drawDataRGB->put(AdrMaxCorX-32,AdrMaxCorY,0xff00aa00);    ////red
    //cout_<<" AdrMaxCorX="<<AdrMaxCorX-32<<" AdrMaxCorY="<<AdrMaxCorY<<" MaxCor="<<MaxCorY<<endl;
#endif
	
   //  DT(" maxCorEND="<<maxCor);  DT(" DLT="<<correlation-maxCor);  DT(" correlation="<<correlation<<END);
   //  DT(" stepwh="<<stepwh);
	
maxCorEND:; // переход

	
	// ВИЗУАЛИЗАЦИЯ цифровая
	DR(" //__correlation="<<correlation<<END);
	DR(END<<"// w*h/(t+1)="<<w*h/(t+1)<<",  t="<<t<<END);
	////
	DR(" maxX="<<AdrMaxCorX<<END);
	
	DR(n+1<<"-n- "); DR(Lf<<" Lf ");
	DR(Rg<<" Rg "); DR(Delta<<" Delta "); DR(END);
	
	
	//____________
	/**/
	
	////} // i  //проверка быстродействия
/*
	__asm {
		emms;
	} // emms; команда обеспечивает переход процессора от исполнения MMX-команд
	// к исполнению обычных команд с плавающей запятой:
	// она устанавливает значение 1 во всех разрядах слова состояния.

	//DM("2@@")tm_end=clock(); tm_end-=tm_start; time=tm_end/CLOCKS_PER_SEC;DM("time="<<time<<END);
	//DR("Matrix_Lion_2@@")tm_end=clock(); tm_end-=tm_start1; time=tm_end/CLOCKS_PER_SEC;DR("time="<<time<<END<<END);
*/

	*maxX=AdrMaxCorX;
	*maxY=AdrMaxCorY;
	mask32->correlation=correlation;
	
	return correlation;
	
	
	
	////////////////////////////////////////////////////////////////////////////////
	
	//			 maxX=maxX - border - 32;
	//			 maxY=maxY - border;
	/**/
	
	//------------------------------------------------------------------------------
	
/*
	 //		 int qx=100*w/9;      int qy=100*h/9;
//DR("//qx="<<qx<<"  //qy="<<qy<<END); DR(END);
DR(END);
		 maxCor=0;
		 for ( Y=Y0; Y <= Y1; Y+=qy ) {
		   y=Y/100;  DR(END);      //p=y*dx;
		   for ( X=X0; X <= X1; X+=qx ) {
			 x=X/100;
			 Cor=setMatrix_Point(mask32, x,y, c_out);   t++;
			 if ( Cor > maxCor ) { maxCor=Cor;     AdrCorX=x; AdrCorY=y; }
			 if ( maxCor==100 )  { MaxCorX=maxCor; goto maxCorEND; }
//			 drawDataRGB[0][y][x-32]=0;
			  DR(Cor<<","<<x<<","<<y<<"  "<<"\t");
///			 DR(Cor<<","<<AdrCorX<<","<<AdrCorY<<"  "<<"\t");
		   } // x
		 } // y
		 if ( maxCor<30 )  { goto maxCorEND; }
//		 maxCorEND:;
DR(END);
DR(END);DR("  maxCor="<<maxCor<<"   AdrCorX="<<AdrCorX<<"   AdrCorY="<<AdrCorY<<"   t="<<t<<END);
*/

//------------------------------------------------------------------------------
 /*
			 // ПРИНЦИП РАБОТЫ поиска триадами
// это метод для поиска максимумов и минимумов функции, которая либо сначала
// строго возрастает, затем строго убывает, либо наоборот. Троичный поиск определяет,
// что минимум или максимум не может лежать либо в первой, либо в последней трети
// области, и затем повторяет поиск на оставшихся двух третях.

//  Функция поиска триада (F, влево, вправо, абсолютная точность)
	  function ternarySearch(f, left, right, absolutePrecision)
// left and right are the current bounds; the maximum is between them
// слева и справа являются нынешние границы; максимум между ними
	if (right-left < absolutePrecision) return (left+right)/2
	leftThird := (left*2+right)/3   // Треть влево
	rightThird := (left+right*2)/3  // Треть вправо
	if (f(leftThird) < f(rightThird))
		return ternarySearch(f, leftThird, right, absolutePrecision)
	else
		return ternarySearch(f, left, rightThird, absolutePrecision)
end
  */
/*
	  // работоспособное решение задачи нахождение максимума функции
	  Lf=0;   Rg=X0-X1;   // интервал поиска X0-X1
	 for ( n=0; n<10; n++ ){           d+=M;

		   dt=LfMem=(Lf+Lf+Rg)/3;               // треть влево (Lf+Lf+Rg)/3;
		   LfAmSum=FFFF( dt/4, 2 );             // получение отклика функции
												// в которой ищем максимум
		   dt=RgMem=(Lf+Rg+Rg)/3;               // треть вправо  (Lf+Rg+Rg)/3;
		   RgAmSum=FFFF( dt/4, 2 );             // получение отклика функции

		   DM("  LfMem="<<LfMem<<"   RgMem="<<RgMem<<"   LfAmSum="
		   <<LfAmSum<<"   RgAmSum="<<RgAmSum<<END); DM(Rg-Lf<<" Rg-Lf "); DM(END);

		  if ( LfAmSum < RgAmSum) { Lf=LfMem; } else { Rg=RgMem; }
		  if ( fabs(Rg-Lf)<Delta || RgAmSum-LfAmSum==0 ) break;

	 } // n
*/
//------------------------------------------------------------------------------


}//_____________________________________________________________________________