text
stringlengths 0
1.25M
| meta
stringlengths 47
1.89k
|
|---|---|
SUBROUTINE DUMOD5
C
C MSFC ROUTINE, TO CONVERT NASTRAN TABULAR DATA BLOCKS INTO 2-
C DIMENSIONAL DATA BLOCKS (S.P. REAL ONLY) FOR CONVENIENCE IN
C MANIPULATION AND OUTPUT, SPECIALLY TO BE USED WITH OUTPUT5 AND
C INPUT5.
C
C THIS VERSION WAS MODIFIED BY R. MOORE/MSFC IN JAN. 1989
C TO ALLOW SELECTION OF EITHER 8 OR 16 VALUES PER ELEMENT BY
C USING A 7TH PARAMETER ON DMAP
C
C DUMMOD5 T1,T2,T3,T4,T5/O1,O2,O3,O4,O5/C,N,P1/C,N,P2/C,N,P3
C C,N,P4/C,N,P5/C,N,Q/C,N,R $
C
C TI = INPUT GINO FILE, OEF1, OQG1 OR SIMILAR TYPE OF TABULAR
C DATA BLOCKS
C OI = OUTPUT GINO DATA BLOCK, PACKED, BUT NOT QUITE A REGULAR
C NASTRAN MATRIX BLOCK, SEE PICTURE BELOW
C IF OI IS PURGED (NOT PRESENT), MATRIX BLOCK IS WRITTEN OUT
C TO FORTRAN UNIT 15 (INP1) DIRECTLY, IN BINARY RECORDS,
C BANDED MATRIX FORM (FROM FIRST NON-ZERO TO LAST NON-ZERO
C ELEMENTS), D.R. OR S.P.
C PI = TI TABLE IS MAPPED INTO A PI X 8 2-DIMENSIONAL BLOCKS.
C EACH BLOCK IS PACKED AS A COLUMN OF A MATRIX
C Q = ELEMENT/GRID POINT ID PRINT-PUNCH CONTROL
C = -1, NO PRINT AND NO PUNCH
C = 0, PRINT ONLY, NO PUNCH
C = +1, BOTH PRINT AND PUNCH
C = /2/ CONTENTS OF OUTPUT TAPE, INP1, WILL BE PRINTED OUT
C R = SWITCH TO CHANGE FROM 8 TO 16 VALUES IN TABLE MAPPING
C DEFAULT = 0 WHICH SETS TO 8. R = 1 SETS IT TO 16
C
C CDC USER ONLY - FORTRAN UNIT 11 (UT1) IS USED INSTEAD OF 15 (INP1)
C
C
C |<------ 8 OR 16 ------->|
C ==========================
C / I I \
C / I------- TABULAR --------I \
C P1 I DATA I BLOCK 1 (MATRIX COLUMN 1)
C \ I-------- BLOCKS --------I /
C \ I I /
C ==========================
C / I I \
C / I------------------------I \
C P1 I I BLOCK 2 (MATRIX COLUMN 2)
C
C WRITTEN BY SOMEBODY FOR MARSHALL SPACE FLIGHT CENTER (MSFC).
C MODIFIED BY G.CHAN/UNISYS TO EMPLOY OPEN-CORE SPACE INSTEAD OF
C THE FIXED DIMENSION ARRAYS, AND TO EXPAND FROM ONE INPUT DATA
C BLOCK TO FIVE. IF A CORRESPONDING OUTPUT FILE IS MISSING OR
C PURGED, THE DATA BLOCKS ARE WRITTEN DIRECTLY TO FORTRAN TAPE
C (UNIT 15, INP1) USING OUTPUT5 BINARY FORMAT.
C
C CONTENTS OF INP1 TAPE IF IT IS WRITTEN -
C
C RECORD WORD CONTENT TYPE
C ------ ------ ----------------------------------------
C 0 TAPE HEADER RECORD
C 1-2 'XXXXXXXX', TAPE ID 2*BCD
C 3-4 MACHINE TYPE 2*BCD
C 5-7 DATE 3*INT
C 8 SYSTEM BUFFSIZE INT
C 9 0 (BINARY TAPE) INT
C 1 FIRST MATRIX HEADER
C 1 0 INT
C 2,3 1,1 2*INT
C 4 A DOUBLE PRECISION ZERO D.P.
C 5-10 6 WORDS FROM MATRIX TRAILER 6*INT
C (COL,ROW,FORM,TYPE,MAX,DENSITY-
C TYPE=1 OR 3, DENSITY=1)
C 11-12 MATRIX DMAP NAME 2*BCD
C 2 1 1 (FIRST COLUMN ID) INT
C 2 LOCATION OF FIST NON-ZERO ELEMENT INT
C 3 LOCATION OF LAST NON-ZERO ELEMENT INT
C 4-N S.P. DATA REAL
C 3 1 2 (SECOND COLUMN ID) INT
C 2-N SAME AS RECORD 1
C : 1-N REPEAT FOR MORE COLUMNS
C
C X 1 X (X-TH COLUMN ID, A NUL COLUMN) INT
C 2-3 1,1 INT
C 4-5 0.0,0.0 REAL)
C
C M 1-N LAST COLUMN, SAME AS RECORD 1
C M+1 1 -1 (ELEM) OR -2 (GRID) INT
C 2 1 INT
C 3 LENGTH OF ELEM./GRID ID LIST, L INT
C 4-L+4 LIST OF ELEMENT OR GRID IDS INT
C
C M+2 SECOND MATRIX HEADER
C : : REPEAT 1 THRU (M+1) FOR THE SECOND MATRIX
C
C : : REPEAT, UP TO 5 OUTPUT DATA BLOCKS PER TAPE
C
C COMMENTS FROM G.C. -
C (1) THIS MODULE IS VERY LIMITED IN SCOPE. IT HANDLES ONLY SOME
C SPECIAL TYPES OF TABULAR INPUT DATA BLOCKS. THE (PI X 8) MATRI
C SPACE IS FOR PRINT/PUNCH PURPOSE. THE ORIGINAL PROGRAM SEEMS
C TO BE WRITTEN TO MEET A PARTICULAR JOB REQUIREMENT.
C
C (2) CURRENT MODULE HANDLES ONLY SINGLE PRECISION DATA
C
C (3) THE PROCEDURE TO READ AND/OR WRITE THE TAPE IS COMMONLY USED
C AMONG INPUTT5, OUTPUT5, AND DUMMOD5. ANY PROCEDURE CHANGE
C SHOULD BE MADE TO ALL THREE MODULES.
C
IMPLICIT INTEGER (A-Z)
LOGICAL NONE, DEBUG
INTEGER NAME(2), MCB(7), TRL(7), IZ(8), TEMP(10),
1 EG(2), IR(5001), ID(5001),UNVC(2),MT(2),
2 INFILE(2),OUTFIL(2),DATE(3), SAVE(2,5)
REAL Z, EPSI
DOUBLE PRECISION DZERO, DTEMP
CHARACTER UFM*23, UWM*25, UIM*29
CWKBNB
CHARACTER*80 DSNAMES
COMMON /DSNAME/ DSNAMES(80)
CWKBNE
COMMON /XMSSG / UFM, UWM, UIM
COMMON /ZZZZZZ/ Z(1)
COMMON /MACHIN/ MACH, IJHALF(3),MCHNAM
COMMON /SYSTEM/ IBUF, NOUT, DUMM(88),LPCH
COMMON /PACKX / TYPIN, TYPOUT, II, JJ, INCR
COMMON /BLANK / P(5), Q, R
EQUIVALENCE (Z(1),IZ(1)), (DATE(1),DUMM(13))
CWKBI
DATA IFIRST/0/
DATA TAPE, IRDLMT, ID, IM, IE, XX, EPSI /
1 15, 5000, 5001*0, 1H-,1H=, 4HXXXX, 1.0E-30 /
DATA ZERO, ONE, EG, NAME /
1 0, 1, 4HELEM, 4HGRID, 4HDUMO, 4HD5 /
DATA UNVC, MT / 4HUNIV, 4HAC , 2*4H /
DATA DEBUG, DZERO, SAVE / .FALSE., 0.D0, 10*1H /
C
IF (MACH .EQ. 12) TAPE = 11
CALL PAGE
WRITE (NOUT,5) P,Q,R
5 FORMAT ('0*** MODULE DUMMOD5 CALLED BY USER DMAP ALTER.', /5X,
1 'PARAMETERS ARE P=',5(I5,1H,),5X,'Q=',I5,5X,'R=',I4,/)
I6 OR 8 = 8
IF (R .EQ. 1) I6 OR 8 = 16
INCR = 1
TYPIN = 1
TYPOUT= 1
II = 1
TAPX =-1
TAPP =-1
CORE = KORSZ(Z)
BUF1 = CORE - IBUF + 1
BUF2 = BUF1 - IBUF
CORE = BUF2 - 1
HALF = CORE/2
HALF1 = HALF + 1
CWKBNB
IF ( IFIRST .NE. 0 ) GO TO 1
CLOSE ( UNIT=TAPE)
OPEN ( UNIT=TAPE, FILE=DSNAMES(TAPE), FORM='UNFORMATTED',
1 STATUS='UNKNOWN' )
IFIRST = 1
1 CONTINUE
CWKBNE
C
DO 450 LOOP = 1,5
INPUT = 100 + LOOP
OUTPT = 200 + LOOP
TRL(1)= INPUT
CALL RDTRL (TRL(1))
IF (TRL(1) .LE. 0) GO TO 450
CALL FNAME (INPUT,INFILE)
C
C INPUT DATA PRECISION TYPE IS S.P. ONLY
C
TYPE = 1
C
IF (P(LOOP) .LE. 0) P(LOOP) = PV
PV = P(LOOP)
JJ = P(LOOP)*I6 OR 8
DO 10 J = 1,JJ
10 Z(J+HALF) = 0.0
CALL GOPEN (INPUT,Z(BUF1),0)
MCB(1) = OUTPT
CALL RDTRL (MCB)
NONE = .FALSE.
IF (MCB(1) .LE. 0) NONE = .TRUE.
IF (NONE) GO TO 15
CALL GOPEN (OUTPT,Z(BUF2),1)
CALL FNAME (OUTPT,OUTFIL)
CALL MAKMCB (MCB,OUTPT,0,2,1)
GO TO 20
15 TAPX = TAPX + 1
IF (TAPX .LE. 0) GO TO 20
SAVE(1,TAPX) = INFILE(1)
SAVE(2,TAPX) = INFILE(2)
20 I = 1
NXZH = 0
NXIR = 0
CALL READ (*290,*30,INPUT,TEMP,10,1,M)
NWDS = TEMP(10)
NELTP= TEMP( 3)
C IF (NELTP.GE.11 .AND. NELTP.LE.14) GO TO 320
C CELAS1 CELAS4
GO TO 60
30 CALL MESAGE (-37,0,NAME)
40 CALL READ (*290,*50,INPUT,TEMP,10,1,M)
NWDS = TEMP(10)
IF (TEMP(3) .NE. NELTP) GO TO 60
GO TO 130
50 CALL MESAGE (-61,INPUT,NAME)
C 60 IF (TEMP(3).GE.11 .AND. TEMP(3).LE.14) GO TO 320
C CELAS1 CELAS4
60 CONTINUE
NEWLT = TEMP(3)
NWDS1 = NWDS - 1
NWDS2 = NWDS - 2
DO 70 L = 1,JJ
70 Z(L) = 0.0
DO 80 L = 1,IRDLMT
80 IR(L) = 0
CALL READ (*330,*350,INPUT,IR(1),1,0,M)
KOUNT = 0
DO 90 JSQ = 1,IRDLMT
KOUNT = KOUNT + 1
LOC = NWDS1*JSQ - NWDS2
CALL READ (*330,*350,INPUT,Z(LOC),NWDS1,0,M)
C LAST = LOC + NWDS1 - 1
LAST = KOUNT*I6 OR 8
CALL READ (*330,*100,INPUT,IR(JSQ+1),1,0,M)
90 CONTINUE
100 M = NWDS*KOUNT
IJK = 0
DO 120 J = 1,M,NWDS
IJK = IJK + 1
NROP = (IR(IJK)-1)/10
LOCID = NXIR + IJK
ID(LOCID) = NROP*100 + NEWLT
LOCA = (IJK*I6 OR 8) - (I6 OR 8 -1) + NXZH
LJ = NWDS1*IJK - NWDS1
KK = LOCA + NWDS + HALF
IF (KK .GT. CORE) CALL MESAGE (-8,0,NAME)
DO 110 JM = 1,NWDS1
110 Z(LOCA+JM-1+HALF) = Z(LJ+JM)
120 CONTINUE
NXIR = NXIR + JSQ
NXZH = NXZH + LAST
GO TO 40
130 IF (Q .LT. 1) GO TO 150
IS = IM
KK = HALF + NXZH
WRITE (NOUT,140) IS,I,(Z(J),J=HALF1,KK)
140 FORMAT (' COLUMN',A1,I5, /,(2X,8E16.6))
150 I = I + 1
IF (NONE) GO TO 180
CALL PACK (Z(HALF1),OUTPT,MCB)
GO TO 270
160 IF (TAPX .GT. 0) GO TO 170
C
C WRITE TAPE HEADER AND MATRIX HEADER
C (CURRENTLY, OUTPUT TAPE IS WRITTEN OUT IN SINGLE PRECISION ONLY)
C CHANGE IN 89 VERSION -
C MUST SET MATRIX DENSITY IN MATRIX TRAILER TO NON-ZERO IF INPUT5
C IS TO BE USED
C
TAPX = 1
SAVE(1,TAPX) = INFILE(1)
SAVE(2,TAPX) = INFILE(2)
MT(1) = MCHNAM
IF (MACH .NE. 3) GO TO 162
MT(1) = UNVC(1)
MT(2) = UNVC(2)
162 WRITE (TAPE) XX,XX,MT,DATE,IBUF,ZERO
IF (DEBUG) WRITE (NOUT,165) XX,XX,MT,DATE,IBUF,ZERO
165 FORMAT ('0+++TAPE HEADER/DUMMOD5-',/3X,2A4,1X,2A4,3I4,2I6)
170 IF (TAPX .EQ. TAPP) GO TO 190
TAPP = TAPX
TRL(5) = TYPOUT
TRL(7) = 1
WRITE (TAPE) ZERO,ONE,ONE,DZERO,(TRL(K),K=2,7),INFILE
IF (DEBUG) WRITE (NOUT,175) ZERO,ONE,ONE,DZERO,(TRL(K),K=2,7),
1 INFILE
175 FORMAT (' +++MATRIX HEADER/DUMMOD5- ',3I5,D8.0,6I5,1X,2A4)
GO TO 190
C
180 ASSIGN 270 TO RETN
190 DO 200 JB = II,JJ
CWKBNB 8/94 ALPHA-VMS
ITYPE = NUMTYP( Z(JB+HALF) )
IF ( ITYPE .LE. 1 ) GO TO 200
CWKBNE 8/94 ALPHA-VMS
IF (ABS(Z(JB+HALF)) .GT. EPSI) GO TO 210
200 CONTINUE
WRITE (TAPE) I,ONE,ONE,(ZERO,J=1,TYPE)
IF (DEBUG) WRITE (NOUT,205) I,ONE,ONE,(ZERO,J=1,TYPE)
205 FORMAT (' +++ZEROS/DUMMOD5- ',7I5)
GO TO 265
210 JE = JJ
DO 220 J = II,JJ
CWKBNB 8/94 ALPHA-VMS
ITYPE = NUMTYP( Z(JE+HALF) )
IF ( ITYPE .LE. 1 ) GO TO 220
CWKBNE 8/94 ALPHA-VMS
IF (ABS(Z(JE+HALF)) .GT. EPSI) GO TO 230
220 JE = JE - 1
230 GO TO (260,240,240,250), TYPE
240 IF (MOD(JB,2) .EQ. 0) JB = JB - 1
IF (MOD(JE,2) .EQ. 1) JE = JE + 1
GO TO 260
250 J = MOD(JB,4)
IF (J .EQ. 0) J = 4
JB = JB - J + 1
J = MOD(JE,4)
IF (J .EQ. 0) J = 4
JE = JE - J + 4
260 WRITE (TAPE) I,JB,JE,(Z(J+HALF),J=JB,JE)
IF (DEBUG) WRITE (NOUT,262) I,JB,JE
262 FORMAT (' +++DATA RECORD/DUMMOD5- ',3I5)
265 GO TO RETN, (270,370)
C
270 DO 280 L = 1,JJ
280 Z(L+HALF) = 0.0
NXZH = 0
NXIR = 0
GO TO 60
290 IF (Q .LT. 0) GO TO 300
IS = IE
KK = HALF + NXZH
WRITE (NOUT,140) IS,I,(Z(J),J=HALF1,KK)
300 ASSIGN 370 TO RETN
IF (NONE) GO TO 160
CALL PACK (Z(HALF1),OUTPT,MCB)
MCB(3) = JJ
CALL WRTTRL (MCB)
IF (Q .EQ. 2) WRITE (NOUT,310) (MCB(J),J=1,5)
310 FORMAT (/2X,'MCB=',6I8)
GO TO 370
C 320 CALL READ (*330,*40 ,INPUT,IR(1),1,0,M)
C CALL READ (*330,*350,INPUT, Z(1),1,0,M)
C Z(1) = 0.0
C GO TO 320
330 WRITE (NOUT,340) INFILE
340 FORMAT (/5X,'*** EOF ENCOUNTERED ON INPUT ',2A4,' DATA BLOCK')
GO TO 440
350 WRITE (NOUT,360) INFILE
360 FORMAT (/5X,'*** INPUT ',2A4,'DATA BLOCK IS EMPTY')
GO TO 440
370 IF (.NOT.NONE) WRITE (NOUT,380) UIM,INFILE,OUTFIL
380 FORMAT (A29,', MODULE DUMMOD5 SUCCESSFULLY PROCESSED TABULAR ',
1 'DATA FROM ',2A4,' TO DATA BLOCK ',2A4, /5X,
2 'IN GINO PACKED FORM')
IF (NONE) WRITE (NOUT,390) UIM,INFILE,TAPE
390 FORMAT (A29,', MODULE DUMMOD5 SUCCESSFULLY COPIED TABULAR DATA ',
1 'FROM ',2A4,' TO OUTPUT TAPE', /5X,
3 '(FORTRAN UNIT',I4,') IN BANDED MATRIX FORM')
IF (Q .GT. 0) WRITE (LPCH,400) (ID(J),J=1,NXIR)
400 FORMAT (8I10)
L = EG(1)
IF (NEWLT .GT. 0) GO TO 420
L = EG(2)
DO 410 J = 1,NXIR
410 ID(J) = ID(J)/100
420 WRITE (NOUT,430) L,INFILE,(ID(J),J=1,NXIR)
430 FORMAT (//5X,A4,'-ID ARRAY FOLLOWS/FROM ',2A4, (/5X,15I8))
IF (.NOT.NONE) GO TO 440
I = -1
IF (NEWLT .EQ. 0) I = -2
WRITE (TAPE) I,ONE,NXIR,(ID(J),J=1,NXIR)
IF (DEBUG) WRITE (NOUT,435) I,ONE,NXIR
435 FORMAT (' +++ELEM/GRID ID RECORD/DUMMOD5- ',3I5)
440 CONTINUE
CALL CLOSE (INPUT,1)
IF (.NOT.NONE) CALL CLOSE (OUTPT,1)
450 CONTINUE
C
IF (TAPX .LE. 0) GO TO 590
WRITE (NOUT,455) UIM,TAPE,(SAVE(1,J),SAVE(2,J),J=1,TAPX)
455 FORMAT (A29,', FOLLOWING DATA BLOCKS WERE COPIED TO FORTRAN UNIT',
1 I3,' BY MODULE DUMMOD5', /5X,
2 'USING UNFORMATTED (BINARY) WRITE', /6X,5(2A4,3X))
ENDFILE TAPE
REWIND TAPE
C
C TO READ THE OUTPUT TAPE, Q=/2/
C
IF (IABS(Q) .LT. 2) GO TO 590
CALL PAGE1
K = 1
READ (TAPE,END=575) MCB,J,I
WRITE (NOUT,460) MCB,J
460 FORMAT (//,' TAPEID=',2A4,' FROM ',A4,A2,' MACHINE, DATE',I5,
1 1H/,I2,1H/,I2,' BINARY TAPE. BUFFSIZE=',I7//)
470 READ (TAPE,END=580) I,JB,JE,(Z(J),J=JB,JE)
IF (I) 560,480,500
480 BACKSPACE TAPE
READ (TAPE,END=580) I,JB,JE,DTEMP,(IZ(J),J=1,8)
WRITE (NOUT,490) K,IZ(7),IZ(8),(IZ(J),J=1,6)
490 FORMAT (//,' DATA BLOCK',I3,3X,2A4,' TRAILER=',6I5)
K = K + 1
GO TO 470
500 WRITE (NOUT,510) I,JB,JE,(Z(J),J=JB,JE)
510 FORMAT (//,' COLUMN RECORD =',I3,' JB,JE =',2I5,/,(1X,10E13.6))
GO TO 470
C
560 L = EG(-I)
WRITE (NOUT,570) L,(IZ(J),J=JB,JE)
570 FORMAT (//2X,A4,'-ID LIST -',/,(1X,10I10))
GO TO 470
575 WRITE (NOUT,577)
577 FORMAT (//,' EMPTY TAPE')
580 REWIND TAPE
590 CONTINUE
RETURN
END
|
{"hexsha": "f0f335098f2c8b0483af8956c663a2d5259f6a3b", "size": 15241, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "mis/dumod5.f", "max_stars_repo_name": "ldallolio/NASTRAN-95", "max_stars_repo_head_hexsha": "6d2c175f5b53ebaec4ba2b5186f7926ef9d0ed47", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2016-01-09T14:33:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T11:51:42.000Z", "max_issues_repo_path": "mis/dumod5.f", "max_issues_repo_name": "gassive/NASTRAN95", "max_issues_repo_head_hexsha": "98cb3acaa7990d639360601648498834c7782056", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-01-17T07:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T19:37:44.000Z", "max_forks_repo_path": "mis/dumod5.f", "max_forks_repo_name": "gassive/NASTRAN95", "max_forks_repo_head_hexsha": "98cb3acaa7990d639360601648498834c7782056", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-04-07T20:51:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T14:16:01.000Z", "avg_line_length": 36.9031476998, "max_line_length": 73, "alphanum_fraction": 0.48881307, "num_tokens": 5713}
|
function [Ep,Cp,Eh,F,L,dFdp,dFdpp] = spm_nlsi_GN(M,U,Y)
% Bayesian inversion of nonlinear models - Gauss-Newton/Variational Laplace
% FORMAT [Ep,Cp,Eh,F] = spm_nlsi_GN(M,U,Y)
%
% [Dynamic] MIMO models
%__________________________________________________________________________
%
% M.IS - function name f(P,M,U) - generative model
% This function specifies the nonlinear model:
% y = Y.y = IS(P,M,U) + X0*P0 + e
% where e ~ N(0,C). For dynamic systems this would be an integration
% scheme (e.g. spm_int). spm_int expects the following:
%
% M.f - f(x,u,P,M)
% M.g - g(x,u,P,M)
% M.h - h(x,u,P,M)
% x - state variables
% u - inputs or causes
% P - free parameters
% M - fixed functional forms and parameters in M
%
% M.FS - function name f(y,M) - feature selection
% This [optional] function performs feature selection assuming the
% generalized model y = FS(y,M) = FS(IS(P,M,U),M) + X0*P0 + e
%
% M.P - starting estimates for model parameters [optional]
%
% M.pE - prior expectation - E{P} of model parameters
% M.pC - prior covariance - Cov{P} of model parameters
%
% M.hE - prior expectation - E{h} of log-precision parameters
% M.hC - prior covariance - Cov{h} of log-precision parameters
%
% U.u - inputs (or just U)
% U.dt - sampling interval
%
% Y.y - outputs (samples x observations x ...)
% Y.dt - sampling interval for outputs
% Y.X0 - confounds or null space (over size(y,1) samples or all vec(y))
% Y.Q - q error precision components (over size(y,1) samples or all vec(y))
%
%
% Parameter estimates
%--------------------------------------------------------------------------
% Ep - (p x 1) conditional expectation E{P|y}
% Cp - (p x p) conditional covariance Cov{P|y}
% Eh - (q x 1) conditional log-precisions E{h|y}
%
% log evidence
%--------------------------------------------------------------------------
% F - [-ve] free energy F = log evidence = p(y|f,g,pE,pC) = p(y|m)
%
%__________________________________________________________________________
% Returns the moments of the posterior p.d.f. of the parameters of a
% nonlinear model specified by IS(P,M,U) under Gaussian assumptions.
% Usually, IS is an integrator of a dynamic MIMO input-state-output model
%
% dx/dt = f(x,u,P)
% y = g(x,u,P) + X0*P0 + e
%
% A static nonlinear observation model with fixed input or causes u
% obtains when x = []. i.e.
%
% y = g([],u,P) + X0*P0e + e
%
% but static nonlinear models are specified more simply using
%
% y = IS(P,M,U) + X0*P0 + e
%
% Priors on the free parameters P are specified in terms of expectation pE
% and covariance pC. The E-Step uses a Fisher-Scoring scheme and a Laplace
% approximation to estimate the conditional expectation and covariance of P
% If the free-energy starts to increase, an abbreviated descent is
% invoked. The M-Step estimates the precision components of e, in terms
% of log-precisions. Although these two steps can be thought of in
% terms of E and N steps they are in fact variational steps of a full
% variational Laplace scheme that accommodates conditional uncertainty
% over both parameters and log precisions (c.f. hyperparameters with hyper
% priors)
%
% An optional feature selection can be specified with parameters M.FS.
%
% For generic aspects of the scheme see:
%
% Friston K, Mattout J, Trujillo-Barreto N, Ashburner J, Penny W.
% Variational free energy and the Laplace approximation.
% NeuroImage. 2007 Jan 1;34(1):220-34.
%
% This scheme handels complex data along the lines originally described in:
%
% Sehpard RJ, Lordan BP, and Grant EH.
% Least squares analysis of complex data with applications to permittivity
% measurements.
% J. Phys. D. Appl. Phys 1970 3:1759-1764.
%
%__________________________________________________________________________
% Copyright (C) 2001-2015 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_nlsi_GN.m 7279 2018-03-10 21:22:44Z karl $
% options
%--------------------------------------------------------------------------
try, M.nograph; catch, M.nograph = 0; end
try, M.noprint; catch, M.noprint = 0; end
try, M.Nmax; catch, M.Nmax = 128; end
% figure (unless disabled)
%--------------------------------------------------------------------------
if ~M.nograph
Fsi = spm_figure('GetWin','SI');
end
% check integrator
%--------------------------------------------------------------------------
try
M.IS;
catch
M.IS = 'spm_int';
end
% composition of feature selection and prediction (usually an integrator)
%--------------------------------------------------------------------------
try
y = Y.y;
catch
y = Y;
end
try
% try FS(y,M)
%----------------------------------------------------------------------
try
y = feval(M.FS,y,M);
IS = inline([M.FS '(' M.IS '(P,M,U),M)'],'P','M','U');
% try FS(y)
%------------------------------------------------------------------
catch
y = feval(M.FS,y);
IS = inline([M.FS '(' M.IS '(P,M,U))'],'P','M','U');
end
catch
% otherwise FS(y) = y
%----------------------------------------------------------------------
try
IS = inline([M.IS '(P,M,U)'],'P','M','U');
catch
IS = M.IS;
end
end
% converted to function handle
%--------------------------------------------------------------------------
IS = spm_funcheck(IS);
% paramter update eqation
%--------------------------------------------------------------------------
if isfield(M,'f'), M.f = spm_funcheck(M.f); end
if isfield(M,'g'), M.g = spm_funcheck(M.g); end
if isfield(M,'h'), M.h = spm_funcheck(M.h); end
% size of data (samples x response component x response component ...)
%--------------------------------------------------------------------------
if iscell(y)
ns = size(y{1},1);
else
ns = size(y,1);
end
ny = length(spm_vec(y)); % total number of response variables
nr = ny/ns; % number response components
M.ns = ns; % number of samples M.ns
% initial states
%--------------------------------------------------------------------------
try
M.x;
catch
if ~isfield(M,'n'), M.n = 0; end
M.x = sparse(M.n,1);
end
% input
%--------------------------------------------------------------------------
try
U;
catch
U = [];
end
% initial parameters
%--------------------------------------------------------------------------
try
spm_vec(M.P) - spm_vec(M.pE);
fprintf('\nParameter initialisation successful\n')
catch
M.P = M.pE;
end
% time-step
%--------------------------------------------------------------------------
try
dt = Y.dt;
catch
dt = 1;
end
% precision components Q
%--------------------------------------------------------------------------
try
Q = Y.Q;
if isnumeric(Q), Q = {Q}; end
catch
Q = spm_Ce(ns*ones(1,nr));
end
nh = length(Q); % number of precision components
nq = ny/length(Q{1}); % for compact Kronecker form of M-step
% prior moments (assume uninformative priors if not specifed)
%--------------------------------------------------------------------------
pE = M.pE;
try
pC = M.pC;
catch
np = spm_length(M.pE);
pC = speye(np,np)*exp(16);
end
% confounds (if specified)
%--------------------------------------------------------------------------
try
nb = size(Y.X0,1); % number of bins
nx = ny/nb; % number of blocks
dfdu = kron(speye(nx,nx),Y.X0);
catch
dfdu = sparse(ny,0);
end
if isempty(dfdu), dfdu = sparse(ny,0); end
% hyperpriors - expectation (and initialize hyperparameters)
%--------------------------------------------------------------------------
try
hE = M.hE;
if length(hE) ~= nh
hE = hE + sparse(nh,1);
end
catch
hE = sparse(nh,1) - log(var(spm_vec(y))) + 4;
end
h = hE;
% hyperpriors - covariance
%--------------------------------------------------------------------------
try
ihC = spm_inv(M.hC);
if length(ihC) ~= nh
ihC = ihC*speye(nh,nh);
end
catch
ihC = speye(nh,nh)*exp(4);
end
% unpack covariance
%--------------------------------------------------------------------------
if isstruct(pC);
pC = spm_diag(spm_vec(pC));
end
% dimension reduction of parameter space
%--------------------------------------------------------------------------
V = spm_svd(pC,0);
nu = size(dfdu,2); % number of parameters (confounds)
np = size(V,2); % number of parameters (effective)
ip = (1:np)';
iu = (1:nu)' + np;
% second-order moments (in reduced space)
%--------------------------------------------------------------------------
pC = V'*pC*V;
uC = speye(nu,nu)/1e-8;
ipC = inv(spm_cat(spm_diag({pC,uC})));
% initialize conditional density
%--------------------------------------------------------------------------
Eu = spm_pinv(dfdu)*spm_vec(y);
p = [V'*(spm_vec(M.P) - spm_vec(M.pE)); Eu];
Ep = spm_unvec(spm_vec(pE) + V*p(ip),pE);
% EM
%==========================================================================
criterion = [0 0 0 0];
C.F = -Inf; % free energy
v = -4; % log ascent rate
dFdh = zeros(nh,1);
dFdhh = zeros(nh,nh);
for k = 1:M.Nmax
% time
%----------------------------------------------------------------------
tStart = tic;
% E-Step: prediction f, and gradients; dfdp
%======================================================================
try
% gradients
%------------------------------------------------------------------
[dfdp,f] = spm_diff(IS,Ep,M,U,1,{V});
dfdp = reshape(spm_vec(dfdp),ny,np);
% check for stability
%------------------------------------------------------------------
normdfdp = norm(dfdp,'inf');
revert = isnan(normdfdp) || normdfdp > exp(32);
catch
revert = true;
end
if revert && k > 1
for i = 1:4
% reset expansion point and increase regularization
%--------------------------------------------------------------
v = min(v - 2,-4);
% E-Step: update
%--------------------------------------------------------------
p = C.p + spm_dx(dFdpp,dFdp,{v});
Ep = spm_unvec(spm_vec(pE) + V*p(ip),pE);
% try again
%--------------------------------------------------------------
try
[dfdp,f] = spm_diff(IS,Ep,M,U,1,{V});
dfdp = reshape(spm_vec(dfdp),ny,np);
% check for stability
%----------------------------------------------------------
normdfdp = norm(dfdp,'inf');
revert = isnan(normdfdp) || normdfdp > exp(32);
catch
revert = true;
end
% break
%--------------------------------------------------------------
if ~revert, break, end
end
end
% convergence failure
%----------------------------------------------------------------------
if revert
error('SPM:spm_nlsi_GN','Convergence failure.');
end
% prediction error and full gradients
%----------------------------------------------------------------------
e = spm_vec(y) - spm_vec(f) - dfdu*p(iu);
J = -[dfdp dfdu];
% M-step: Fisher scoring scheme to find h = max{F(p,h)}
%======================================================================
for m = 1:8
% precision and conditional covariance
%------------------------------------------------------------------
iS = sparse(0);
for i = 1:nh
iS = iS + Q{i}*(exp(-32) + exp(h(i)));
end
S = spm_inv(iS);
iS = kron(speye(nq),iS);
Pp = real(J'*iS*J);
Cp = spm_inv(Pp + ipC);
% precision operators for M-Step
%------------------------------------------------------------------
for i = 1:nh
P{i} = Q{i}*exp(h(i));
PS{i} = P{i}*S;
P{i} = kron(speye(nq),P{i});
JPJ{i} = real(J'*P{i}*J);
end
% derivatives: dLdh = dL/dh,...
%------------------------------------------------------------------
for i = 1:nh
dFdh(i,1) = trace(PS{i})*nq/2 ...
- real(e'*P{i}*e)/2 ...
- spm_trace(Cp,JPJ{i})/2;
for j = i:nh
dFdhh(i,j) = - spm_trace(PS{i},PS{j})*nq/2;
dFdhh(j,i) = dFdhh(i,j);
end
end
% add hyperpriors
%------------------------------------------------------------------
d = h - hE;
dFdh = dFdh - ihC*d;
dFdhh = dFdhh - ihC;
Ch = spm_inv(real(-dFdhh));
% update ReML estimate
%------------------------------------------------------------------
dh = spm_dx(dFdhh,dFdh,{4});
dh = min(max(dh,-1),1);
h = h + dh;
% convergence
%------------------------------------------------------------------
dF = dFdh'*dh;
if dF < 1e-2, break, end
end
% E-Step with Levenberg-Marquardt regularization
%======================================================================
% objective function: F(p) = log evidence - divergence
%----------------------------------------------------------------------
L(1) = spm_logdet(iS)*nq/2 - real(e'*iS*e)/2 - ny*log(8*atan(1))/2; ...
L(2) = spm_logdet(ipC*Cp)/2 - p'*ipC*p/2;
L(3) = spm_logdet(ihC*Ch)/2 - d'*ihC*d/2;
F = sum(L);
% record increases and reference log-evidence for reporting
%----------------------------------------------------------------------
try
F0;
if ~M.noprint
fprintf(' actual: %.3e (%.2f sec)\n',full(F - C.F),toc(tStart))
end
catch
F0 = F;
end
% if F has increased, update gradients and curvatures for E-Step
%----------------------------------------------------------------------
if F > C.F || k < 3
% accept current estimates
%------------------------------------------------------------------
C.p = p;
C.h = h;
C.F = F;
C.L = L;
C.Cp = Cp;
% E-Step: Conditional update of gradients and curvature
%------------------------------------------------------------------
dFdp = -real(J'*iS*e) - ipC*p;
dFdpp = -real(J'*iS*J) - ipC;
% decrease regularization
%------------------------------------------------------------------
v = min(v + 1/2,4);
str = 'EM:(+)';
else
% reset expansion point
%------------------------------------------------------------------
p = C.p;
h = C.h;
Cp = C.Cp;
% and increase regularization
%------------------------------------------------------------------
v = min(v - 2,-4);
str = 'EM:(-)';
end
% E-Step: update
%======================================================================
dp = spm_dx(dFdpp,dFdp,{v});
p = p + dp;
Ep = spm_unvec(spm_vec(pE) + V*p(ip),pE);
% Graphics
%======================================================================
if exist('Fsi', 'var')
spm_figure('Select', Fsi)
% reshape prediction if necessary
%------------------------------------------------------------------
e = spm_vec(e);
f = spm_vec(f);
try
e = reshape(e,ns,nr);
f = reshape(f,ns,nr);
end
% subplot prediction
%------------------------------------------------------------------
x = (1:size(e,1))*dt;
xLab = 'time (seconds)';
try
if length(M.Hz) == ns
x = M.Hz;
xLab = 'Frequency (Hz)';
end
end
% plot real or complex predictions
%------------------------------------------------------------------
tstr = sprintf('%s: %i','prediction and response: E-Step',k);
if isreal(spm_vec(y))
subplot(2,1,1)
plot(x,real(f)), hold on
plot(x,real(f + e),':'), hold off
xlabel(xLab)
title(tstr,'FontSize',16)
grid on
else
subplot(2,2,1)
plot(x,real(f)), hold on
plot(x,real(f + e),':'), hold off
xlabel(xLab)
ylabel('real')
title(tstr,'FontSize',16)
grid on
subplot(2,2,2)
plot(x,imag(f)), hold on
plot(x,imag(f + e),':'), hold off
xlabel(xLab)
ylabel('imaginary')
title(tstr,'FontSize',16)
grid on
end
% subplot parameters
%--------------------------------------------------------------
subplot(2,1,2)
bar(full(V*p(ip)))
xlabel('parameter')
tstr = 'conditional [minus prior] expectation';
title(tstr,'FontSize',16)
grid on
drawnow
end
% convergence
%----------------------------------------------------------------------
dF = dFdp'*dp;
if ~M.noprint
fprintf('%-6s: %i %6s %-6.3e %6s %.3e ',str,k,'F:',full(C.F - F0),'dF predicted:',full(dF))
end
criterion = [(dF < 1e-1) criterion(1:end - 1)];
if all(criterion)
if ~M.noprint
fprintf(' convergence\n')
end
break
end
end
if exist('Fsi', 'var')
spm_figure('Focus', Fsi)
end
% outputs
%--------------------------------------------------------------------------
Ep = spm_unvec(spm_vec(pE) + V*C.p(ip),pE);
Cp = V*C.Cp(ip,ip)*V';
Eh = C.h;
F = C.F;
L = C.L;
|
{"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_nlsi_GN.m"}
|
from collections.abc import Iterable
import calendar
import cftime
import numpy as np
import xarray as xr
# units
mwCO2 = 44.
mwC = 12.01
mwAir = 28.966
mon_per_year = 12
g_per_Pg = 1e-15
g_per_kg = 1e3
d_per_yr = 365.25
s_per_d = 86400.
molC_to_PgC = g_per_Pg * mwC
kgCmon_to_PgCyr = mon_per_year * g_per_kg * g_per_Pg
kgCO2mon_to_PgCyr = mon_per_year * g_per_kg * g_per_Pg * mwC / mwCO2
kgCmon_to_molCyr = mon_per_year * g_per_kg / mwC
kgCO2mon_to_molCyr = mon_per_year * g_per_kg / mwCO2
molm2s_to_molCm2yr = d_per_yr * s_per_d
mols_to_PgCyr = mwC * g_per_Pg * d_per_yr * s_per_d
molCyr_to_PgCyr = mwC * g_per_Pg
kgCO2s_to_molCyr = d_per_yr * s_per_d * g_per_kg / mwCO2
str_molCm2yr = 'mol C m$^{-2}$ yr$^{-1}$'
str_PgCyr = 'Pg C yr$^{-1}$'
def eomday(year, month):
"""end of month day"""
if isinstance(year, Iterable):
assert isinstance(month, Iterable)
return np.array([calendar.monthrange(y, m)[-1] for y, m in zip(year, month)])
else:
return calendar.monthrange(year, month)[-1]
def yyyymmdd_to_year_mon_day(yyyymmdd):
year = np.int(yyyymmdd * 1e-4)
month = np.int((yyyymmdd - year * 1e4) * 1e-2)
day = np.int(yyyymmdd - year * 1e4 - month * 1e2)
return year, month, day
def nday_per_year(year):
"""number of days in a year"""
if eomday(year, 2) == 29:
return 366
else:
return 365
def to_datenum(y, m, d, time_units='days since 0001-01-01 00:00:00'):
"""convert year, month, day to number"""
return cftime.date2num(cftime.datetime(y, m, d), units=time_units)
def infer_lat_name(ds):
lat_names = ['latitude', 'lat']
for n in lat_names:
if n in ds:
return n
raise ValueError('could not determine lat name')
def infer_lon_name(ds):
lon_names = ['longitude', 'lon']
for n in lon_names:
if n in ds:
return n
raise ValueError('could not determine lon name')
def lat_weights_regular_grid(lat):
"""
Generate latitude weights for equally spaced (regular) global grids.
Weights are computed as sin(lat+dlat/2)-sin(lat-dlat/2) and sum to 2.0.
"""
dlat = np.abs(np.diff(lat))
np.testing.assert_almost_equal(dlat, dlat[0])
w = np.abs(np.sin(np.radians(lat + dlat[0] / 2.)) - np.sin(np.radians(lat - dlat[0] / 2.)))
if np.abs(lat[0]) > 89.9999:
w[0] = np.abs(1. - np.sin(np.pi / 2. - np.radians(dlat[0] / 2.)))
if np.abs(lat[-1]) > 89.9999:
w[-1] = np.abs(1. - np.sin(np.pi / 2. - np.radians(dlat[0] / 2.)))
return w
def compute_grid_area(ds, check_total=True):
"""Compute the area of grid cells."""
radius_earth = 6.37122e6 # m, radius of Earth
area_earth = 4.0 * np.pi * radius_earth**2 # area of earth [m^2]e
lon_name = infer_lon_name(ds)
lat_name = infer_lat_name(ds)
weights = lat_weights_regular_grid(ds[lat_name])
area = weights + 0.0 * ds[lon_name] # add 'lon' dimension
area = (area_earth / area.sum(dim=(lat_name, lon_name))) * area
if check_total:
np.testing.assert_approx_equal(np.sum(area), area_earth)
return xr.DataArray(area, dims=(lat_name, lon_name), attrs={'units': 'm^2', 'long_name': 'area'})
def ensure_monthly(ds):
np.testing.assert_approx_equal(
actual=(ds.time.diff('time') / np.timedelta64(1, 'D')).mean(),
desired=30.4,
significant=1
)
def ensure_daily(ds):
np.testing.assert_approx_equal(
actual=(ds.time.diff('time') / np.timedelta64(1, 'D')).mean(),
desired=1,
significant=7
)
def normalize_freq(freq):
if freq in ['mon', 'monthly', '1M', 'month_1']:
return '1M'
elif freq in ['day', 'daily', 'D']:
return 'D'
else:
raise ValueError(f'unknown freq: {freq}')
def resample(ds, freq):
"""wrapper to xarray resample, avoiding putting time dim in data"""
freq = normalize_freq(freq)
# determine time vars
time_vars = [v for v in ds.variables if 'time' in ds[v].dims]
other_vars = set(ds.variables) - set(time_vars)
# resample
with xr.set_options(keep_attrs=True):
dsr = ds[time_vars].resample(time=freq).mean()
# copy other vars
for v in other_vars:
dsr[v] = ds[v]
return dsr
def regularize_monthly_time(ds):
"""Produce a time axis for the middle of the month"""
# make sure it's monthly data
ensure_monthly(ds)
# construct time bounds
year = ds.time.values.astype('datetime64[Y]').astype(int) + 1970
month = ds.time.values.astype('datetime64[M]').astype(int) % 12 + 1
lastday = eomday(year, month)
oneday = np.timedelta64(1, 'D')
time_bnds = np.vstack(
([
np.datetime64(f'{y:04d}-{m:02d}-01') - oneday for y, m in zip(year, month)
],
[
np.datetime64(f'{y:04d}-{m:02d}-{d:02d}')
for y, m, d in zip(year, month, lastday)
])).T.astype('datetime64[ns]')
# write time and time_bounds to dataset
ds['time_bnds'] = xr.DataArray(
time_bnds,
dims=('time', 'd2'),
name='time_bnds'
)
ds['time'] = xr.DataArray(
time_bnds.astype('int64').mean(axis=1).astype('datetime64[ns]'),
dims=('time'),
name='time'
)
ds.time.attrs['bounds'] = 'time_bnds'
return ds
def regularize_daily_time(ds):
"""Produce a time axis for the middle of the day"""
# make sure it's daily data
ensure_daily(ds)
# construct time bounds
year = ds.time.values.astype('datetime64[Y]').astype(int) + 1970
month = ds.time.values.astype('datetime64[M]').astype(int) % 12 + 1
day = (ds.time.values.astype('datetime64[D]') - ds.time.values.astype('datetime64[M]') + 1).astype(int)
oneday = np.timedelta64(1, 'D')
time_bnds = np.vstack(
([
np.datetime64(f'{y:04d}-{m:02d}-{d:02d}') for y, m, d in zip(year, month, day)
],
[
np.datetime64(f'{y:04d}-{m:02d}-{d:02d}') + oneday for y, m, d in zip(year, month, day)
]
)).T.astype('datetime64[ns]')
# write time and time_bounds to dataset
ds['time_bnds'] = xr.DataArray(
time_bnds,
dims=('time', 'd2'),
name='time_bnds'
)
ds['time'] = xr.DataArray(
time_bnds.astype('int64').mean(axis=1).astype('datetime64[ns]'),
dims=('time'),
name='time'
)
ds.time.attrs['bounds'] = 'time_bnds'
return ds
def compute_potential_temperature(pressure, temperature, p0=None):
"""compute potential temperate from pressure and temperature
ptemp = temperature * (p0 / pressure)**0.286
p0 is determined based on units of pressure
"""
if p0 is None:
if 'units' in pressure.attrs:
if pressure.attrs['units'].lower() in ['hpa', 'mb', 'millibar', 'millibars']:
p0 = 1000.
elif pressure.attrs['units'].lower() in ['pa']:
p0 = 100000. # default units = Pa
else:
raise ValueError('cannot determine units of pressure')
ptemp = temperature * (p0 / pressure)**0.286
ptemp.name = 'theta'
ptemp.attrs['long_name'] = 'Potential temperature'
if 'units' in temperature.attrs:
ptemp.attrs['units'] = temperature.attrs['units']
return ptemp
def remap_vertical_coord(ds, da_new_levels, da_coord_field, levdim='lev', method='log',
include_coord_field=False):
"""Interpolate to new vertical coordinate.
Parameters
----------
ds : xarray Dataset
xarray dataset with data to be remapped
da_new_levels : xarray DataArray
The levels upon which to remap
da_coord_field : xarray DataArray
4d da_coord_field field
levdim : str, optional
The name of the "level" dimension
method : str
log or linear
include_coord_field : boolean
Remap the coordinate field itself
Returns
-------
dso : xr.Dataset
Interpolated dataset
"""
if method == 'linear':
from metpy.interpolate import interpolate_1d
interpolate = interpolate_1d
elif method == 'log':
from metpy.interpolate import log_interpolate_1d
interpolate = log_interpolate_1d
else:
raise ValueError(f'unknown option for interpolation: {method}')
if isinstance(da_coord_field, str):
da_coord_field = ds[da_coord_field]
# determine output dims
dims_in = da_coord_field.dims
interp_axis = dims_in.index(levdim)
dims_out = dims_in[:interp_axis] + da_new_levels.dims + dims_in[interp_axis+1:]
len_interp_dim = da_coord_field.shape[interp_axis]
assert len_interp_dim == len(da_new_levels), (
f'new_levels must be the same length as the {levdim} '
f'in input data (limitation of application of apply_ufunc)'
)
# loop over vars and interpolate
dso = xr.Dataset()
coords = {c: da_coord_field[c] for c in da_coord_field.coords if c != levdim}
coords[da_new_levels.dims[0]] = da_new_levels
def interp_func(da_coord_field, data_field):
"""Define interpolation function."""
return interpolate(da_new_levels.values, da_coord_field, data_field,
axis=interp_axis)
for name in ds.variables:
da = ds[name]
if name == da_coord_field.name and not include_coord_field:
continue
if da.dims != dims_in:
dso[name] = da.copy()
else:
data = xr.apply_ufunc(interp_func, da_coord_field, da,
output_dtypes=[da.dtype],
dask='parallelized')
dso[name] = xr.DataArray(data.data, dims=dims_out,
attrs=da.attrs, coords=coords)
return dso
|
{"hexsha": "a7d238df511603134effb2ea687558738ead6c5c", "size": 10096, "ext": "py", "lang": "Python", "max_stars_repo_path": "so-co2-airborne-obs/models/calc.py", "max_stars_repo_name": "mgrover1/so-co2-airborne-obs", "max_stars_repo_head_hexsha": "254945a4fcad7817cc0874e5ff53fb692daabadf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "so-co2-airborne-obs/models/calc.py", "max_issues_repo_name": "mgrover1/so-co2-airborne-obs", "max_issues_repo_head_hexsha": "254945a4fcad7817cc0874e5ff53fb692daabadf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "so-co2-airborne-obs/models/calc.py", "max_forks_repo_name": "mgrover1/so-co2-airborne-obs", "max_forks_repo_head_hexsha": "254945a4fcad7817cc0874e5ff53fb692daabadf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-03T18:29:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T18:29:47.000Z", "avg_line_length": 29.6941176471, "max_line_length": 107, "alphanum_fraction": 0.596473851, "include": true, "reason": "import numpy", "num_tokens": 2844}
|
#!/usr/bin/env python3
"""
Copyright (C) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import logging
import sys
from argparse import ArgumentParser, SUPPRESS
from pathlib import Path
from time import perf_counter
import cv2
import numpy as np
from openvino.inference_engine import IECore
sys.path.append(str(Path(__file__).resolve().parents[2] / 'common/python'))
from models import OutputTransform, SegmentationModel, SalientObjectDetectionModel
import monitors
from pipelines import get_user_config, AsyncPipeline
from images_capture import open_images_capture
from performance_metrics import PerformanceMetrics
from helpers import resolution
logging.basicConfig(format='[ %(levelname)s ] %(message)s', level=logging.INFO, stream=sys.stdout)
log = logging.getLogger()
class SegmentationVisualizer:
pascal_voc_palette = [
(0, 0, 0),
(128, 0, 0),
(0, 128, 0),
(128, 128, 0),
(0, 0, 128),
(128, 0, 128),
(0, 128, 128),
(128, 128, 128),
(64, 0, 0),
(192, 0, 0),
(64, 128, 0),
(192, 128, 0),
(64, 0, 128),
(192, 0, 128),
(64, 128, 128),
(192, 128, 128),
(0, 64, 0),
(128, 64, 0),
(0, 192, 0),
(128, 192, 0),
(0, 64, 128)
]
def __init__(self, colors_path=None):
if colors_path:
self.color_palette = self.get_palette_from_file(colors_path)
else:
self.color_palette = self.pascal_voc_palette
self.color_map = self.create_color_map()
def get_palette_from_file(self, colors_path):
with open(colors_path, 'r') as file:
colors = []
for line in file.readlines():
values = line[line.index('(')+1:line.index(')')].split(',')
colors.append([int(v.strip()) for v in values])
return colors
def create_color_map(self):
classes = np.array(self.color_palette, dtype=np.uint8)[:, ::-1] # RGB to BGR
color_map = np.zeros((256, 1, 3), dtype=np.uint8)
classes_num = len(classes)
color_map[:classes_num, 0, :] = classes
color_map[classes_num:, 0, :] = np.random.uniform(0, 255, size=(256-classes_num, 3))
return color_map
def apply_color_map(self, input):
input_3d = cv2.merge([input, input, input])
return cv2.LUT(input_3d, self.color_map)
def overlay_masks(self, frame, objects, output_transform):
# Visualizing result data over source image
return output_transform.resize(np.floor_divide(frame, 2) + np.floor_divide(self.apply_color_map(objects), 2))
class SaliencyMapVisualizer:
def overlay_masks(self, frame, objects, output_transform):
saliency_map = (objects * 255).astype(np.uint8)
saliency_map = cv2.merge([saliency_map, saliency_map, saliency_map])
return output_transform.resize(np.floor_divide(frame, 2) + np.floor_divide(saliency_map, 2))
def build_argparser():
parser = ArgumentParser(add_help=False)
args = parser.add_argument_group('Options')
args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.')
args.add_argument('-m', '--model', help='Required. Path to an .xml file with a trained model.',
required=True, type=Path)
args.add_argument('-at', '--architecture_type', help='Required. Specify the model\'s architecture type.',
type=str, required=False, default='segmentation', choices=('segmentation', 'salient_object_detection'))
args.add_argument('-i', '--input', required=True,
help='Required. An input to process. The input must be a single image, '
'a folder of images, video file or camera id.')
args.add_argument('-d', '--device', default='CPU', type=str,
help='Optional. Specify the target device to infer on; CPU, GPU, HDDL or MYRIAD is '
'acceptable. The demo will look for a suitable plugin for device specified. '
'Default value is CPU.')
common_model_args = parser.add_argument_group('Common model options')
common_model_args.add_argument('-c', '--colors', type=Path,
help='Optional. Path to a text file containing colors for classes.')
infer_args = parser.add_argument_group('Inference options')
infer_args.add_argument('-nireq', '--num_infer_requests', help='Optional. Number of infer requests.',
default=1, type=int)
infer_args.add_argument('-nstreams', '--num_streams',
help='Optional. Number of streams to use for inference on the CPU or/and GPU in throughput '
'mode (for HETERO and MULTI device cases use format '
'<device1>:<nstreams1>,<device2>:<nstreams2> or just <nstreams>).',
default='', type=str)
infer_args.add_argument('-nthreads', '--num_threads', default=None, type=int,
help='Optional. Number of threads to use for inference on CPU (including HETERO cases).')
io_args = parser.add_argument_group('Input/output options')
io_args.add_argument('--loop', default=False, action='store_true',
help='Optional. Enable reading the input in a loop.')
io_args.add_argument('-o', '--output', required=False,
help='Optional. Name of the output file(s) to save.')
io_args.add_argument('-limit', '--output_limit', required=False, default=1000, type=int,
help='Optional. Number of frames to store in output. '
'If 0 is set, all frames are stored.')
io_args.add_argument('--no_show', help="Optional. Don't show output.", action='store_true')
io_args.add_argument('--output_resolution', default=None, type=resolution,
help='Optional. Specify the maximum output window resolution '
'in (width x height) format. Example: 1280x720. '
'Input frame size used by default.')
io_args.add_argument('-u', '--utilization_monitors', default='', type=str,
help='Optional. List of monitors to show initially.')
return parser
def get_model(ie, args):
if args.architecture_type == 'segmentation':
return SegmentationModel(ie, args.model), SegmentationVisualizer(args.colors)
if args.architecture_type == 'salient_object_detection':
return SalientObjectDetectionModel(ie, args.model), SaliencyMapVisualizer()
def main():
metrics = PerformanceMetrics()
args = build_argparser().parse_args()
log.info('Initializing Inference Engine...')
ie = IECore()
plugin_config = get_user_config(args.device, args.num_streams, args.num_threads)
log.info('Loading network...')
model, visualizer = get_model(ie, args)
pipeline = AsyncPipeline(ie, model, plugin_config, device=args.device, max_num_requests=args.num_infer_requests)
cap = open_images_capture(args.input, args.loop)
next_frame_id = 0
next_frame_id_to_show = 0
log.info('Starting inference...')
print("To close the application, press 'CTRL+C' here or switch to the output window and press ESC key")
presenter = None
output_transform = None
video_writer = cv2.VideoWriter()
while True:
if pipeline.is_ready():
# Get new image/frame
start_time = perf_counter()
frame = cap.read()
if frame is None:
if next_frame_id == 0:
raise ValueError("Can't read an image from the input")
break
if next_frame_id == 0:
output_transform = OutputTransform(frame.shape[:2], args.output_resolution)
if args.output_resolution:
output_resolution = output_transform.new_resolution
else:
output_resolution = (frame.shape[1], frame.shape[0])
presenter = monitors.Presenter(args.utilization_monitors, 55,
(round(output_resolution[0] / 4), round(output_resolution[1] / 8)))
if args.output and not video_writer.open(args.output, cv2.VideoWriter_fourcc(*'MJPG'),
cap.fps(), output_resolution):
raise RuntimeError("Can't open video writer")
# Submit for inference
pipeline.submit_data(frame, next_frame_id, {'frame': frame, 'start_time': start_time})
next_frame_id += 1
else:
# Wait for empty request
pipeline.await_any()
if pipeline.callback_exceptions:
raise pipeline.callback_exceptions[0]
# Process all completed requests
results = pipeline.get_result(next_frame_id_to_show)
if results:
objects, frame_meta = results
frame = frame_meta['frame']
start_time = frame_meta['start_time']
frame = visualizer.overlay_masks(frame, objects, output_transform)
presenter.drawGraphs(frame)
metrics.update(start_time, frame)
if video_writer.isOpened() and (args.output_limit <= 0 or next_frame_id_to_show <= args.output_limit-1):
video_writer.write(frame)
next_frame_id_to_show += 1
if not args.no_show:
cv2.imshow('Segmentation Results', frame)
key = cv2.waitKey(1)
if key == 27 or key == 'q' or key == 'Q':
break
presenter.handleKey(key)
pipeline.await_all()
# Process completed requests
for next_frame_id_to_show in range(next_frame_id_to_show, next_frame_id):
results = pipeline.get_result(next_frame_id_to_show)
while results is None:
results = pipeline.get_result(next_frame_id_to_show)
objects, frame_meta = results
frame = frame_meta['frame']
start_time = frame_meta['start_time']
frame = visualizer.overlay_masks(frame, objects, output_transform)
presenter.drawGraphs(frame)
metrics.update(start_time, frame)
if video_writer.isOpened() and (args.output_limit <= 0 or next_frame_id_to_show <= args.output_limit-1):
video_writer.write(frame)
if not args.no_show:
cv2.imshow('Segmentation Results', frame)
key = cv2.waitKey(1)
metrics.print_total()
print(presenter.reportMeans())
if __name__ == '__main__':
sys.exit(main() or 0)
|
{"hexsha": "90a506cce2ced12492972d99f8011a25e2eecb07", "size": 11322, "ext": "py", "lang": "Python", "max_stars_repo_path": "demos/segmentation_demo/python/segmentation_demo.py", "max_stars_repo_name": "APrigarina/open_model_zoo", "max_stars_repo_head_hexsha": "b1ff98b64a6222cf6b5f3838dc0271422250de95", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/segmentation_demo/python/segmentation_demo.py", "max_issues_repo_name": "APrigarina/open_model_zoo", "max_issues_repo_head_hexsha": "b1ff98b64a6222cf6b5f3838dc0271422250de95", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/segmentation_demo/python/segmentation_demo.py", "max_forks_repo_name": "APrigarina/open_model_zoo", "max_forks_repo_head_hexsha": "b1ff98b64a6222cf6b5f3838dc0271422250de95", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-12T07:26:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T07:26:46.000Z", "avg_line_length": 42.8863636364, "max_line_length": 125, "alphanum_fraction": 0.6218865925, "include": true, "reason": "import numpy", "num_tokens": 2515}
|
#!/usr/bin/env python
from __future__ import division
from __future__ import print_function
import datetime
import numpy as np
import sys
import tensorflow as tf
import tensorflow.contrib.metrics as tf_metrics
import tensorflow.contrib.layers as tf_layers
import tensorflow.contrib.seq2seq as tf_seq2seq
import morpho_dataset
#import contrib_seq2seq
#class CharEncoder():
#class WordEncoder():
#class Decoder:
class Network:
MAX_GEN_LEN = 99
EMBEDDING_SIZE = 100
ALIGNMENT_SIZE = 100
def __init__(self,
encoder, decoder,
rnn_cell, rnn_cell_dim,
chars_size, words_size, tags_size,
bow_char, eow_char,
logdir, expname,
threads=1, seed=42):
# Create an empty graph and a session
graph = tf.Graph()
graph.seed = seed
self.session = tf.Session(
graph=graph,
config=tf.ConfigProto(
inter_op_parallelism_threads=threads,
intra_op_parallelism_threads=threads))
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S")
self.summary_writer = tf.summary.FileWriter("{}/{}-{}".format(logdir, timestamp, expname), flush_secs=10)
# Construct the graph
with self.session.graph.as_default():
if rnn_cell == "LSTM":
rnn_cell = tf.contrib.rnn.LSTMCell(rnn_cell_dim)
elif rnn_cell == "GRU":
rnn_cell = tf.contrib.rnn.GRUCell(rnn_cell_dim)
else:
raise ValueError("Unknown rnn_cell {}".format(rnn_cell))
self.global_step = tf.Variable(0, dtype=tf.int64, trainable=False, name="global_step")
self.sentence_lens = tf.placeholder(tf.int32, [None], name="sent_lens")
self.lemma_ids = tf.placeholder(tf.int32, [None, None], name="lemma_ids")
self.lemmas = tf.placeholder(tf.int64, [None, None], name="lemmas")
self.lemma_lens = tf.placeholder(tf.int32, [None], name="lemma_lens")
self.tag_ids = tf.placeholder(tf.int32, [None, None], name="tag_ids")
self.tags = tf.placeholder(tf.int64, [None, None], name="tags")
self.tag_lens = tf.placeholder(tf.int32, [None], name="tag_lens")
self.form_ids = tf.placeholder(tf.int32, [None, None], name="form_ids")
self.forms = tf.placeholder(tf.int64, [None, None], name="forms")
self.form_lens = tf.placeholder(tf.int32, [None], name="form_lens")
self.alphabet_len = chars_size
self.word_vocab_len = words_size
self.tag_vocab_len = tags_size
self.dummy_inputs = tf.zeros([tf.shape(self.sentence_lens)[0], self.MAX_GEN_LEN], name="inference_shape")
self.char_embedding_matrix = tf.get_variable(
"char_embeddings",
[self.alphabet_len, self.EMBEDDING_SIZE],
initializer=tf.random_normal_initializer(stddev=0.01),
dtype=tf.float32)
self.we_lookup_matrix = tf.get_variable(
"we_lookup_matrix",
[self.word_vocab_len, self.EMBEDDING_SIZE],
initializer=tf.random_normal_initializer(stddev=0.01),
dtype=tf.float32,
trainable=True)
self.tag_lookup_matrix = tf.get_variable(
"tag_lookup_matrix",
[self.tag_vocab_len, self.EMBEDDING_SIZE],
initializer=tf.random_normal_initializer(stddev=0.01),
dtype=tf.float32,
trainable=True)
# Encode words
with tf.variable_scope("encoder"):
self.char_embeddings = tf.nn.embedding_lookup(self.char_embedding_matrix, self.lemmas)
ch_rnn_cell = tf.contrib.rnn.GRUCell(rnn_cell_dim)
hidden_states, final_states = tf.nn.bidirectional_dynamic_rnn(
cell_fw=ch_rnn_cell,
cell_bw=ch_rnn_cell,
inputs=self.char_embeddings,
sequence_length=self.lemma_lens,
dtype=tf.float32,
scope="char_BiRNN")
self.sentence_mask = tf.sequence_mask(self.sentence_lens)
# Create decoder input
self.we_encoder_matrix = tf_layers.linear(
tf.concat(axis=1, values=final_states),
self.EMBEDDING_SIZE,
scope="we_encoder_matrix")
self.encoder_output = tf.nn.embedding_lookup(self.we_encoder_matrix, self.lemma_ids)
self.encoder_output = tf.reshape(
tf.boolean_mask(self.encoder_output, self.sentence_mask),
[-1, self.EMBEDDING_SIZE],
name="encoder_output_flat")
# Encode tags
self.tags_embedded = tf.nn.embedding_lookup(self.tag_lookup_matrix, self.tag_ids)
self.tags_embedded = tf.reshape(
tf.boolean_mask(self.tags_embedded, self.sentence_mask),
[-1, self.EMBEDDING_SIZE],
name="tag_embeddings_flat")
# Combine encoder_output with tag embedding
self.encoder_output = tf_layers.linear(
tf.concat(axis=1, values=[self.encoder_output, self.tags_embedded]),
self.EMBEDDING_SIZE,
scope="encoder_output_with_tags")
# Create annotations for attention
self.annot_matrix = tf_layers.linear(
tf.concat(axis=2, values=hidden_states),
self.EMBEDDING_SIZE,
scope="annot_matrix")
self.annotations = tf.nn.embedding_lookup(self.annot_matrix, self.lemma_ids)
self.annotations = tf.reshape(
tf.boolean_mask(self.annotations, self.sentence_mask),
[-1, tf.shape(self.annot_matrix)[1], self.EMBEDDING_SIZE],
name="annotations_flat")
# Reshape form values
self.forms_flat = tf.nn.embedding_lookup(self.forms, self.form_ids)
self.forms_flat = tf.reshape(
tf.boolean_mask(self.forms_flat, self.sentence_mask),
[-1, tf.shape(self.forms)[1]],
name="forms_flat")
self.forms_flat_lens = tf.nn.embedding_lookup(self.form_lens, self.form_ids)
self.forms_flat_lens = tf.reshape(
tf.boolean_mask(self.forms_flat_lens, self.sentence_mask),
[-1],
name="lemmas_flat_lens")
self.attention_fn = None
if decoder in ["individual", "individual_attention", "combined_attention", "combined_attention_birnn"]:
if decoder in ["individual_attention", "combined_attention", "combined_attention_birnn"]:
#self.attention_fn = self.attention_fn_builder(self.annotations)
if decoder == "combined_attention":
word_embeddings = tf.nn.embedding_lookup(self.we_lookup_matrix, self.lemma_ids)
word_embeddings = tf.reshape(
tf.boolean_mask(word_embeddings, self.sentence_mask),
[-1, self.EMBEDDING_SIZE],
name="word_embeddings_flat")
self.encoder_output = tf_layers.linear(
tf.concat(axis=1, values=[self.encoder_output, word_embeddings]),
self.EMBEDDING_SIZE,
scope="combined_encoder_output")
if decoder == "combined_attention_rnn":
else:
raise ValueError("Unknown decoder ({}).".format(decoder))
# Decoder training
with tf.variable_scope("decoder"):
if decoder == "individual":
self.training_logits, states = tf_seq2seq.rnn_decoder(
decoder_inputs=self.forms_flat,
initial_state=self.encoder_output,
cell=rnn_cell)
else:
self.training_logits, states = tf_seq2seq.attention_decoder(
decoder_inputs=self.forms_flat,
initial_state=self.encoder_output,
attention_states=self.annotations,
cell=rnn_cell)
#self.training_logits, states = tf_seq2seq.dynamic_rnn_decoder(
#cell=rnn_cell,
#decoder_fn=self.decoder_fn_train(
# self.encoder_output,
# self.output_fn_builder(),
# self.input_fn_builder(self.char_embedding_matrix, self.attention_fn)),
#inputs=tf.expand_dims(self.forms_flat, -1),
#sequence_length=self.forms_flat_lens)
# Decoder inference
with tf.variable_scope("decoder", reuse=True):
if decoder == "individual":
self.training_logits, states = tf_seq2seq.rnn_decoder(
decoder_inputs=self.dummy_inputs,
initial_state=self.encoder_output,
cell=rnn_cell,
loop_function=decoder_fn)
else:
self.training_logits, states = tf_seq2seq.attention_decoder(
decoder_inputs=self.dummy_inputs,
initial_state=self.encoder_output,
attention_states=self.annotations,
cell=rnn_cell,
loop_function=decoder_fn)
#self.inference_logits, states = tf_seq2seq.dynamic_rnn_decoder(
#cell=rnn_cell,
#decoder_fn=self.decoder_fn_inference(
# self.encoder_output,
# self.output_fn_builder(),
# self.input_fn_builder(self.char_embedding_matrix, self.attention_fn),
#bow_char,
#eow_char,
#self.MAX_GEN_LEN))
self.predictions = tf.argmax(self.inference_logits, 2)
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.training_logits, labels=self.forms_flat[:,1:]))
self.training = tf.train.AdamOptimizer().minimize(loss, global_step=self.global_step)
self.forms_flat = tf.cond(
tf.reduce_max(self.forms_flat_lens) > self.MAX_GEN_LEN,
lambda: tf.slice(self.forms_flat, [0, 0], [-1, self.MAX_GEN_LEN]),
lambda: self.forms_flat)
self.pred_padded = tf.pad(
self.predictions,
[[0,0],[0, self.MAX_GEN_LEN - tf.shape(self.predictions)[1]]],
mode="CONSTANT")
self.forms_padded = tf.pad(
self.forms_flat,
[[0,0],[0, self.MAX_GEN_LEN - tf.shape(self.forms_flat)[1] + 1]],
mode="CONSTANT")
self.char_accuracy = tf_metrics.accuracy(self.pred_padded, self.forms_padded[:,1:])
self.word_accuracy = tf.reduce_mean(tf.reduce_min(tf.cast(tf.equal(self.pred_padded, self.forms_padded[:,1:]), tf.float32), axis=1))
self.summary = {}
for dataset_name in ["train", "dev"]:
self.summary[dataset_name] = tf.summary.merge([tf.summary.scalar(dataset_name+"/loss", loss),
tf.summary.scalar(dataset_name+"/char_accuracy", self.char_accuracy),
tf.summary.scalar(dataset_name+"/word_accuracy", self.word_accuracy)])
# Initialize variables
self.session.run(tf.global_variables_initializer())
if self.summary_writer:
self.summary_writer.add_graph(self.session.graph)
# Simple decoder for training
def decoder_fn_train(self, encoder_state, output_fn, input_fn, name=None):
def decoder_fn(time, cell_state, next_id, cell_output, context_state):
cell_output = output_fn(cell_output)
reuse = True
if cell_state is None: # first call, return encoder_state
cell_state = encoder_state
reuse = None
next_input = input_fn(tf.squeeze(next_id, [1]), cell_state, reuse)
return (None, cell_state, next_input, cell_output, context_state)
return decoder_fn
# TODO: Beam search
# Simple decoder for inference
def decoder_fn_inference(self, encoder_state, output_fn, input_fn,
beginning_of_word="<bow>", end_of_word="<eow>", maximum_length=MAX_GEN_LEN):
batch_size = tf.shape(encoder_state)[0]
def decoder_fn(time, cell_state, cell_input, cell_output, context_state):
cell_output = output_fn(cell_output)
if cell_state is None:
cell_state = encoder_state
next_id = tf.tile([beginning_of_word], [batch_size])
done = tf.zeros([batch_size], dtype=tf.bool)
else:
next_id = tf.argmax(cell_output, 1)
done = tf.equal(next_id, end_of_word)
done = tf.cond(
tf.greater_equal(time, maximum_length), # return true if time >= maxlen
lambda: tf.ones([batch_size], dtype=tf.bool),
lambda: done)
next_input = input_fn(next_id, cell_state, True)
return (done, cell_state, next_input, cell_output, context_state)
return decoder_fn
def decoder_fn_builder(self, encoder_state, output_fn, input_fn,
beginning_of_word="<bow>", end_of_word="<eow>", maximum_length=MAX_GEN_LEN):
def decoder_fn(cell_output, i):
cell_output = output_fn(cell_output)
next_input = tf.argmax(cell_output, 1)
next_input = input_fn(next_input)
return decoder_fn
# TODO: dropout
def attention_fn_builder(self, annotations):
def attention_fn(state):
batch_size = tf.shape(state)[0]
annot_len = tf.shape(annotations)[1]
annot_dim = annotations.get_shape().as_list()[2]
state_dim = state.get_shape().as_list()[1]
e_dim = self.ALIGNMENT_SIZE
a = tf.reshape(annotations, [-1, annot_dim])
U = tf.get_variable(
"annot_weight",
shape=[annot_dim, e_dim],
initializer=tf.random_normal_initializer(stddev=0.1),
trainable=True)
U_b = tf.get_variable(
"annot_bias",
shape=[e_dim],
initializer=tf.constant_initializer(0.1))
W = tf.get_variable(
"state_weight",
shape=[state_dim, e_dim],
initializer=tf.random_normal_initializer(stddev=0.1),
trainable=True)
W_b = tf.get_variable(
"state_bias",
shape=[e_dim],
initializer=tf.constant_initializer(0.1))
v = tf.get_variable(
"lin_combo",
shape=[e_dim, 1],
initializer=tf.random_normal_initializer(stddev=0.1),
trainable=True)
w_res = tf.matmul(state, W) + W_b
w_res = tf.tile(tf.reshape(w_res, [-1, 1]), [1, annot_len])
u_res = tf.matmul(a, U) + U_b
u_res = tf.reshape(u_res, [-1, annot_len])
e = tf.matmul(tf.tanh(tf.reshape(w_res + u_res, [-1, e_dim])), v)
e = tf.reshape(e, [batch_size, -1])
alpha = tf.nn.softmax(e)
alpha = tf.tile(tf.reshape(alpha, [-1, 1]), [1, annot_dim])
c = tf.multiply(alpha, a)
c = tf.reduce_sum(tf.reshape(c, [batch_size, -1, annot_dim]), 1)
C = tf.get_variable(
"attention_weight",
shape=[state_dim, state_dim],
initializer=tf.random_normal_initializer(stddev=0.1),
trainable=True)
C_b = tf.get_variable(
"attention_bias",
shape=[state_dim],
initializer=tf.constant_initializer(0.1))
return tf.add(tf.matmul(c, C), C_b)
return attention_fn
# Output function builder (makes logits out of rnn outputs)
def output_fn_builder(self):
def output_fn(cell_output):
if cell_output is None:
return tf.zeros([self.alphabet_len], tf.float32) # only used for shape inference
else:
return tf_layers.linear(
cell_output,
num_outputs=self.alphabet_len,
scope="decoder_output")
return output_fn
# Input function builder (makes rnn input from word id and cell state)
def input_fn_builder(self, embeddings):
def input_fn(next_id):
return tf.nn.embedding_lookup(embeddings, next_id)
return input_fn
# Input function builder (makes rnn input from word id and cell state)
#def input_fn_builder(self, embeddings, attention_fn=None):
# def input_fn(next_id, cell_state, reuse=True):
# if attention_fn is not None:
# with tf.variable_scope("attention", reuse=reuse):
# return tf.add(
# tf.nn.embedding_lookup(embeddings, next_id),
# attention_fn(cell_state))
# else:
# return tf.nn.embedding_lookup(embeddings, next_id)
#
# return input_fn
@property
def training_step(self):
return self.session.run(self.global_step)
def train(self,
sentence_lens,
forms, form_ids, form_lens,
tags, tag_ids, tag_lens,
lemmas, lemma_ids, lemma_lens):
try:
_, summary, pred = self.session.run([self.training, self.summary, self.predictions],
{self.sentence_lens: sentence_lens,
self.forms: forms,
self.form_ids: form_ids,
self.form_lens: form_lens,
self.tags: tags,
self.tag_ids: tag_ids,
self.tag_lens: tag_lens,
self.lemmas: lemmas,
self.lemma_ids: lemma_ids,
self.lemma_lens: lemma_lens})
except Exception as e:
import pdb; pdb.set_trace()
raise e
self.summary_writer.add_summary(summary["train"], self.training_step)
def evaluate(self,
sentence_lens,
forms, form_ids, form_lens,
tags, tag_ids, tag_lens,
lemmas, lemma_ids, lemma_lens):
try:
ch_acc, w_acc, summary, pred = self.session.run([self.char_accuracy, self.word_accuracy, self.summary, self.predictions],
{self.sentence_lens: sentence_lens,
self.forms: forms,
self.form_ids: form_ids,
self.form_lens: form_lens,
self.tags: tags,
self.tag_ids: tag_ids,
self.tag_lens: tag_lens,
self.lemmas: lemmas,
self.lemma_ids: lemma_ids,
self.lemma_lens: lemma_lens})
except Exception as e:
import pdb; pdb.set_trace()
raise e
self.summary_writer.add_summary(summary["dev"], self.training_step)
return ch_acc, w_acc
def predict(self,
sentence_lens,
lemmas, lemma_ids, lemma_lens,
tags, tag_ids, tag_lens):
predictions = self.session.run([self.predictions],
{self.sentence_lens: sentence_lens,
self.lemmas: lemmas,
self.lemma_ids: lemma_ids,
self.lemma_lens: lemma_lens,
self.tags: tags,
self.tag_ids: tag_ids,
self.tag_lens: tag_lens})
return predictions
if __name__ == "__main__":
# Fix random seed
np.random.seed(42)
# Parse arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", default=64, type=int, help="Batch size.")
parser.add_argument("--data_train", default="data/en-train-gen.txt", type=str, help="Training data file.")
parser.add_argument("--data_dev", default="data/en-dev.txt", type=str, help="Development data file.")
parser.add_argument("--data_test", default="data/en-test-gen.txt", type=str, help="Testing data file.")
parser.add_argument("--epochs", default=10, type=int, help="Number of epochs.")
parser.add_argument("--logdir", default="logs", type=str, help="Logdir name.")
parser.add_argument("--rnn_cell", default="GRU", type=str, help="RNN cell type.")
parser.add_argument("--rnn_cell_dim", default=100, type=int, help="RNN cell dimension.")
parser.add_argument("--encoder", default="simple", type=str, help="Which encoder should we use.")
parser.add_argument("--decoder", default="individual", type=str, help="Which decoder should we use.")
parser.add_argument("--threads", default=1, type=int, help="Maximum number of threads to use.")
args = parser.parse_args()
# Load the data
print("Loading the data.", file=sys.stderr)
data_train = morpho_dataset.MorphoDataset(args.data_train, add_bow_eow=True)
data_dev = morpho_dataset.MorphoDataset(args.data_dev, add_bow_eow=True, train=data_train)
data_test = morpho_dataset.MorphoDataset(args.data_test, add_bow_eow=True, train=data_train)
bow_char = data_train.alphabet.index("<bow>")
eow_char = data_train.alphabet.index("<eow>")
# Construct the network
print("Constructing the network.", file=sys.stderr)
expname = "generator-{}{}-bs{}-epochs{}".format(args.rnn_cell, args.rnn_cell_dim, args.batch_size, args.epochs)
network = Network(rnn_cell=args.rnn_cell,
encoder=args.encoder,
decoder=args.decoder,
rnn_cell_dim=args.rnn_cell_dim,
chars_size=len(data_train.alphabet),
words_size=len(data_train.factors[data_train.FORMS]['words']),
tags_size=len(data_train.factors[data_train.TAGS]['words']),
bow_char=bow_char,
eow_char=eow_char,
logdir=args.logdir,
expname=expname,
threads=args.threads)
# Train
best_dev_ch_acc = 0
best_dev_w_acc = 0
test_predictions = None
for epoch in range(args.epochs):
print("Training epoch {}".format(epoch + 1), file=sys.stderr)
while not data_train.epoch_finished():
sentence_lens, form_ids, charseq_ids, charseqs, charseq_lens = \
data_train.next_batch(args.batch_size, including_charseqs=True)
network.train(
sentence_lens,
charseqs[data_train.FORMS],
charseq_ids[data_train.FORMS],
charseq_lens[data_train.FORMS],
charseqs[data_train.TAGS],
charseq_ids[data_train.TAGS],
charseq_lens[data_train.TAGS],
charseqs[data_train.LEMMAS],
charseq_ids[data_train.LEMMAS],
charseq_lens[data_train.LEMMAS])
sentence_lens, form_ids, charseq_ids, charseqs, charseq_lens = data_dev.whole_data_as_batch(including_charseqs=True)
dev_ch_acc, dev_w_acc = network.evaluate(
sentence_lens,
charseqs[data_train.FORMS],
charseq_ids[data_train.FORMS],
charseq_lens[data_train.FORMS],
charseqs[data_train.TAGS],
charseq_ids[data_train.TAGS],
charseq_lens[data_train.TAGS],
charseqs[data_train.LEMMAS],
charseq_ids[data_train.LEMMAS],
charseq_lens[data_train.LEMMAS])
print("Development ch_acc after epoch {} is {:.2f}, w_acc is {:.2f}.".format(epoch + 1, 100. * dev_ch_acc, 100. * dev_w_acc), file=sys.stderr)
if dev_w_acc > best_dev_w_acc or (dev_w_acc == best_dev_w_acc and dev_ch_acc > best_dev_ch_acc):
best_dev_w_acc = dev_w_acc
best_dev_ch_acc = dev_ch_acc
sentence_lens, form_ids, charseq_ids, charseqs, charseq_lens = data_test.whole_data_as_batch(including_charseqs=True)
test_predictions = network.predict(
sentence_lens,
charseqs[data_train.LEMMAS],
charseq_ids[data_train.LEMMAS],
charseq_lens[data_train.LEMMAS],
charseqs[data_train.TAGS],
charseq_ids[data_train.TAGS],
charseq_lens[data_train.TAGS])
# Print test predictions
test_forms = data_test.factors[data_test.FORMS]['strings'] # We use strings instead of words, because words can be <unk>
test_predictions = list(test_predictions)
for i in range(len(data_test.sentence_lens)):
for j in range(data_test.sentence_lens[i]):
form = ''
pred = test_predictions.pop(0)
for k in range(len(pred)):
if pred[k] == eow_char:
break
form += data_test.alphabet[pred[k]]
print("{}\t{}\t_".format(test_forms[i][j], form))
print()
print("Final best dev set accuracy: {:.2f}".format(100. * best_dev_w_acc))
|
{"hexsha": "338c591776f18cc40f66c3243e016bf89628a641", "size": 29081, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/posteditor.py", "max_stars_repo_name": "varisd/MLFix", "max_stars_repo_head_hexsha": "383d3c71e57eaa0d0829624f6d0d890f9c720567", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-18T02:12:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T02:12:42.000Z", "max_issues_repo_path": "scripts/posteditor.py", "max_issues_repo_name": "varisd/MLFix", "max_issues_repo_head_hexsha": "383d3c71e57eaa0d0829624f6d0d890f9c720567", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-08-05T14:51:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-05T14:51:44.000Z", "max_forks_repo_path": "scripts/posteditor.py", "max_forks_repo_name": "varisd/MLFix", "max_forks_repo_head_hexsha": "383d3c71e57eaa0d0829624f6d0d890f9c720567", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9673539519, "max_line_length": 150, "alphanum_fraction": 0.5117430625, "include": true, "reason": "import numpy", "num_tokens": 5253}
|
[STATEMENT]
lemma bind_returns_result_E2:
assumes "h \<turnstile> f \<bind> g \<rightarrow>\<^sub>r y" and "pure f h"
obtains x where "h \<turnstile> f \<rightarrow>\<^sub>r x" and "h \<turnstile> g x \<rightarrow>\<^sub>r y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>x. \<lbrakk>h \<turnstile> f \<rightarrow>\<^sub>r x; h \<turnstile> g x \<rightarrow>\<^sub>r y\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using assms pure_returns_heap_eq bind_returns_result_E
[PROOF STATE]
proof (prove)
using this:
h \<turnstile> f \<bind> g \<rightarrow>\<^sub>r y
pure f h
\<lbrakk>?h \<turnstile> ?f \<rightarrow>\<^sub>h ?h'; pure ?f ?h\<rbrakk> \<Longrightarrow> ?h = ?h'
\<lbrakk>?h \<turnstile> ?f \<bind> ?g \<rightarrow>\<^sub>r ?y; \<And>x h'. \<lbrakk>?h \<turnstile> ?f \<rightarrow>\<^sub>r x; ?h \<turnstile> ?f \<rightarrow>\<^sub>h h'; h' \<turnstile> ?g x \<rightarrow>\<^sub>r ?y\<rbrakk> \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis
goal (1 subgoal):
1. (\<And>x. \<lbrakk>h \<turnstile> f \<rightarrow>\<^sub>r x; h \<turnstile> g x \<rightarrow>\<^sub>r y\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by metis
|
{"llama_tokens": 468, "file": "Core_DOM_common_preliminaries_Heap_Error_Monad", "length": 2}
|
import numpy as np
import torch
'''
Mixup code from https://github.com/facebookresearch/mixup-cifar10
'''
def mixup_data(x, y, alpha=1.0, use_cuda=True):
'''Returns mixed inputs, pairs of targets, and lambda'''
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
batch_size = x.size()[0]
if use_cuda:
index = torch.randperm(batch_size).cuda()
else:
index = torch.randperm(batch_size)
mixed_x = lam * x + (1 - lam) * x[index, :]
y_a, y_b = y, y[index]
return mixed_x, y_a, y_b, lam
def mixup_criterion(criterion, pred, y_a, y_b, lam):
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)
def model_accuracy(net, dataloader, use_cuda):
total = 0
correct = 0
with torch.no_grad():
for (images, labels) in dataloader:
if use_cuda:
images, labels = images.cuda(), labels.cuda()
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
return 100 * correct / total
'''
Early stopping calculator, based on https://github.com/Bjarten/early-stopping-pytorch
'''
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience=7, verbose=False, delta=0):
"""
Args:
patience (int): How long to wait after last time validation loss improved.
Default: 7
verbose (bool): If True, prints a message for each validation loss improvement.
Default: False
delta (float): Minimum change in the monitored quantity to qualify as an improvement.
Default: 0
"""
self.patience = patience
self.verbose = verbose
self.counter = 0
self.best_score = None
self.early_stop = False
self.val_loss_min = np.Inf
self.delta = delta
def __call__(self, val_loss):
score = -val_loss
if self.best_score is None:
self.best_score = score
elif score < self.best_score + self.delta:
self.counter += 1
print(f'EarlyStopping counter: {self.counter} out of {self.patience}')
if self.counter >= self.patience:
self.early_stop = True
else:
self.best_score = score
self.counter = 0
'''
Cutout code from https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py
'''
class Cutout(object):
"""Randomly mask out one or more patches from an image.
Args:
n_holes (int): Number of patches to cut out of each image.
length (int): The length (in pixels) of each square patch.
"""
def __init__(self, n_holes, length):
self.n_holes = n_holes
self.length = length
def __call__(self, img):
"""
Args:
img (Tensor): Tensor image of size (C, H, W).
Returns:
Tensor: Image with n_holes of dimension length x length cut out of it.
"""
h = img.size(1)
w = img.size(2)
mask = np.ones((h, w), np.float32)
for n in range(self.n_holes):
y = np.random.randint(h)
x = np.random.randint(w)
y1 = np.clip(y - self.length // 2, 0, h)
y2 = np.clip(y + self.length // 2, 0, h)
x1 = np.clip(x - self.length // 2, 0, w)
x2 = np.clip(x + self.length // 2, 0, w)
mask[y1: y2, x1: x2] = 0.
mask = torch.from_numpy(mask)
mask = mask.expand_as(img)
img = img * mask
return img
def train(net, criterion, optimizer, dataloader, use_cuda, mixup, verbose=False):
total = 0
correct = 0
running_loss = 0
losses = []
# Setup the model in training mode
net.train()
for i, (inputs, labels) in enumerate(dataloader, 0):
# get the inputs; data is a list of [inputs, labels]
# use gpu
if use_cuda:
inputs, labels = inputs.cuda(), labels.cuda()
# Use mixup if needed
if mixup:
inputs, labels_a, labels_b, lam = mixup_data(inputs, labels, 1, use_cuda)
outputs = net(inputs)
loss = mixup_criterion(criterion, outputs, labels_a, labels_b, lam)
else:
# forward pass: compute predicted outputs by passing inputs to the model
outputs = net(inputs)
# compute the loss
loss = criterion(outputs, labels)
# zero the parameter gradients
optimizer.zero_grad()
# compute gradients
loss.backward()
# update parameters
optimizer.step()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
if mixup:
correct += (lam * predicted.eq(labels_a.data).sum().float()
+ (1 - lam) * predicted.eq(labels_b.data).sum().float())
else:
correct += (predicted == labels).sum().item()
losses.append(loss.item())
# print every 100 minibatches
running_loss += loss.item()
if (i + 1) % 100 == 0:
if verbose:
print('[%5d] loss: %.3f, accuracy: %.3f' %
(i + 1, running_loss / 2000, (correct / total) * 100))
running_loss = 0.0
accuracy = 100 * correct / total
return np.average(losses), accuracy
def validate(net, criterion, dataloader, use_cuda, mixup):
net.eval()
total = 0
correct = 0
losses = []
for inputs, labels in dataloader:
if use_cuda:
inputs, labels = inputs.cuda(), labels.cuda()
# Use mixup if needed
if mixup:
inputs, labels_a, labels_b, lam = mixup_data(inputs, labels, 1, use_cuda)
outputs = net(inputs)
loss = mixup_criterion(criterion, outputs, labels_a, labels_b, lam)
else:
# forward pass: compute predicted outputs by passing inputs to the model
outputs = net(inputs)
# calculate the loss
loss = criterion(outputs, labels)
losses.append(loss.item())
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
if mixup:
correct += (lam * predicted.eq(labels_a.data).sum().float()
+ (1 - lam) * predicted.eq(labels_b.data).sum().float())
else:
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
return np.average(losses), accuracy
def save_checkpoint(state, filename):
"""
Save the training model
"""
print("Saving", filename)
torch.save(state, filename)
|
{"hexsha": "ee0a0be286acf426926735334deecc21ecd0f2f7", "size": 6844, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "DiscoBroccoli/Classification-of-Image-Data", "max_stars_repo_head_hexsha": "c415f4a220b47efc00f618b760ffa9c52754d6c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils.py", "max_issues_repo_name": "DiscoBroccoli/Classification-of-Image-Data", "max_issues_repo_head_hexsha": "c415f4a220b47efc00f618b760ffa9c52754d6c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.py", "max_forks_repo_name": "DiscoBroccoli/Classification-of-Image-Data", "max_forks_repo_head_hexsha": "c415f4a220b47efc00f618b760ffa9c52754d6c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0175438596, "max_line_length": 97, "alphanum_fraction": 0.5629748685, "include": true, "reason": "import numpy", "num_tokens": 1664}
|
from functools import partial
import numpy as np
from scipy.special import gammainc
from sklearn.neighbors import KernelDensity
from sklearn.utils.extmath import row_norms
from sklearn.utils import check_random_state
from sklearn.model_selection import GridSearchCV
from scipy.stats import multivariate_normal
from melime.generators.gen_base import GenBase
class KDEGen(GenBase):
"""
Modification of KenelDensity from sklearn do sample data around a specific point.
"""
def __init__(self, search_best=True, verbose=False, **kwargs):
super().__init__()
self.manifold = KernelDensity(**kwargs)
if "bandwidth" in kwargs:
self.bandwidth = kwargs["bandwidth"]
self.search_best = search_best
self.verbose = verbose
def fit(
self, x, y=None, sample_weight=None,
):
if self.search_best:
bandwidths = np.linspace(0.005, 0.5, 20)
grid = GridSearchCV(estimator=self.manifold, param_grid={"bandwidth": bandwidths}, cv=5, n_jobs=-1)
grid.fit(x)
self.manifold = grid.best_estimator_
best_params_ = grid.best_params_
self.bandwidth = best_params_["bandwidth"]
if self.verbose:
print("Best Parameter for the KDE:")
print(best_params_)
print("Score:", grid.best_score_)
return self
else:
self.manifold.fit(x, y=None, sample_weight=None)
return self
def predict(self, x, kernel_width=None):
"""
Probability density function - PDF
:param x:
:param kernel_width:
:return:
"""
return np.exp(self.manifold.score_samples(x))
def sample_radius(self, x_exp, r=None, n_min_kernels=10, n_samples=1, random_state=None):
"""Generate random samples from the model.
This is a modification of the method sample from Sklearn KDE.
This modification allows sample instance inside a ball of radius r.
Currently, this is implemented only for gaussian and tophat kernels.
Parameters
----------
x_exp : sample data around x_exp, a ball is define with radius r
r: radius of a ball for sampling the data
n_samples : int, optional
Number of samples to generate. Defaults to 1.
random_state : int, RandomState instance or None. default to None
If int, random_state is the seed used by the random number
generator; If RandomState instance, random_state is the random
number generator; If None, the random number generator is the
RandomState instance used by `np.random`.
Returns
-------
X : array_like, shape (n_samples, n_features)
List of samples.
"""
# TODO: implement sampling for other valid kernel shapes, This TODO is from Sklearn
if self.manifold.kernel not in ["gaussian", "tophat"]:
raise NotImplementedError()
# TODO:
# Select the automatically the ball to find the kernel. Not sure if this is the best strategy.
ind_ = None
if r is None:
len_n_kernel = 0
r = 0.1
while len_n_kernel < n_min_kernels:
r += 0.1
ind_ = self.manifold.tree_.query_radius(x_exp, r=r, return_distance=False)[0].astype(int)
len_n_kernel = len(ind_)
else:
ind_ = self.manifold.tree_.query_radius(x_exp, r=r, return_distance=False)[0].astype(int)
# TODO: Make the selection from the tree structure.
# TODO: For now the three is transformed into numpy array, it is slow.
# TODO: data = np.asarray(self.tree_.data[ind_])
data = np.asarray(self.manifold.tree_.data) # TODO: Coping all the three. Not good!
data = data[ind_]
if data.shape[0] == 0:
return np.empty(data.shape)
rng = check_random_state(random_state)
u = rng.uniform(0, 1, size=n_samples)
if self.manifold.tree_.sample_weight is None:
i = (u * data.shape[0]).astype(np.int64)
else:
# TODO TB: Come back here!
cumsum_weight = np.cumsum(np.asarray(self.manifold.tree_.sample_weight))
sum_weight = cumsum_weight[-1]
i = np.searchsorted(cumsum_weight, u * sum_weight)
if self.manifold.kernel == "gaussian":
return np.atleast_2d(rng.normal(data[i], self.bandwidth))
elif self.manifold.kernel == "tophat":
# we first draw points from a d-dimensional normal distribution,
# then use an incomplete gamma function to map them to a uniform
# d-dimensional tophat distribution.
dim = data.shape[1]
X = rng.normal(size=(n_samples, dim))
s_sq = row_norms(X, squared=True)
correction = gammainc(0.5 * dim, 0.5 * s_sq) ** (1.0 / dim) * self.bandwidth / np.sqrt(s_sq)
return data[i] + X * correction[:, np.newaxis]
def sample(self, n_samples=1, random_state=None):
return self.manifold.sample(n_samples=n_samples, random_state=random_state)
|
{"hexsha": "e1af07a7a7ace65c32a8f0d6d44e444c2e6cc884", "size": 5217, "ext": "py", "lang": "Python", "max_stars_repo_path": "melime/generators/kde_gen.py", "max_stars_repo_name": "elian204/melime", "max_stars_repo_head_hexsha": "aef885fa4b6b02f7bf7294140d78a85fe546b622", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2020-09-15T02:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T17:08:53.000Z", "max_issues_repo_path": "melime/generators/kde_gen.py", "max_issues_repo_name": "elian204/melime", "max_issues_repo_head_hexsha": "aef885fa4b6b02f7bf7294140d78a85fe546b622", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-03T04:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T16:32:25.000Z", "max_forks_repo_path": "melime/generators/kde_gen.py", "max_forks_repo_name": "elian204/melime", "max_forks_repo_head_hexsha": "aef885fa4b6b02f7bf7294140d78a85fe546b622", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-20T16:52:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T10:04:27.000Z", "avg_line_length": 40.1307692308, "max_line_length": 111, "alphanum_fraction": 0.6218133027, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1170}
|
module pub
implicit none
integer yn,kn,ne,N,enn,hn
real eta,dk,de
parameter(yn = 50,hn = 4,kn = 50, ne = 50,N = yn*4,eta = 0.01,dk = 0.01,de = dk)
real,parameter::pi = 3.1415926535
complex,parameter::im = (0.,1.0)
complex Ham(N,N),one(N,N)
!=================================
real m0,mu
real tx,ty
real ax,ay,gamma
complex g1(hn,hn)
complex g2(hn,hn)
complex g3(hn,hn)
!================cheev===============
integer::lda = N
integer,parameter::lwmax = 2*N + N**2
real,allocatable::w(:)
complex,allocatable::work(:)
real,allocatable::rwork(:)
integer,allocatable::iwork(:)
integer lwork
integer lrwork
integer liwork
integer info
end module pub
!================= PROGRAM START ============================
program sol
use pub
integer i1
!====空间申请==================
allocate(w(N))
allocate(work(lwmax))
allocate(rwork(1+5*N+2*N**2))
allocate(iwork(3+5*N))
!======parameter value setting =====
m0 = 1.5
mu = 0
tx = 1.0
ty = 1.0
ax = 1.0
ay = 1.0
do i1 = 1,N
one(i1,i1) = 1 !单位矩阵
end do
call main()
stop
end program sol
!=============================================================================================
subroutine main()
! Calculate edge spectrum function
use pub
integer m1,m2,i1
real kx,ky,omega,re2
complex h1(N,N),h2(N,N)
complex re1
open(30,file="openy-bhz.dat")
!-------------------------------------------------
! y-direction is open
do omega = -3.0,3.0,de
do kx = -pi,pi,dk
re1 = 0
call openy(kx)
h1 = omega*one - ham + im*eta*one
call inv(h1,h2)
do i1 = 1,N
re1 = re1 + h2(i1,i1)
end do
re2 = -2*aimag(re1)/pi/N
write(30,999)kx/pi,omega,re2
end do
write(30,*)" "
end do
close(30)
!---------------------------------------------------------------------
! x-direction is open
open(31,file="openx-bhz.dat")
do omega = -3.0,3.0,de
do ky = -pi,pi,dk
re1 = 0
call openx(ky)
h1 = omega*one - ham + im*eta*one
call inv(h1,h2)
do i1 = 1,N
re1 = re1 + h2(i1,i1)
end do
re2 = -2*aimag(re1)/pi/N
write(31,999)ky/pi,omega,re2
end do
write(31,*)" "
end do
close(31)
999 format(3f11.5)
return
end subroutine main
!======================== Pauli Matrix driect product============================
subroutine Pauli()
use pub
! TI
!=== Kinetic energy
g1(1,1) = 1
g1(2,2) = -1
g1(3,3) = 1
g1(4,4) = -1
!====== SOC-x
g2(1,2) = 1
g2(2,1) = 1
g2(3,4) = -1
g2(4,3) = -1
!====== SOC-y
g3(1,2) = -im
g3(2,1) = im
g3(3,4) = -im
g3(4,3) = im
return
end subroutine Pauli
!==========================================================
subroutine openx(ky)
use pub
real ky
integer m,l,k
call Pauli()
Ham = 0
!========== Positive energy ========
do k = 0,yn-1
if (k == 0) then ! Only right block in first line
do m = 1,hn
do l = 1,hn
Ham(m,l) = (m0-ty*cos(ky))*g1(m,l) + ay*sin(ky)*g3(m,l)
Ham(m,l + hn) = (-tx*g1(m,l) - im*ax*g2(m,l))/2
end do
end do
elseif ( k==yn-1 ) then ! Only left block in last line
do m = 1,hn
do l = 1,hn
Ham(k*hn + m,k*hn + l) = (m0-ty*cos(ky))*g1(m,l) + ay*sin(ky)*g3(m,l)
Ham(k*hn + m,k*hn + l - hn) = -tx*g1(m,l)/2 + im*ax*g2(m,l)/2
end do
end do
else
do m = 1,hn
do l = 1,hn ! k start from 1,matrix block from 2th row
Ham(k*hn + m,k*hn + l) = (m0 - ty*cos(ky))*g1(m,l) + ay*sin(ky)*g3(m,l)
Ham(k*hn + m,k*hn + l + hn) = (-tx*g1(m,l) - im*ax*g2(m,l))/2
Ham(k*hn + m,k*hn + l - hn) = -tx*g1(m,l)/2 + im*ax*g2(m,l)/2
end do
end do
end if
end do
!------------------------
call isHermitian()
! call eigsol()
return
end subroutine openx
!==========================================================
subroutine openy(kx)
use pub
real kx
integer m,l,k
call Pauli()
Ham = 0
!========== Positive energy ========
do k = 0,yn-1
if (k == 0) then ! Only right block in first line
do m = 1,hn
do l = 1,hn
Ham(m,l) = (m0-tx*cos(kx))*g1(m,l) + ax*sin(kx)*g2(m,l)
Ham(m,l + hn) = (-ty*g1(m,l) - im*ay*g3(m,l))/2
end do
end do
elseif ( k==yn-1 ) then ! Only left block in last line
do m = 1,hn
do l = 1,hn
Ham(k*hn + m,k*hn + l) = (m0-tx*cos(kx))*g1(m,l) + ax*sin(kx)*g2(m,l)
Ham(k*hn + m,k*hn + l - hn) = -ty*g1(m,l)/2 + im*ay*g3(m,l)/2
end do
end do
else
do m = 1,hn
do l = 1,hn ! k start from 1,matrix block from 2th row
Ham(k*hn + m,k*hn + l) = (m0-tx*cos(kx))*g1(m,l) + ax*sin(kx)*g2(m,l)
Ham(k*hn + m,k*hn + l + hn) = (-ty*g1(m,l) - im*ay*g3(m,l) )/2
Ham(k*hn + m,k*hn + l - hn) = -ty*g1(m,l)/2 + im*ay*g3(m,l)/2
end do
end do
end if
end do
!---------------------------------
call isHermitian()
! call eigsol()
return
end subroutine openy
!============================================================
subroutine isHermitian()
use pub
integer i,j
do i = 1,N
do j = 1,N
if (Ham(i,j) .ne. conjg(Ham(j,i)))then
open(160,file = 'hermitian.dat')
write(160,*)i,j
write(160,*)Ham(i,j)
write(160,*)Ham(j,i)
write(160,*)"===================="
write(*,*)"Hamiltonian is not hermitian"
stop
end if
end do
end do
close(160)
return
end subroutine isHermitian
!================= 矩阵本征值求解 ==============
subroutine eigSol()
use pub
integer m
lwork = -1
liwork = -1
lrwork = -1
call cheevd('V','Upper',N,Ham,lda,w,work,lwork &
,rwork,lrwork,iwork,liwork,info)
lwork = min(2*N+N**2, int( work( 1 ) ) )
lrwork = min(1+5*N+2*N**2, int( rwork( 1 ) ) )
liwork = min(3+5*N, iwork( 1 ) )
call cheevd('V','Upper',N,Ham,lda,w,work,lwork &
,rwork,lrwork,iwork,liwork,info)
if( info .GT. 0 ) then
open(110,file="mes.dat",status="unknown")
write(110,*)'The algorithm failed to compute eigenvalues.'
close(110)
end if
! open(120,file="eigval.dat")
! do m = 1,N
! write(120,*)w(m)
! end do
! close(120)
return
end subroutine eigSol
!=================================================================
subroutine inv(matin,matout)
use pub
complex,intent(in) :: matin(N,N)
complex:: matout(size(matin,1),size(matin,2))
real:: work2(size(matin,1)) ! work array for LAPACK
integer::info2,ipiv(size(matin,1)) ! pivot indices
! Store A in Ainv to prevent it from being overwritten by LAPACK
matout = matin
! SGETRF computes an LU factorization of a general M-by-N matrix A
! using partial pivoting with row interchanges.
call CGETRF(N,N,matout,N,ipiv,info2)
if (info2.ne.0)then
write(*,*)'Matrix is numerically singular!'
stop
end if
! SGETRI computes the inverse of a matrix using the LU factorization
! computed by SGETRF.
call CGETRI(N,matout,N,ipiv,work2,N,info2)
if (info2.ne.0)then
write(*,*)'Matrix inversion failed!'
stop
end if
return
end subroutine inv
|
{"hexsha": "451575a7b5f1cf5ae40c3ab57ab6555c97dca52b", "size": 8079, "ext": "f90", "lang": "FORTRAN", "max_stars_repo_path": "assets/data/bhz.f90", "max_stars_repo_name": "hongyi-zhao/yxli8023.github.io", "max_stars_repo_head_hexsha": "4fec5ff3ddbf89e84796148aee86cf93d293a99f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T11:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T11:32:16.000Z", "max_issues_repo_path": "assets/data/bhz.f90", "max_issues_repo_name": "hongyi-zhao/yxli8023.github.io", "max_issues_repo_head_hexsha": "4fec5ff3ddbf89e84796148aee86cf93d293a99f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/data/bhz.f90", "max_forks_repo_name": "hongyi-zhao/yxli8023.github.io", "max_forks_repo_head_hexsha": "4fec5ff3ddbf89e84796148aee86cf93d293a99f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8118081181, "max_line_length": 94, "alphanum_fraction": 0.4345834881, "num_tokens": 2639}
|
module GradDescent
using LinearAlgebra
export
Optimizer,
VanillaGradDescent,
Inversedecay,
Momentum,
Adagrad,
Adadelta,
RMSprop,
Adam,
Adamax,
Nadam,
update,
t
include("AbstractOptimizer.jl")
include("VanillaGradDescent.jl")
include("InverseDecayOptimizer.jl")
include("MomentumOptimizer.jl")
include("AdaGradOptimizer.jl")
include("AdaDeltaOptimizer.jl")
include("RMSpropOptimizer.jl")
include("AdamOptimizer.jl")
include("AdamaxOptimizer.jl")
include("NadamOptimizer.jl")
end # module
|
{"hexsha": "3d867d6e6785a8a2fc119040ede69851326c013f", "size": 538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GradDescent.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_stars_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-08-20T00:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:09:32.000Z", "max_issues_repo_path": "src/GradDescent.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_issues_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:33:14.000Z", "max_forks_repo_path": "src/GradDescent.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_forks_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-03T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:48:41.000Z", "avg_line_length": 17.9333333333, "max_line_length": 35, "alphanum_fraction": 0.7342007435, "num_tokens": 148}
|
#include <boost/units/physical_dimensions/inductance.hpp>
|
{"hexsha": "35e1c9a88e631aae998a3410af83c70b0095ef8e", "size": 58, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_units_physical_dimensions_inductance.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_units_physical_dimensions_inductance.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_units_physical_dimensions_inductance.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 29.0, "max_line_length": 57, "alphanum_fraction": 0.8448275862, "num_tokens": 14}
|
'''Train Basic CIFAR-10 model'''
from __future__ import print_function
import logging
import os
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
from lib.cifar_resnet import *
from lib.dataset_utils import *
def evaluate(net, dataloader, criterion, device):
net.eval()
val_loss = 0
val_correct = 0
val_total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(dataloader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = net(inputs)
loss = criterion(outputs, targets)
val_loss += loss.item()
_, predicted = outputs.max(1)
val_total += targets.size(0)
val_correct += predicted.eq(targets).sum().item()
return val_loss / val_total, val_correct / val_total
def train(net, trainloader, validloader, criterion, optimizer, epoch, device,
log, save_best_only=True, best_acc=0, model_path='./model.pt'):
net.train()
train_loss = 0
train_correct = 0
train_total = 0
for batch_idx, (inputs, targets) in enumerate(trainloader):
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = outputs.max(1)
train_total += targets.size(0)
train_correct += predicted.eq(targets).sum().item()
val_loss, val_acc = evaluate(net, validloader, criterion, device)
log.info(' %5d | %.4f, %.4f | %8.4f, %7.4f', epoch,
train_loss / train_total, train_correct / train_total,
val_loss, val_acc)
# Save model weights
if not save_best_only or (save_best_only and val_acc > best_acc):
log.info('Saving model...')
torch.save(net.state_dict(), model_path)
best_acc = val_acc
return best_acc
def main():
# Set experiment id
exp_id = 2
model_name = 'cifar10_resnet_exp%d' % exp_id
# Training parameters
batch_size = 128
epochs = 120
data_augmentation = False
learning_rate = 1e-3
l1_reg = 0
l2_reg = 1e-4
# Subtracting pixel mean improves accuracy
subtract_pixel_mean = False
# Set all random seeds
seed = 2019
np.random.seed(seed)
torch.manual_seed(seed)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Set up model directory
save_dir = os.path.join(os.getcwd(), 'saved_models')
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
model_path = os.path.join(save_dir, model_name + '.h5')
# Get logger
log_file = model_name + '.log'
log = logging.getLogger('train_cifar10')
log.setLevel(logging.DEBUG)
# Create formatter and add it to the handlers
formatter = logging.Formatter(
'[%(levelname)s %(asctime)s %(name)s] %(message)s')
# Create file handler
fh = logging.FileHandler(log_file, mode='w')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)
log.info(log_file)
log.info(('CIFAR10 | exp_id: {}, seed: {}, init_learning_rate: {}, ' +
'batch_size: {}, l2_reg: {}, l1_reg: {}, epochs: {}, ' +
'data_augmentation: {}, subtract_pixel_mean: {}').format(
exp_id, seed, learning_rate, batch_size, l2_reg, l1_reg,
epochs, data_augmentation, subtract_pixel_mean))
log.info('Preparing data...')
trainloader, validloader, testloader = load_cifar10(batch_size,
data_dir='/data',
val_size=0.1,
normalize=False,
augment=True,
shuffle=True,
seed=seed)
log.info('Building model...')
# net = ResNet(BasicBlock, [2, 2, 2, 2])
net = PreActResNet(PreActBlock, [2, 2, 2, 2])
net = net.to(device)
if device == 'cuda':
net = torch.nn.DataParallel(net)
cudnn.benchmark = True
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(
net.parameters(), lr=learning_rate, weight_decay=l2_reg)
lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer, [50, 70, 90], gamma=0.1)
log.info(' epoch | loss , acc | val_loss, val_acc')
best_acc = 0
for epoch in range(epochs):
lr_scheduler.step()
best_acc = train(net, trainloader, validloader, criterion, optimizer,
epoch, device, log, save_best_only=True,
best_acc=best_acc, model_path=model_path)
test_loss, test_acc = evaluate(net, testloader, criterion, device)
log.info('Test loss: %.4f, Test acc: %.4f', test_loss, test_acc)
if __name__ == '__main__':
main()
|
{"hexsha": "8a889ca6bf55a9e59d5d4ec2b81e18dc5bee8147", "size": 5093, "ext": "py", "lang": "Python", "max_stars_repo_path": "train_scripts/train_cifar10.py", "max_stars_repo_name": "chawins/entangle-rep", "max_stars_repo_head_hexsha": "3e9e0d6e7536b0de0e35d7f8717f2ccc8e887759", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-06-30T12:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T20:20:36.000Z", "max_issues_repo_path": "train_scripts/train_cifar10.py", "max_issues_repo_name": "chawins/entangle-rep", "max_issues_repo_head_hexsha": "3e9e0d6e7536b0de0e35d7f8717f2ccc8e887759", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-11T10:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:50:33.000Z", "max_forks_repo_path": "train_scripts/train_cifar10.py", "max_forks_repo_name": "chawins/entangle-rep", "max_forks_repo_head_hexsha": "3e9e0d6e7536b0de0e35d7f8717f2ccc8e887759", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-07-09T14:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T19:18:34.000Z", "avg_line_length": 32.4394904459, "max_line_length": 77, "alphanum_fraction": 0.5929707442, "include": true, "reason": "import numpy", "num_tokens": 1202}
|
from semeval2020.language_models.bertwrapper import BertWrapper
from semeval2020.data_loader.sentence_loader import SentenceLoader
from semeval2020.util import preprocessing
from semeval2020.factory_hub import config_factory
import numpy as np
import torch
import os.path
import tqdm
########################################
# Config Parameter ####################
########################################
paths = config_factory.get_config("ProjectPaths")
language = 'english'
corpus = "corpus2"
base_path = paths["base_path"]
model_string = "bert-base-multilingual-cased"
output_path = paths["bert_embeddings"]
max_length_sentence = 70
padding_length = 100
########################################
# Code ################################
########################################
base_out_path = f"{output_path}{language}/{corpus}/"
os.makedirs(base_out_path, exist_ok=True)
data_loader = SentenceLoader(base_path, language=language, corpus=corpus)
bert_model = BertWrapper(model_string=model_string)
# load the data and the target words
target_words, sentences = data_loader.load()
# prepare the sentences
sentences = preprocessing.sanitized_sentences(sentences, max_len=max_length_sentence)
sentences = preprocessing.filter_for_words(sentences, target_words)
sentences = preprocessing.remove_pos_tagging(sentences, target_words)
sentences = preprocessing.remove_numbers(sentences)
target_words = [preprocessing.remove_pos_tagging_word(word) for word in target_words]
# tokenize sentences
tokenized_target_sentences = bert_model.tokenize_sentences(sentences, target_words)
# allocate dicts to save embeddings and sentences mapped to target words
target_embeddings_dict = {target: [] for target in target_words}
target_sentences_dict = {target: [] for target in target_words}
bert_model.enter_eval_mode()
# compute the embeddings
for tokenized_sentence, target_word_idx_dict in tqdm.tqdm(tokenized_target_sentences):
input_ids = bert_model.get_tokenized_input_ids(tokenized_sentence, padding_length=padding_length)
attention_mask = bert_model.get_attention_mask(input_ids)
input_id_tensor = torch.tensor([input_ids])
attention_mask_tensor = torch.tensor([attention_mask])
target_embeddings = bert_model.compute_embeddings(input_id_tensor, attention_mask_tensor, target_word_idx_dict)
for target, embeddings in target_embeddings.items():
target_embeddings_dict[target].extend(embeddings)
sent = ' '.join(tokenized_sentence)
target_sentences_dict[target].extend([sent] * len(embeddings))
# save the embeddings and the sentences
os.makedirs(base_out_path, exist_ok=True)
for target, target_embeddings in target_embeddings_dict.items():
np.save(f"{base_out_path}{target}", target_embeddings)
|
{"hexsha": "b07cd0204998dbad4f1a01ef81edf3b9adb8f2e4", "size": 2765, "ext": "py", "lang": "Python", "max_stars_repo_path": "semeval2020/main/compute_bert_embeddings.py", "max_stars_repo_name": "DavidRother/semeval2020-task1", "max_stars_repo_head_hexsha": "715f82afb8b282669d59ff610b63714d19db4618", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-12-02T23:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T11:19:28.000Z", "max_issues_repo_path": "semeval2020/main/compute_bert_embeddings.py", "max_issues_repo_name": "DavidRother/semeval2020-task1", "max_issues_repo_head_hexsha": "715f82afb8b282669d59ff610b63714d19db4618", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-24T15:22:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-25T08:08:07.000Z", "max_forks_repo_path": "semeval2020/main/compute_bert_embeddings.py", "max_forks_repo_name": "DavidRother/semeval2020-task1", "max_forks_repo_head_hexsha": "715f82afb8b282669d59ff610b63714d19db4618", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 115, "alphanum_fraction": 0.7486437613, "include": true, "reason": "import numpy", "num_tokens": 550}
|
//////////////////////////////////////////////////////////////////////////////
//
// Released under MIT License
// Copyright (c) 2020 Hernan Perrone (hernan.perrone@gmail.com)
//////////////////////////////////////////////////////////////////////////////
#include <fstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "ft_utils.hpp"
namespace ft {
boost::uuids::uuid getClientUUID(const std::filesystem::path& uuid_file)
{
boost::uuids::uuid ret;
if (std::filesystem::exists(uuid_file) &&
!std::filesystem::is_regular_file(uuid_file)) {
throw std::runtime_error(std::string("UIID file is not a regular file: "
) + (std::string)uuid_file);
}
if (std::filesystem::exists(uuid_file)) {
std::stringstream ss;
std::ifstream is(uuid_file, std::ifstream::in);
ss << is.rdbuf();
is.close();
ss >> ret;
} else {
std::filesystem::create_directories(uuid_file.parent_path());
ret = boost::uuids::random_generator()();
std::ofstream os(uuid_file, std::ifstream::out);
os << to_string(ret);
os.close();
}
return ret;
}
} // ft
|
{"hexsha": "f3ab9b186739241831c1b7078f4694b97408ee27", "size": 1186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ft_utils.cpp", "max_stars_repo_name": "hperrone/file_transfer", "max_stars_repo_head_hexsha": "303e3c139c814685ffc7b13d1a1fc8f03c678fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ft_utils.cpp", "max_issues_repo_name": "hperrone/file_transfer", "max_issues_repo_head_hexsha": "303e3c139c814685ffc7b13d1a1fc8f03c678fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ft_utils.cpp", "max_forks_repo_name": "hperrone/file_transfer", "max_forks_repo_head_hexsha": "303e3c139c814685ffc7b13d1a1fc8f03c678fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7826086957, "max_line_length": 78, "alphanum_fraction": 0.5978077572, "num_tokens": 284}
|
"""dask kernels for :mod:`xarray_extras.interpolate`
.. codeauthor:: Guido Imperiale
"""
from typing import Iterable, Optional, Tuple, Union
import numpy as np
from scipy.interpolate import BSpline, make_interp_spline
from scipy.interpolate._bsplines import _as_float_array, _augknt, _not_a_knot
def _memoryview_safe(x: np.ndarray) -> np.ndarray:
"""Make array safe to run in a Cython memoryview-based kernel. These
kernels typically break down with the error ``ValueError: buffer source
array is read-only`` when running in dask distributed.
"""
if not x.flags.writeable:
if not x.flags.owndata:
x = x.copy(order="C")
x.setflags(write=True)
return x
Boundary = Iterable[Tuple[int, float]]
BCType = Union[Tuple[Boundary, Boundary], str, None]
def make_interp_knots(
x: np.ndarray, k: int = 3, bc_type: BCType = None, check_finite: bool = True
) -> np.ndarray:
"""Compute the knots of the B-spline.
.. note::
This is a temporary implementation that should be moved to the main
scipy library - see `<https://github.com/scipy/scipy/issues/8810>`_.
Parameters
----------
x : array_like, shape (n,)
Abscissas.
k : int, optional
B-spline degree. Default is cubic, k=3.
bc_type : 2-tuple or None
Boundary conditions.
Default is None, which means choosing the boundary conditions
automatically. Otherwise, it must be a length-two tuple where the first
element sets the boundary conditions at ``x[0]`` and the second
element sets the boundary conditions at ``x[-1]``. Each of these must
be an iterable of pairs ``(order, value)`` which gives the values of
derivatives of specified orders at the given edge of the interpolation
interval.
check_finite : bool, optional
Whether to check that the input arrays contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Default is True.
Returns
-------
numpy array with size = x.size + k + 1, representing the B-spline knots.
"""
if k < 2 and bc_type is not None:
raise ValueError("Too much info for k<2: bc_type can only be None.")
x = np.array(x)
if x.ndim != 1 or np.any(x[1:] <= x[:-1]):
raise ValueError("Expect x to be a 1-D sorted array-like.")
if k == 0:
t = np.r_[x, x[-1]]
elif k == 1:
t = np.r_[x[0], x, x[-1]]
elif bc_type is None:
if k == 2:
# OK, it's a bit ad hoc: Greville sites + omit
# 2nd and 2nd-to-last points, a la not-a-knot
t = (x[1:] + x[:-1]) / 2.0
t = np.r_[(x[0],) * (k + 1), t[1:-1], (x[-1],) * (k + 1)]
else:
t = _not_a_knot(x, k)
else:
t = _augknt(x, k)
return _as_float_array(t, check_finite)
def make_interp_coeffs(
x: np.ndarray,
y: np.ndarray,
k: int = 3,
t: Optional[np.ndarray] = None,
bc_type: BCType = None,
axis: int = 0,
check_finite: bool = True,
) -> np.ndarray:
"""Compute the knots of the B-spline.
.. note::
This is a temporary implementation that should be moved to the main
scipy library - see `<https://github.com/scipy/scipy/issues/8810>`_.
See :func:`scipy.interpolate.make_interp_spline` for parameters.
:param t:
Knots array, as calculated by :func:`make_interp_knots`.
- For k=0, must always be None (the coefficients are not a function of
the knots).
- For k=1, set to None if t has been calculated by
:func:`make_interp_knots`; pass a vector if it already existed
before.
- For k=2 and k=3, must always pass either the output of
:func:`make_interp_knots` or a pre-generated vector.
"""
x = _memoryview_safe(x)
y = _memoryview_safe(y)
if t is not None:
t = _memoryview_safe(t)
return make_interp_spline(
x, y, k, t, bc_type=bc_type, axis=axis, check_finite=check_finite
).c
def splev(
x_new: np.ndarray,
t: np.ndarray,
c: np.ndarray,
k: int = 3,
extrapolate: Union[bool, str] = True,
) -> np.ndarray:
"""Generate a BSpline object on the fly from knots and coefficients and
evaluate it on x_new.
See :class:`scipy.interpolate.BSpline` for all parameters.
"""
t = _memoryview_safe(t)
c = _memoryview_safe(c)
x_new = _memoryview_safe(x_new)
spline = BSpline.construct_fast(t, c, k, axis=0, extrapolate=extrapolate)
return spline(x_new)
|
{"hexsha": "2c957e9917123e3431c8a4d5fb24ff010cd85115", "size": 4660, "ext": "py", "lang": "Python", "max_stars_repo_path": "xarray_extras/kernels/interpolate.py", "max_stars_repo_name": "crusaderky/xarray_extras", "max_stars_repo_head_hexsha": "d82be4dab330a2a00cd7664a8dd77b60d870cee5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-05-07T09:53:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T07:14:12.000Z", "max_issues_repo_path": "xarray_extras/kernels/interpolate.py", "max_issues_repo_name": "crusaderky/xarray_extras", "max_issues_repo_head_hexsha": "d82be4dab330a2a00cd7664a8dd77b60d870cee5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-05-30T10:02:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T20:00:56.000Z", "max_forks_repo_path": "xarray_extras/kernels/interpolate.py", "max_forks_repo_name": "crusaderky/xarray_extras", "max_forks_repo_head_hexsha": "d82be4dab330a2a00cd7664a8dd77b60d870cee5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8169014085, "max_line_length": 80, "alphanum_fraction": 0.628111588, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1276}
|
The Davis Daytime Toastmasters Community Organizations club is a safe environment for you to become the Public Speaking speaker and leader you want to be. As of September 2013, we are a mix of beginning and intermediate Toastmasters, with about 8 to 10 members in attendance each week.
The Davis Daytime Toastmasters club is part of http://www.toastmasters.org/ Toastmasters International, a NonProfit Organizations 501(c)(3) nonprofit educational organization based in Rancho Santa Margarita, California. Through club activities and conferences, Toastmasters helps its members improve their communication and leadership skills while fostering selfconfidence and personal growth.
The Daytimers club was chartered by http://www.westyost.com/ West Yost Associates, a local water resources engineering firm, as a training tool for the employees to improve their communication and better themselves. As such, the meetings are held at the West Yost office. However, we are a public club, and more than half of our members are from the community at large. All are welcome to visit and check us out!
The Daytimers would like to thank the Davis Toastmasters Town and Gown Toastmasters for all their help in getting started as a club. The Town and Gown meets on Tuesday evenings.
Here are some photos of the building we meet in:
20131223 16:09:07 nbsp The Davis Daytime Toastmasters club is moving the January 1, 2014 meeting to January 8, 2014 in observation of the New Years Day holiday. The club will return to its normal 1st and 3rd Wednesday of each month schedule in February 2014. Users/TTT
|
{"hexsha": "ca8eb2a29d8b6e7910737385d17081331eba977d", "size": 1605, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "lab/davisWiki/Davis_Daytime_Toastmasters.f", "max_stars_repo_name": "voflo/Search", "max_stars_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab/davisWiki/Davis_Daytime_Toastmasters.f", "max_issues_repo_name": "voflo/Search", "max_issues_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab/davisWiki/Davis_Daytime_Toastmasters.f", "max_forks_repo_name": "voflo/Search", "max_forks_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 94.4117647059, "max_line_length": 415, "alphanum_fraction": 0.8074766355, "num_tokens": 352}
|
#script was heavily based on ipython notebook created by Steve Crawford
import glob
import os
import numpy as np
from astropy.io import fits
from astropy import units as u
from ccdproc import CCDData
from pyhrs import create_masterbias
from pyhrs import create_masterflat
from pyhrs import normalize_image
from pyhrs import create_orderframe
from scipy import ndimage as nd
from astropy import modeling as mod
import argparse
import gc
def create_list_folder():
"""Creates a list of HRS files that are in the current directory
Parameters
----------
Returns
-------
blue_files: list of str
List of HRS blue frames in the running directory
red_files: list of str
List of HRS red frames in the running directory
"""
path=os.getcwd()+os.sep #get current directory
blue_files = glob.glob('%sH201*.fits'%path)
red_files = glob.glob('%sR201*.fits'%path)
return blue_files,red_files
def divide_list(list_file):
"""Checks if every element in provided list is a HRS image and divides the original list into red and blue frames lists
Parameters
----------
list_file: list of str
List containing names of HRS files
Returns
-------
blue_files: list of str
List of HRS blue frames in the running directory
red_files: list of str
List of HRS red frames in the running directory
"""
blue_files=[]
red_files=[]
f=open(list_file,"r")
for line in f.readlines():
line_s=line.replace("\n", "")
if (line_s[-5:]==".fits") and ("H201" in line_s) and not("pH201" in line_s):
blue_files.append(line_s)
elif (line_s[-5:]==".fits") and ("R201" in line_s) and not("pR201" in line_s):
red_files.append(line_s)
else:
print("This does not look like a name of a raw HRS file: %s"%line_s)
f.close()
return blue_files,red_files
def write_bias_flat_arc(files):
"""Creates masterbias masterflat and masterarc files
Parameters
----------
files: list of str
List containing names of HRS files
Returns
-------
Writes HBIAS.fits RBIAS.fits HFLAT.fits RFLAT.fits HARC.fits and RARC.fits in the current directory
"""
#create a list of calibration frames
hbias_list = []
rbias_list = []
hflat_list = []
rflat_list = []
harc_list = []
rarc_list = []
for img in files:
data, header = fits.getdata(img, header=True)
if not ('DATASEC' in header):
#just adding 'DATASEC' keyword if missing
header['DATASEC']=header['AMPSEC']
fits.writeto(img, data, header, clobber=True)
if header['OBSTYPE']=='Bias' and header['DETNAM']=='HBDET':
hbias_list.append(img)
if header['OBSTYPE']=='Bias' and header['DETNAM']=='HRDET':
rbias_list.append(img)
if 'EXPTYPE' in header:
if header['EXPTYPE']=='Flat field' and header['DETNAM']=='HBDET':
hflat_list.append(img)
if header['EXPTYPE']=='Flat field' and header['DETNAM']=='HRDET':
rflat_list.append(img)
if header['CCDTYPE']=='Arc' and header['DETNAM']=='HBDET':
harc_list.append(img)
if header['CCDTYPE']=='Arc' and header['DETNAM']=='HRDET':
rarc_list.append(img)
else:
if header['CCDTYPE']=='Flat field' and header['DETNAM']=='HBDET':
hflat_list.append(img)
if header['CCDTYPE']=='Flat field' and header['DETNAM']=='HRDET':
rflat_list.append(img)
if header['CCDTYPE']=='Arc' and header['DETNAM']=='HBDET':
harc_list.append(img)
if header['CCDTYPE']=='Arc' and header['DETNAM']=='HRDET':
rarc_list.append(img)
if not(hbias_list==[]):
master_bluebias = create_masterbias(hbias_list)
master_bluebias.write('HBIAS.fits', clobber=True)
print("\nCreated blue masterbias\n")
#this step is just inserted for debugging purposes
master_bluebias = CCDData.read('HBIAS.fits', ignore_missing_end=True)
gc.collect()
if not(hflat_list==[]):
master_blueflat = create_masterflat(hflat_list) #if bias was created it should probably be "create_masterflat(hflat_list,masterbias=master_bluebias)", but it generates an error
master_blueflat.write('HFLAT.fits', clobber=True)
del master_blueflat
gc.collect()
print("\nCreated blue masterflat\n")
if not(harc_list==[]):
master_bluearc = create_masterflat(harc_list) #if bias was created it should probably be "create_masterflat(hflat_list,masterbias=master_bluebias)", but it generates an error
master_bluearc.write('HARC.fits', clobber=True)
del master_bluearc
gc.collect()
print("\nCreated blue masterarc\n")
del master_bluebias
gc.collect()
if not(rbias_list==[]):
master_redbias = create_masterbias(rbias_list)
master_redbias.write('RBIAS.fits', clobber=True)
print("\nCreated red masterbias\n")
#this step is just inserted for debugging purposes
master_redbias = CCDData.read('RBIAS.fits', ignore_missing_end=True)
gc.collect()
if not(rflat_list==[]):
master_redflat = create_masterflat(rflat_list)#if bias was created it should probably be "create_masterflat(rflat_list,masterbias=master_rluebias)", but it generates an error
master_redflat.write('RFLAT.fits', clobber=True)
del master_redflat
gc.collect()
print("\nCreated red masterflat\n")
if not(rarc_list==[]):
master_redarc = create_masterflat(rarc_list)
master_redarc.write('RARC.fits', clobber=True)
del master_redarc
gc.collect()
print("\nCreated red masterarc\n")
del master_redbias
gc.collect()
return True
def write_orderframe(f_limit_red=1000.0,f_limit_blue=1000.0,interactive=True):
"""Creates blue and red order frames
Parameters
----------
f_limit_red: float
Limiting value for detecting orders in the red flat. Value should be higher than counts of the background light, but lower than in most part of any order.
f_limit_blue: float
Same as f_limit_red, but for blue frame.
interactive: bool
If true the program will display the flat frames in DS9 and it will ask the user to enter values of f_limit_red and f_limit_blue
Returns
-------
Writes HNORM.fits RNORM.fits HORDER.fits and RORDER.fits in the current directory
"""
print("Creating normalized red flat")
if interactive:
import pyds9
d=pyds9.DS9()
d.set("file RFLAT.fits")
print("Flat opened in DS9")
check=True
while check:
f_limit_red=raw_input("Enter a count number that is higher than background light, but lower than in most part of any order: ")
try:
f_limit_red=float(f_limit_red)
check=False
except ValueError:
print("\nError: Entered value should be a float ")
master_redflat = CCDData.read('RFLAT.fits', ignore_missing_end=True)
image = nd.filters.maximum_filter(master_redflat, 10)
mask = (image > f_limit_red)
norm = normalize_image(image, mod.models.Legendre1D(10), mask=mask)
norm[norm < f_limit_red]=0
hdu = fits.PrimaryHDU(norm)
hdu.writeto('RNORM.fits', clobber=True)
#create the initial detection kernal
ys, xs = norm.shape
xc = int(xs/2.0)
norm[norm>500] = 500
ndata = norm[:,xc]
detect_kern = ndata[5:80]
#these remove light that has bleed at the edges and may need adjusting
norm[:,:20]=0
norm[:,4040:]=0
#detect orders in image
frame = create_orderframe(norm, 53, xc, detect_kern, y_start=8,
y_limit=3920, smooth_length=20)
hdu = fits.PrimaryHDU(frame)
hdu.writeto('RORDER.fits', clobber=True)
print("Creating normalized blue flat")
if interactive:
d.set("file HFLAT.fits")
print("Flat opened in DS9")
check=True
while check:
f_limit_blue=raw_input("Enter a count number that is higher than background light, but lower than in most part of any order: ")
try:
f_limit_blue=float(f_limit_blue)
check=False
except ValueError:
print("\nError: Entered value should be a float ")
#normalize the blue image--these values may need adjusting based on the image
master_blueflat = CCDData.read('HFLAT.fits', ignore_missing_end=True)
image = nd.filters.maximum_filter(master_blueflat, 10)
mask = (image > f_limit_blue)
norm = normalize_image(image, mod.models.Legendre1D(10), mask=mask)
norm[norm < f_limit_blue]=0
hdu = fits.PrimaryHDU(norm)
hdu.writeto('HNORM.fits', clobber=True)
#create the initial detection kernal
ys, xs = norm.shape
xc = int(xs/2.0)
norm[norm>500] = 500
ndata = norm[:,xc]
detect_kern = ndata[5:80]
#these remove light that has bleed at the edges and may need adjusting
norm[:,:20]=0
norm[:,4040:]=0
#detect orders in image
frame = create_orderframe(norm, 53, xc, detect_kern, y_start=8,
y_limit=3920, smooth_length=20)
hdu = fits.PrimaryHDU(frame)
hdu.writeto('HORDER.fits', clobber=True)
return True
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-l','--list', help='Text file containing list of raw calibration files',type=str, required=False)
parser.add_argument("-i","--interactive",help="Interactive fitting",action="store_true")
parser.add_argument("-o","--orderframe",help="The program will create the order frame",action="store_true")
parser.add_argument("-p","--parameters", nargs='+',help="Parameters for making the order frame: f_limit_red and f_limit_blue", required=False)
args=parser.parse_args()
check_input=True
if (args.orderframe) and (not args.interactive) and (not len(args.parameters)==2):
check_input=False
print("In order to create the order frame the script should be run in interactive mode or parameters for making order frame should be specified")
if (not args.list==None):
blue_files,red_files=divide_list(args.list)
else:
blue_files,red_files=create_list_folder()
if blue_files+red_files==[]:
check_input=False
if (not args.list==None):
print("No HRS images in the list")
else:
print("No HRS images found in the running directory")
if check_input==True:
write_bias_flat_arc(blue_files+red_files)
if args.orderframe and args.interactive:
write_orderframe(interactive=True)
elif args.orderframe and len(args.parameters)==2:
write_orderframe(f_limit_red=args.parameters[0],f_limit_blue=args.parameters[1])
|
{"hexsha": "9a340373685813897753b25b70e22fa35f66624b", "size": 10761, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/make_calibrationframes.py", "max_stars_repo_name": "crawfordsm/pyhrs", "max_stars_repo_head_hexsha": "b1eeca635a41791e17ce0c5529b427245bded341", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/make_calibrationframes.py", "max_issues_repo_name": "crawfordsm/pyhrs", "max_issues_repo_head_hexsha": "b1eeca635a41791e17ce0c5529b427245bded341", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/make_calibrationframes.py", "max_forks_repo_name": "crawfordsm/pyhrs", "max_forks_repo_head_hexsha": "b1eeca635a41791e17ce0c5529b427245bded341", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8372781065, "max_line_length": 182, "alphanum_fraction": 0.6656444568, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 2718}
|
module Editor where
open import Agda.Builtin.FromNat
open import BasicIO
open import Data.Bool
open import Data.Char
open import Data.List hiding (_++_)
open import Data.String
open import Data.Unit
open import Function
open import Int
open import Terminal
readTimeout : Int
readTimeout = 0
readMinChars : Int
readMinChars = 1
attrUpdates : TerminalAttributes → TerminalAttributes
attrUpdates =
(flip withoutMode processInput)
∘ (flip withoutMode enableEcho)
∘ (flip withTime readTimeout)
∘ (flip withMinInput readMinChars)
handleInput : String → IO Bool
handleInput "q" = return false
handleInput cs = termWrite cs >>= const (return true)
parsePath : List (List Char) → IO (List Char)
parsePath (path ∷ []) = return path
parsePath _ = fail (toList "Exactly one file path argument required")
{-# NON_TERMINATING #-}
mainLoop : IO ⊤
mainLoop = do
input ← termRead
continue ← handleInput input
if continue then mainLoop else return tt
setupAndRun : IO ⊤
setupAndRun = do
args ← getArgs
path ← parsePath args
bracket
(termWrite (hideCursor ++ altScreenEnable) >> return tt)
(const (termWrite (altScreenDisable ++ showCursor)))
(const mainLoop)
main : IO ⊤
main = withUpdatedAttributes attrUpdates setupAndRun
|
{"hexsha": "f651415abb1a2e7ce114557ade0f969f8f336c9f", "size": 1247, "ext": "agda", "lang": "Agda", "max_stars_repo_path": "src/Editor.agda", "max_stars_repo_name": "cruhland/agda-editor", "max_stars_repo_head_hexsha": "c5ffd117f6d5a98f7c68a2a6b9be54a150c70945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Editor.agda", "max_issues_repo_name": "cruhland/agda-editor", "max_issues_repo_head_hexsha": "c5ffd117f6d5a98f7c68a2a6b9be54a150c70945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Editor.agda", "max_forks_repo_name": "cruhland/agda-editor", "max_forks_repo_head_hexsha": "c5ffd117f6d5a98f7c68a2a6b9be54a150c70945", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5283018868, "max_line_length": 69, "alphanum_fraction": 0.7489975942, "num_tokens": 327}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 13 12:43:45 2021
@author: cadecastro.com
"""
import numpy as np
import matplotlib.pyplot as plt
#Caudal máximo:
Qmax=0.050#[m^3/s] Caudal máximo a simular
N=int(100)#Puntos de caudal a simular
#Geometría ducto:
D=0.1016#[m] Diámetro (hidráulico si no es circular)
L=50.0#[m] Longitud ducto
z=10.0#[m] Altura a elevar fluido
#Propiedades fluido:
rho=999.8#[kg/m^3] Densidad
mu=0.001#[Pa*s] Viscosidad dinámica
g=9.81#[m/s^2] Aceleración de la gravedad
#Material ducto:
ks=0.5#[mm] Rugosidad
#Pérdidas locales:
K=3.5#Suma de coef. de pérdidas locales en el ducto
#Curva de la bomba (elíptica)
H_max=25 #[m] Cabeza máxima (estática)
Q_max=0.050 #[m^3/s] Caudal máximo bomba (sin carga)
#SOLUCIÓN:
Q=np.linspace(Qmax/N,Qmax,N)#
hreq=np.zeros(N)#
hp=np.zeros(N)#
Preq=np.zeros(N)#
Pp=np.zeros(N)#
e_d=ks*0.001/D#Rugosidad relativa
for i in range(0,N):
V=4*Q[i]/(np.pi*D*D)#[m/s] Velocidad media flujo
Re=rho*V*D/mu#Número de Reynolds
#Pérdidas por fricción:
if Re<2300:
f=64/Re
else:
itmax=50#
emax=1e-6#
it=0#
cdc=1#
f0=float(0.015)#
while cdc==1:
it=it+1#
f=np.power(-2*np.log10(e_d/3.7+2.51/(Re*np.sqrt(f0))),-2)
res=abs(f-f0)
if res<=emax or it>=itmax:
cdc=0
else:
f0=f
hL=f*(L/D)*V*V/(2*g)+K*V*V/(2*g)#[m] Pérdidas
hreq[i]=z+hL#[m] Cabeza de bomba requerida
hp[i]=H_max*np.sqrt(1-Q[i]*Q[i]/(Q_max*Q_max))#[m] Cabeza entregada por la bomba
Preq[i]=hreq[i]*rho*g*Q[i]/1000#[kW] Potencia requerida
Pp[i]=hp[i]*rho*g*Q[i]/1000#[kW] Potencia de la bomba
plt.figure(1)
plt.plot(Q,hreq,'b-')
plt.plot(Q,hp,'r-')
plt.grid(True,'both','both')
plt.legend(['Cabeza requerida','Cabeza de la bomba'])
plt.xlabel('Q [m^3/s]')
plt.ylabel('h [m]')
plt.title('Cabeza de bombeo')
plt.figure(2)
plt.plot(Q,Preq,'b-')
plt.plot(Q,Pp,'r-')
plt.grid(True,'both','both')
plt.legend(['Potencia requerida','Potencia de la bomba'])
plt.xlabel('Q [m^3/s]')
plt.ylabel('P [kW]')
plt.title('Potencia de bombeo')
|
{"hexsha": "b899d8cc40f84f5e4bd45fd5b12fd1858e4f0857", "size": 2148, "ext": "py", "lang": "Python", "max_stars_repo_path": "curva_bombeo.py", "max_stars_repo_name": "cadecastro/hidraulica", "max_stars_repo_head_hexsha": "1670e00d27fdf5a36d0b7bab7bf0fa9f7650e0a3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "curva_bombeo.py", "max_issues_repo_name": "cadecastro/hidraulica", "max_issues_repo_head_hexsha": "1670e00d27fdf5a36d0b7bab7bf0fa9f7650e0a3", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "curva_bombeo.py", "max_forks_repo_name": "cadecastro/hidraulica", "max_forks_repo_head_hexsha": "1670e00d27fdf5a36d0b7bab7bf0fa9f7650e0a3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8795180723, "max_line_length": 84, "alphanum_fraction": 0.6205772812, "include": true, "reason": "import numpy", "num_tokens": 844}
|
Require Import Category4.
Require Import Category5.
(* given a Category5 we define the data necessary to create a Category4 *)
Definition Obj4_ (C:Category5) : Type := Obj C.
Inductive Mor4_ (C:Category5) : Type :=
mor4_ : forall (a b:Obj C), Hom a b -> Mor4_ C.
Arguments mor4_ {C} _ _ _.
Definition dom4_ (C:Category5) (f:Mor4_ C) : Obj4_ C :=
match f with
| mor4_ a _ _ => a
end.
Definition cod4_ (C:Category5) (f:Mor4_ C) : Obj4_ C :=
match f with
| mor4_ _ b _ => b
end.
|
{"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/cat/Category5AsCategory4.v"}
|
""" Visualization code for MuJoCo Maze.
"""
import itertools as it
from typing import List, Optional, Tuple
from gym.spaces import Box
import numpy as np
import torch
from mujoco_maze.maze_env import MazeEnv
import rainy
from vis_utils import get_n_row_cols, ValueHeatMap, Trajectory
from rainy.lib.hooks import EvalHook
from rainy.prelude import Self, State
N_SENSOR_SAMPLES_DEFAULT = 100
SEED = 123456
def _sample_sensor_obs(space: Box, n: int, seed: int = SEED) -> np.ndarray:
space.seed(seed)
return np.stack([space.sample() for _ in range(n)])
def _sample_states(
env: MazeEnv, cell_discr: int, n_sensor_samples: int,
) -> Tuple[np.ndarray, List[Tuple[int, int]], Tuple[int, int]]:
structure, scaling = env.unwrapped._maze_structure, env.unwrapped._maze_size_scaling
space = env.observation_space
# Construct a dummy Box space to sample sensory observations
sensor_obs = _sample_sensor_obs(
Box(space.low[2:], space.high[2:]), n_sensor_samples,
)
init_x = env.unwrapped._init_torso_x
init_y = env.unwrapped._init_torso_y
unit = 1.0 / cell_discr
offset = unit / 2 - 0.5
res = []
mapping = []
h, w = len(structure), len(structure[0])
coordinates = []
for i, j in it.product(range(h), range(w)):
if structure[i][j].is_block():
continue
arrs = []
for dyi, dxi in it.product(range(cell_discr), range(cell_discr)):
y, x = i + offset + dyi * unit, j + offset + dxi * unit
xy = np.array([x * scaling - init_x, y * scaling - init_y])
xy_repeated = np.tile(xy, (n_sensor_samples, 1))
arr = np.concatenate((xy_repeated, sensor_obs), axis=1)
arrs.append(arr)
mapping.append((j * cell_discr + dxi, i * cell_discr + dyi))
coordinates.append((x * cell_discr, y * cell_discr))
res.append(np.stack(arrs))
dat = HeatmapData(1, h, w, cell_discr, mapping)
cds = np.array(coordinates) + 0.5
return np.concatenate(res), dat, cds
class HeatmapData:
def __init__(
self, o: int, h: int, w: int, cell_discr: int, mapping: List[Tuple[int, int]],
) -> None:
self.mapping = mapping
self.data = np.zeros((o, h * cell_discr, w * cell_discr))
self.data_shape = h * cell_discr, w * cell_discr
self.noptions = o
self.h_w_cell_discr = h, w, cell_discr
def update(self, data: np.ndarray) -> np.ndarray:
data = data.reshape(-1, self.noptions) # Batch x Options
for i, (x, y) in enumerate(self.mapping):
self.data[:, y, x] = data[i]
return self.data
def copy(self, noptions: Optional[int] = None) -> Self:
noptions = noptions or self.noptions
return HeatmapData(noptions, *self.h_w_cell_discr, self.mapping)
class A2CVis(EvalHook):
def __init__(
self,
cell_discr: int = 2,
n_sensor_samples: int = N_SENSOR_SAMPLES_DEFAULT,
vmin: float = -1.2,
vmax: float = 1.2,
) -> None:
self.counter = 0
self.cell_discr = cell_discr
self.n_sensor_samples = n_sensor_samples
self.vmin = vmin
self.vmax = vmax
def setup(self, config: rainy.Config) -> None:
self.device = config.device
def reset(
self, agent: rainy.agents.Agent, env: rainy.envs.EnvExt, initial_state: State
) -> None:
if self.counter == 0:
states, self.heatmap_data, _ = _sample_states(
env.unwrapped, self.cell_discr, self.n_sensor_samples,
)
self.states = self.device.tensor(states) # cells, sensor_samples, |s|
self.value_heatmap = ValueHeatMap(
self.heatmap_data.data_shape,
name="Value",
vmin=self.vmin,
vmax=self.vmax,
reverse_y=True,
)
with torch.no_grad():
pi, v, *_ = agent.net(self.states.view(-1, self.states.size(-1)))
v = v.view(self.states.shape[:2]).mean(dim=1).cpu().numpy()
self.value_heatmap.update(self.heatmap_data.update(v))
self.counter += 1
class ImocVis(EvalHook):
POLICY_SCALE: float = 1.5
def __init__(
self,
noptions: int = 4,
cell_discr: int = 2,
n_sensor_samples: int = N_SENSOR_SAMPLES_DEFAULT,
vmin: float = -0.8,
vmax: float = 0.8,
gain_index: int = 0,
rot_index: int = 1,
vis_policy: bool = False,
vis_trajectory: bool = True,
vis_value: bool = True,
is_flat_layout: bool = True,
) -> None:
self.counter = 0
self.noptions = noptions
self.cell_discr = cell_discr
self.n_sensor_samples = n_sensor_samples
self.vmin = vmin
self.vmax = vmax
self._gain_index = gain_index
self._rot_index = rot_index
self._ori_index = 0
self._vis_value = vis_value
self._vis_policy = vis_policy
self._vis_traj = vis_trajectory
self._is_flat = is_flat_layout
self.nrowcols = get_n_row_cols(self.noptions, is_flat_layout=is_flat_layout)
def setup(self, config: rainy.Config) -> None:
self.device = config.device
def _initialize(self, env: MazeEnv) -> None:
if self._vis_policy:
self._ori_index = env.wrapped_env.ORI_IND
states, heatmap_data, self._xy = _sample_states(
env, self.cell_discr, self.n_sensor_samples,
)
data_shape = heatmap_data.data_shape
self.states = self.device.tensor(states) # cells, sensor_samples, |s|
self.qo_heatmap_data = heatmap_data.copy(self.noptions)
self.beta_heatmap_data = self.qo_heatmap_data.copy()
self.beta_heatmap = ValueHeatMap(
data_shape,
name="β(x)",
cmap="YlGnBu",
vmin=0.0,
value_annon="Option",
cbar_annon=True,
reverse_y=True,
**self.nrowcols,
)
if self._vis_value:
self.value_heatmap = ValueHeatMap(
data_shape,
name="Qo",
vmin=self.vmin,
vmax=self.vmax,
reverse_y=True,
**self.nrowcols,
)
if self._vis_traj:
self.trajectory = Trajectory(self.noptions)
obs_space = env.observation_space
obs_range = obs_space.high[:2] - obs_space.low[:2]
obs_low = obs_space.low[:2]
def point(state: np.ndarray) -> np.ndarray:
xy = state[:2].copy()
return (xy - obs_low) / obs_range
self._point = point
act_range = env.action_space.high - env.action_space.low
act_low = env.action_space.low
def scale_action(action: np.ndarray) -> np.ndarray:
return act_range / (1.0 + np.exp(-action)) + act_low
self._scale_action = scale_action
self._quivers = [None] * self.noptions
self._quiverkey = None
def reset(
self, agent: rainy.agents.Agent, env: rainy.envs.EnvExt, initial_state: State
) -> None:
if self.counter == 0:
self._initialize(env.unwrapped)
if self._vis_traj:
self.trajectory.reset(self._point(initial_state))
with torch.no_grad():
# This * is for making this compatible with rainy.agent.PPOCAgent
pi, qo, beta, *_ = agent.net(self.states.view(-1, self.states.size(-1)))
if self._vis_value:
qo = qo.view(*self.states.shape[:2], self.noptions).mean(dim=1)
qo = self.qo_heatmap_data.update(qo.cpu().numpy())
for i in range(self.noptions):
self.value_heatmap.update(qo[i, :], i)
beta = beta.dist.probs.view(*self.states.shape[:2], self.noptions).mean(dim=1)
beta = self.beta_heatmap_data.update(beta.cpu().numpy())
for i in range(self.noptions):
self.beta_heatmap.update(beta[i, :], i)
if self._vis_policy:
self.draw_policy(pi.dist.loc)
# if self.counter == 0:
# self.beta_heatmap.fig.savefig("mjmaze-β-logp0.5to0.1-entm0.005.pdf")
self.counter += 1
def draw_policy(self, pimu: torch.Tensor) -> None:
""" Visualize option-policies by two-dimentional arrows.
"""
pimu = pimu.view(*self.states.shape[:2], self.noptions, -1)
pimu = self._scale_action(pimu.cpu().numpy())
ori = self.states[:, :, self._ori_index].cpu().unsqueeze(-1).numpy()
ori = pimu[:, :, :, self._rot_index] + ori
gain = pimu[:, :, :, self._gain_index]
xvec = (np.cos(ori) * gain).mean(axis=1)
yvec = (np.sin(ori) * gain).mean(axis=1)
quiverkey_idx = self.noptions - 1 if self._is_flat else 0
for opt in range(self.noptions):
if self._quivers[opt] is not None:
self._quivers[opt].remove()
ax = self.beta_heatmap.axes[opt]
self._quivers[opt] = ax.quiver(
self._xy[:, 0],
self._xy[:, 1],
xvec[:, opt] * 2.0,
yvec[:, opt] * 2.0,
units="x",
scale=0.5,
width=0.06,
headwidth=4,
headlength=6,
)
if opt == quiverkey_idx:
if self._quiverkey is not None:
self._quiverkey.remove()
self._quiverkey = ax.quiverkey(
self._quivers[opt],
0.0,
1.05,
1,
"Expected value of Policy",
labelpos="E",
)
self.beta_heatmap.redraw()
# self.beta_heatmap.axes[0].text(1.0, 17.8, "PPIMOC", fontsize=20)
# self.beta_heatmap.fig.savefig(
# "ppimoc-pi-and-beta.pdf", bbox_inches="tight", pad_inches=0.0,
# )
def step(self, _env, _action, transition, net_outputs) -> None:
if not self._vis_traj or "options" not in net_outputs:
return
if transition.terminal:
self.trajectory.render()
else:
option = net_outputs["options"][0].item()
self.trajectory.append(option, self._point(transition.state))
|
{"hexsha": "5b50e492f91ace53fe986ed290c8c1310c5e9f72", "size": 10338, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/vis_mjmaze.py", "max_stars_repo_name": "kngwyu/infomax-option-critic", "max_stars_repo_head_hexsha": "9d907c041c1d0280db9b23eb2fdf9e0033e33bf3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-24T05:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-19T09:27:49.000Z", "max_issues_repo_path": "src/vis_mjmaze.py", "max_issues_repo_name": "kngwyu/infomax-option-critic", "max_issues_repo_head_hexsha": "9d907c041c1d0280db9b23eb2fdf9e0033e33bf3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vis_mjmaze.py", "max_forks_repo_name": "kngwyu/infomax-option-critic", "max_forks_repo_head_hexsha": "9d907c041c1d0280db9b23eb2fdf9e0033e33bf3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9256756757, "max_line_length": 88, "alphanum_fraction": 0.5760301799, "include": true, "reason": "import numpy", "num_tokens": 2648}
|
import os
import unittest
if not os.getcwd().endswith('Tests'):
os.chdir('Tests')
import numpy as np
from PIL import Image
from VSR.Util import imread, rgb_to_yuv
from VSR.Backend import BACKEND
URL = 'data/set5_x2/img_001_SRF_2_LR.png'
class ImageTest(unittest.TestCase):
def psnr(self, x: np.ndarray, y: np.ndarray):
mse = np.mean((x - y) ** 2)
if mse == 0:
return np.inf
psnr = np.log10(255 * 255 / mse) * 10
return psnr
def test_rgb2yuv(self):
img = imread(URL, mode='RGB').astype('float32')
yuv = rgb_to_yuv(img, 255, 'matlab')
yuv_ref = imread(URL, mode='YCbCr').astype('float32')
# should have the same shape
self.assertEqual(yuv.shape, img.shape)
self.assertGreaterEqual(self.psnr(yuv, yuv_ref), 30)
def test_resize_upsample_tf(self):
if BACKEND != 'tensorflow':
return
import tensorflow as tf
tf.enable_eager_execution()
from VSR.Backend.TF.Util import upsample
Im = Image.open(URL)
for X in [Im, Im.convert('L')]:
w = X.width
h = X.height
for ss in [2, 3, 4, 5, 6]:
GT = X.resize([w * ss, h * ss], Image.BICUBIC)
gt = np.asarray(GT, dtype='float32') / 255
x = tf.constant(np.asarray(X), dtype='float32') / 255
y = upsample(x, ss).numpy().clip(0, 1)
self.assertGreaterEqual(self.psnr(y, gt), 30, f"{X.mode}, {ss}")
def test_resize_downsample_tf(self):
if BACKEND != 'tensorflow':
return
import tensorflow as tf
tf.enable_eager_execution()
from VSR.Backend.TF.Util import downsample
Im = Image.open(URL)
for X in [Im, Im.convert('L')]:
w = X.width
h = X.height
for ss in [2, 4, 6, 8]:
w_ = w - w % ss
h_ = h - h % ss
X = X.crop([0, 0, w_, h_])
GT = X.resize([w_ // ss, h_ // ss], Image.BICUBIC)
gt = np.asarray(GT, dtype='float32') / 255
x = tf.constant(np.asarray(X), dtype='float32') / 255
y = downsample(x, ss).numpy().clip(0, 1)
self.assertGreaterEqual(self.psnr(y, gt), 30, f"{X.mode}, {ss}")
def test_resize_upsample_torch(self):
if BACKEND != 'pytorch':
return
from VSR.Backend.Torch.Util.Utility import upsample
import torchvision
Im = Image.open(URL)
trans = torchvision.transforms.ToTensor()
for X in [Im, Im.convert('L')]:
w = X.width
h = X.height
for ss in [2, 3, 4, 5, 6]:
GT = X.resize([w * ss, h * ss], Image.BICUBIC)
gt = trans(GT).numpy()
x = trans(X)
y = upsample(x, ss).numpy().clip(0, 1)
self.assertGreaterEqual(self.psnr(y, gt), 30, f"{X.mode}, {ss}")
def test_resize_downsample_torch(self):
if BACKEND != 'pytorch':
return
from VSR.Backend.Torch.Util.Utility import downsample
import torchvision
Im = Image.open(URL)
trans = torchvision.transforms.ToTensor()
for X in [Im, Im.convert('L')]:
w = X.width
h = X.height
for ss in [2, 4, 6, 8]:
w_ = w - w % ss
h_ = h - h % ss
X = X.crop([0, 0, w_, h_])
GT = X.resize([w_ // ss, h_ // ss], Image.BICUBIC)
gt = trans(GT).numpy()
x = trans(X)
y = downsample(x, ss).numpy().clip(0, 1)
self.assertGreaterEqual(self.psnr(y, gt), 30, f"{X.mode}, {ss}")
if __name__ == '__main__':
unittest.main()
|
{"hexsha": "5b306cbe8dded471403700fd4255c8fcb2ff363b", "size": 3343, "ext": "py", "lang": "Python", "max_stars_repo_path": "Tests/image_test.py", "max_stars_repo_name": "Kadantte/VideoSuperResolution", "max_stars_repo_head_hexsha": "4c86e49d81c7a9bea1fe0780d651afc126768df3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1447, "max_stars_repo_stars_event_min_datetime": "2018-06-04T08:44:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:19:10.000Z", "max_issues_repo_path": "Tests/image_test.py", "max_issues_repo_name": "AbdulMoqeet/VideoSuperResolution", "max_issues_repo_head_hexsha": "82c3347554561ff9dfb5e86d9cf0a55239ca662e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 96, "max_issues_repo_issues_event_min_datetime": "2018-08-29T01:02:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T06:00:01.000Z", "max_forks_repo_path": "Tests/image_test.py", "max_forks_repo_name": "AbdulMoqeet/VideoSuperResolution", "max_forks_repo_head_hexsha": "82c3347554561ff9dfb5e86d9cf0a55239ca662e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 307, "max_forks_repo_forks_event_min_datetime": "2018-06-26T13:35:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T09:01:54.000Z", "avg_line_length": 29.8482142857, "max_line_length": 72, "alphanum_fraction": 0.5842058032, "include": true, "reason": "import numpy", "num_tokens": 1063}
|
"""
Mask R-CNN Copyright (c) 2017 Matterport, Inc.
Train on the CElegans segmentation dataset
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
Modified for CElegans fitness assessment by Krzysztof Fiok
------------------------------------------------------------
Example use:
python3 ce_segmentation.py train --dataset=/path/to/dataset --model=/path/to/model_weights --validation_images=38
python3 ce_segmentation.py train --dataset=segmentation_dataset --model=model_weights.h5 --validation_images=38
"""
if __name__ == '__main__':
import matplotlib
# Agg backend runs without a display
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
import sys
import json
import datetime
import numpy as np
import skimage.io
from imgaug import augmenters as iaa
import random
# Root directory of the project
ROOT_DIR = os.path.abspath("")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn.config import Config
from mrcnn import utils
from mrcnn import model as modellib
# Path to trained weights file
COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Directory to save logs and model checkpoints, if not provided
# through the command line argument --logs
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")
# Results directory
# Save submission files here
RESULTS_DIR = os.path.join(ROOT_DIR, "results/CElegans/")
############################################################
# Configurations
############################################################
class CElegansConfig(Config):
"""Configuration for training on the CElegance segmentation dataset."""
# Give the configuration a recognizable name
NAME = "CE"
# Adjust depending on your GPU memory
IMAGES_PER_GPU = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 2 # Background + CE
# Number of training and validation steps per epoch
STEPS_PER_EPOCH = 40
# Don't exclude based on confidence. Since we have two classes
# then 0.5 is the minimum anyway as it picks between CElegans and BG
DETECTION_MIN_CONFIDENCE = 0.5
# Backbone network architecture
# Supported values are: resnet50, resnet101
BACKBONE = "resnet101"
IMAGE_RESIZE_MODE = "square"
IMAGE_MIN_DIM = 800
IMAGE_MAX_DIM = 1024
IMAGE_MIN_SCALE = 0
# Length of square anchor side in pixels
RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128)
# ROIs kept after non-maximum supression (training and inference)
POST_NMS_ROIS_TRAINING = 2000
POST_NMS_ROIS_INFERENCE = 3000
# Non-max suppression threshold to filter RPN proposals.
# You can increase this during training to generate more propsals.
RPN_NMS_THRESHOLD = 0.9
# How many anchors per image to use for RPN training
RPN_TRAIN_ANCHORS_PER_IMAGE = 256
# Image mean (RGB)
MEAN_PIXEL = np.array([43.53, 39.56, 48.22])
# If enabled, resizes instance masks to a smaller size to reduce
# memory load. Recommended when using high-resolution images.
USE_MINI_MASK = True
MINI_MASK_SHAPE = (256, 256) # (height, width) of the mini-mask
# Number of ROIs per image to feed to classifier/mask heads
# The Mask RCNN paper uses 512 but often the RPN doesn't generate
# enough positive proposals to fill this and keep a positive:negative
# ratio of 1:3. You can increase the number of proposals by adjusting
# the RPN NMS threshold.
TRAIN_ROIS_PER_IMAGE = 600
# Maximum number of ground truth instances to use in one image
MAX_GT_INSTANCES = 300
# Max number of final detections per image
DETECTION_MAX_INSTANCES = 300
class CElegansInferenceConfig(CElegansConfig):
# Set batch size to 1 to run one image at a time
GPU_COUNT = 1
# Non-max suppression threshold to filter RPN proposals.
############################################################
# Dataset
############################################################
class CElegansDataset(utils.Dataset):
def load_celegans(self, dataset_dir, subset):
"""Load a subset of the CElegans dataset.
dataset_dir: Root directory of the dataset
subset: Subset to load.
"""
# Add classes. We have one class.
self.add_class("CE", 1, "CE")
self.add_class("CE", 2, "CE_glow")
# Which subset?
subset_dir = "train"
dataset_dir = os.path.join(dataset_dir)
if subset == "val":
image_ids = VAL_IMAGE_IDS
else:
# Get image ids from directory names
image_ids = next(os.walk(dataset_dir))[1]
if subset == "train":
image_ids = list(set(image_ids) - set(VAL_IMAGE_IDS))
# Add images
for image_id in image_ids:
self.add_image(
"CE",
image_id=image_id,
path=os.path.join(dataset_dir, image_id, "images/{}.png".format(image_id)))
def load_mask(self, image_id):
"""Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
info = self.image_info[image_id]
# Get mask directory from image path
mask_dir = os.path.join(os.path.dirname(os.path.dirname(info['path'])), "masks")
# Read mask files from .png image
mask = []
class_ids = []
for f in next(os.walk(mask_dir))[2]:
if f.endswith(".png"):
m = skimage.io.imread(os.path.join(mask_dir, f)).astype(np.bool)
mask.append(m)
if 'C2C' in f:
class_ids.append(2)
elif 'C1C' in f:
class_ids.append(1)
mask = np.stack(mask, axis=-1)
class_ids = np.array(class_ids, dtype=np.int32)
# Return mask, and array of class IDs of each instance. Since we have
# one class ID, we return an array of ones
return mask, class_ids
def image_reference(self, image_id):
"""Return the path of the image."""
info = self.image_info[image_id]
if info["source"] == "CE":
return info["id"]
else:
super(self.__class__, self).image_reference(image_id)
############################################################
# Training
############################################################
def train(model, dataset_dir):
"""Train the model."""
# Training dataset.
dataset_train = CElegansDataset()
dataset_train.load_celegans(dataset_dir, "train")
dataset_train.prepare()
# Validation dataset
dataset_val = CElegansDataset()
dataset_val.load_celegans(dataset_dir, "val")
dataset_val.prepare()
# Image augmentation
# http://imgaug.readthedocs.io/en/latest/source/augmenters.html
augmentation = iaa.SomeOf((0, 2), [
# iaa.Fliplr(0.5),
# iaa.Flipud(0.5),
# iaa.OneOf([iaa.Affine(rotate=90),
# iaa.Affine(rotate=180),
# iaa.Affine(rotate=270)]),
iaa.Multiply((0.8, 1.5)),
iaa.GaussianBlur(sigma=(0.0, 5.0))
])
# *** This training schedule is an example. Update to your needs ***
# If starting from imagenet, train heads only for a bit
# since they have random weights
# print("Train network heads")
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs=25,
augmentation=None,
layers='heads')
# #
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs=50,
augmentation=None,
layers='4+')
# print("Train all layers")
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs=125,
augmentation=None,
layers='all')
############################################################
# RLE Encoding
############################################################
def rle_encode(mask):
"""Encodes a mask in Run Length Encoding (RLE).
Returns a string of space-separated values.
"""
assert mask.ndim == 2, "Mask must be of shape [Height, Width]"
# Flatten it column wise
m = mask.T.flatten()
# Compute gradient. Equals 1 or -1 at transition points
g = np.diff(np.concatenate([[0], m, [0]]), n=1)
# 1-based indicies of transition points (where gradient != 0)
rle = np.where(g != 0)[0].reshape([-1, 2]) + 1
# Convert second index in each pair to lenth
rle[:, 1] = rle[:, 1] - rle[:, 0]
return " ".join(map(str, rle.flatten()))
def rle_decode(rle, shape):
"""Decodes an RLE encoded list of space separated
numbers and returns a binary mask."""
rle = list(map(int, rle.split()))
rle = np.array(rle, dtype=np.int32).reshape([-1, 2])
rle[:, 1] += rle[:, 0]
rle -= 1
mask = np.zeros([shape[0] * shape[1]], np.bool)
for s, e in rle:
assert 0 <= s < mask.shape[0]
assert 1 <= e <= mask.shape[0], "shape: {} s {} e {}".format(shape, s, e)
mask[s:e] = 1
# Reshape and transpose
mask = mask.reshape([shape[1], shape[0]]).T
return mask
def mask_to_rle(image_id, mask, scores):
"Encodes instance masks to submission format."
assert mask.ndim == 3, "Mask must be [H, W, count]"
# If mask is empty, return line with image ID only
if mask.shape[-1] == 0:
return "{},".format(image_id)
# Remove mask overlaps
# Multiply each instance mask by its score order
# then take the maximum across the last dimension
order = np.argsort(scores)[::-1] + 1 # 1-based descending
mask = np.max(mask * np.reshape(order, [1, 1, -1]), -1)
# Loop over instance masks
lines = []
for o in order:
m = np.where(mask == o, 1, 0)
# Skip if empty
if m.sum() == 0.0:
continue
rle = rle_encode(m)
lines.append("{}, {}".format(image_id, rle))
return "\n".join(lines)
############################################################
# Command Line
############################################################
if __name__ == '__main__':
import argparse
# Parse command line arguments
parser = argparse.ArgumentParser(
description='Mask R-CNN for CElegans counting and segmentation')
parser.add_argument("command",
metavar="<command>",
help="'train'")
parser.add_argument('--dataset', required=False,
metavar="/path/to/dataset/",
help='Path of the dataset')
parser.add_argument('--model', required=True,
metavar="/path/to/model_weights.h5",
help="Path to weights .h5 file or 'coco'")
parser.add_argument('--logs', required=False,
default=DEFAULT_LOGS_DIR,
metavar="/path/to/logs/",
help='Logs and checkpoints directory (default=logs/)')
parser.add_argument("--validation_images", default=38, type=int, help="Number of images from dataset "
"used as validation split during training")
args = parser.parse_args()
# Validate arguments
if args.command == "train":
assert args.dataset, "Argument --dataset is required for training"
print("Weights: ", args.model)
print("Dataset: ", args.dataset)
print("Logs: ", args.logs)
dataset_path = args.dataset
folder_list = os.listdir(dataset_path)
# k: How many % of images choose for validation?
random_list = random.choices(folder_list, k=args.validation_images)
VAL_IMAGE_IDS = random_list
# Configurations
if args.command == "train":
config = CElegansConfig()
else:
config = CElegansInferenceConfig()
config.display()
# Create model
if args.command == "train":
model = modellib.MaskRCNN(mode="training", config=config,
model_dir=args.logs)
else:
model = modellib.MaskRCNN(mode="inference", config=config,
model_dir=args.logs)
# Select weights file to load
if args.model.lower() == "coco":
weights_path = COCO_WEIGHTS_PATH
# Download weights file
if not os.path.exists(weights_path):
utils.download_trained_weights(weights_path)
elif args.model.lower() == "last":
# Find last trained weights
weights_path = model.find_last()
elif args.model.lower() == "imagenet":
# Start from ImageNet trained weights
weights_path = model.get_imagenet_weights()
else:
weights_path = args.model
# Load weights
print("Loading weights ", weights_path)
if args.model.lower() == "coco":
# Exclude the last layers because they require a matching
# number of classes
model.load_weights(weights_path, by_name=True, exclude=[
"mrcnn_class_logits", "mrcnn_bbox_fc",
"mrcnn_bbox", "mrcnn_mask"])
else:
model.load_weights(weights_path, by_name=True)
# Train or evaluate
if args.command == "train":
train(model, args.dataset)
else:
print("'{}' is not recognized. "
"Use 'train' or 'detect'".format(args.command))
|
{"hexsha": "552289040588bcf8bd8f8524693926bdfd44fbdd", "size": 13624, "ext": "py", "lang": "Python", "max_stars_repo_path": "ce_segmentation.py", "max_stars_repo_name": "krzysztoffiok/c_elegans_fitness", "max_stars_repo_head_hexsha": "d16270f882890aa42df55739d9bb0efc2e2168e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-31T15:49:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T15:49:01.000Z", "max_issues_repo_path": "ce_segmentation.py", "max_issues_repo_name": "krzysztoffiok/c_elegans_fitness", "max_issues_repo_head_hexsha": "d16270f882890aa42df55739d9bb0efc2e2168e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ce_segmentation.py", "max_forks_repo_name": "krzysztoffiok/c_elegans_fitness", "max_forks_repo_head_hexsha": "d16270f882890aa42df55739d9bb0efc2e2168e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2311557789, "max_line_length": 117, "alphanum_fraction": 0.5930710511, "include": true, "reason": "import numpy", "num_tokens": 3192}
|
"""
This expirment tests whether or not the magnetic field affects the objects in
the LEO by correlating the resultant intensity of the magnetic field with the
accelertaion and angular velocity of the ISS
"""
""" Importing the libraries and the modules """
from datetime import datetime,timedelta
import magn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import noise_filtering
import plot
"""_______________________ Part 1: Analyzing the IMU sensor data _______________________"""
''' 1-Importing the IMU sensor data '''
#Imports the whole data from the csv using pandas library
data = pd.read_csv('data01.csv')
#Takes the time, gyroscope, magnometer, and accelerometer X, Y, and Z readings from the dataset:
time = data.iloc[:,1].values
gyroX = data.iloc[:,7].values
gyroY = data.iloc[:,8].values
gyroZ = data.iloc[:,9].values
magnX = data.iloc[:,10].values
magnY = data.iloc[:,11].values
magnZ = data.iloc[:,12].values
magn_resultant = magn.get_resultant(magnX,magnY,magnZ)
accX = data.iloc[:,13].values
accY = data.iloc[:,14].values
accZ = data.iloc[:,15].values
acc_resultant = magn.get_resultant(accX,accY,accZ)
''' 2-Preprocessing the data by applying noise filteration '''
gyro_filtered_matrix = noise_filtering.noise_filtering(gyroX,gyroY,gyroZ,sensitivity = (0.0175), frequency = 476, rms = (3.2 * 10**-3) )
#Senstivity and Frequency are according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf
magn_filtered_matrix = noise_filtering.noise_filtering(magnX,magnY,magnZ,sensitivity = 0.043, frequency = 20, rms = (3.2 * 10**-3) )
#Senstivity and Frequency are according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf
#RMS Noise assumtion according to https://www.st.com/resource/en/datasheet/lis3mdl.pdf which is a similar build
acc_filtered_matrix = noise_filtering.noise_filtering(accX,accY,accZ,sensitivity = (0.000244*9.81), frequency = 10, rms = (3.2 * 10**-3) )
#Senstivity and Frequency are according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf
gyroX_filtered = gyro_filtered_matrix[:,0]
gyroY_filtered = gyro_filtered_matrix[:,1]
gyroZ_filtered = gyro_filtered_matrix[:,2]
magn_filtered_resultant = magn.get_resultant(magn_filtered_matrix[:,0],magn_filtered_matrix[:,1],magn_filtered_matrix[:,2])
acc_filtered_resultant = magn.get_resultant(acc_filtered_matrix[:,0],acc_filtered_matrix[:,1],acc_filtered_matrix[:,2])
''' 3- Calculating the resultant magnitude, the standard deviation, the mean and the autocorrelation of the points
for the filtered and unfiltered magnetic field, acceleration, and angular velocity'''
gyroX_sd = magn.get_sd(gyroX_filtered)
gyroY_sd = magn.get_sd(gyroY_filtered)
gyroZ_sd = magn.get_sd(gyroZ_filtered)
gyro_sd_mean = magn.get_mean_3(gyroX_sd, gyroY_sd, gyroZ_sd)
gyroX_mean = magn.get_mean(gyroX_filtered)
gyroY_mean = magn.get_mean(gyroY_filtered)
gyroZ_mean = magn.get_mean(gyroZ_filtered)
gyro_mean_mean = magn.get_mean_3(gyroX_mean, gyroY_mean, gyroZ_mean)
magn_sd = magn.get_sd(magn_filtered_resultant)
magn_mean = magn.get_mean(magn_filtered_resultant)
magn_autocorrelation = magn.autocor(magn_filtered_resultant)
acc_sd = magn.get_sd(acc_filtered_resultant)
acc_mean = magn.get_mean(acc_filtered_resultant)
acc_autocorrelation = magn.autocor(acc_filtered_resultant)
acc_autocorrelation_pure = magn.autocor(acc_resultant)
'''4- Plotting the Autocorrelation'''
#plots accelerometer data
plt.title("Accelerometer Data")
plt.xlabel("Reading number")
plt.ylabel("Acceleration/g")
plt.plot(acc_filtered_resultant,label='AccResultant')
plt.plot([acc_mean]*len(accX),label='Mean')
plt.plot([acc_sd]*len(accX),label='Standard Deviation')
plt.legend()
plt.show()
plt.plot(acc_autocorrelation, label = "Noise filtered acceleration readings autocorrelation")
plt.plot(acc_autocorrelation_pure, label= "Raw acceleration readings autocorrelation")
plt.xlabel("Readings number")
plt.ylabel("Autocorrelation value")
plt.title("Auto correlation of Resultant Acceleration")
plt.legend()
plt.show()
#plots magnetometer data
plt.title("Magnetometer Data")
plt.ylabel("Magnetic Intensity/µT")
plt.xlabel("Reading number")
plt.plot(magn_filtered_resultant,label='MagnResultant')
plt.plot([magn_mean]*len(magnX),label='Mean')
plt.plot([magn_sd]*len(magnX),label='Standard Deviation')
plt.legend()
plt.show()
#plots autocorrelation data
plot.plot_2d(np.arange(0,len(magn_filtered_resultant),1),'Reading number',[np.append(magn_autocorrelation,magn_autocorrelation[-1])],'Autocorrelation of magnetic field',[magn_filtered_resultant],"Resultant Magnetic field Intensity/µT")
"""_______________________ Part 2: Comparing and correlating data ______________________"""
'''1- Plotting the correlations '''
magn_acc_cor = magn.cor(magn_filtered_resultant, acc_filtered_resultant)
#plots correlation data
plt.title("Correlation between Acceleration and Magnetic Intensity")
plt.xlabel("Reading number")
plt.plot(magn_acc_cor)
plt.ylabel("Correlation value")
plt.legend()
plt.show()
magn_gyroX_cor = magn.cor(magn_filtered_resultant, gyroX_filtered)
#plots correlation data
plt.title("Correlation between Angular velocity in X-axis and Magnetic Intensity")
plt.xlabel("Reading number")
plt.plot(magn_gyroX_cor)
plt.ylabel("Correlation value")
plt.legend()
plt.show()
magn_gyroY_cor = magn.cor(magn_filtered_resultant, gyroY_filtered)
#plots correlation data
plt.title("Correlation between Angular velocity in Y-axis and Magnetic Intensity")
plt.xlabel("Reading number")
plt.plot(magn_gyroY_cor)
plt.ylabel("Correlation value")
plt.legend()
plt.show()
magn_gyroZ_cor = magn.cor(magn_filtered_resultant, gyroZ_filtered)
#plots correlation data
plt.title("Correlation between Angular velocity in Z-axis and Magnetic Intensity")
plt.xlabel("Reading number")
plt.plot(magn_gyroZ_cor)
plt.ylabel("Correlation value")
plt.legend()
plt.show()
|
{"hexsha": "fb08a6f9974bf70839b795548f6f1c4e247689f0", "size": 5874, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiment-2.py", "max_stars_repo_name": "RoboneClub/Mechabot-Analysis", "max_stars_repo_head_hexsha": "c81791f9b5333bb88cb1378697872d4840b56455", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiment-2.py", "max_issues_repo_name": "RoboneClub/Mechabot-Analysis", "max_issues_repo_head_hexsha": "c81791f9b5333bb88cb1378697872d4840b56455", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiment-2.py", "max_forks_repo_name": "RoboneClub/Mechabot-Analysis", "max_forks_repo_head_hexsha": "c81791f9b5333bb88cb1378697872d4840b56455", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4844720497, "max_line_length": 235, "alphanum_fraction": 0.7889002383, "include": true, "reason": "import numpy", "num_tokens": 1537}
|
from dsbox.template.template import DSBoxTemplate
from d3m.metadata.problem import TaskKeyword
from dsbox.template.template_steps import TemplateSteps
from dsbox.schema import SpecializedProblem
import typing
import numpy as np # type: ignore
class SRIClassificationTemplate(DSBoxTemplate):
def __init__(self):
DSBoxTemplate.__init__(self)
self.template = {
"weight": 30,
"name": "SRI_classification_template",
"taskSubtype": {TaskKeyword.VERTEX_CLASSIFICATION.name},
"taskType": {TaskKeyword.VERTEX_CLASSIFICATION.name},
# "taskType": {TaskKeyword.VERTEX_CLASSIFICATION.name, TaskKeyword.COMMUNITY_DETECTION.name, TaskKeyword.LINK_PREDICTION.name, TaskKeyword.TIME_SERIES.name},
# "taskSubtype": {"NONE", TaskKeyword.NONOVERLAPPING.name, TaskKeyword.OVERLAPPING.name, TaskKeyword.MULTICLASS.name, TaskKeyword.BINARY.name, TaskKeyword.MULTILABEL.name, TaskKeyword.MULTIVARIATE.name, TaskKeyword.UNIVARIATE.name, TaskKeyword.TIME_SERIES.name},
#"inputType": "table",
"inputType": {"edgeList", "graph", "table"},
"output": "prediction_step",
"steps": [
{
"name": "text_reader_step",
"primitives": ["d3m.primitives.data_preprocessing.dataset_text_reader.DatasetTextReader"],
"inputs": ["template_input"]
},
{
"name": "denormalize_step",
"primitives": ["d3m.primitives.data_transformation.denormalize.Common"],
"inputs": ["text_reader_step"]
},
{
"name": "to_dataframe_step",
"primitives": ["d3m.primitives.data_transformation.dataset_to_dataframe.Common"],
"inputs": ["denormalize_step"]
},
{
"name": "common_profiler_step",
"primitives": ["d3m.primitives.schema_discovery.profiler.Common"],
"inputs": ["to_dataframe_step"]
},
{
"name": "parser_step",
"primitives": ["d3m.primitives.data_transformation.column_parser.Common"],
"inputs": ["common_profiler_step"]
},
{
"name": "pre_extract_target_step",
"primitives": [{
"primitive": "d3m.primitives.data_transformation.extract_columns_by_semantic_types.Common",
"hyperparameters":
{
'semantic_types': ('https://metadata.datadrivendiscovery.org/types/TrueTarget',),
'use_columns': (),
'exclude_columns': ()
}
}],
"inputs": ["parser_step"]
},
{
"name": "extract_target_step",
"primitives": ["d3m.primitives.data_transformation.simple_column_parser.DataFrameCommon"],
"inputs": ["pre_extract_target_step"]
},
{
"name": "extract_attribute_step",
"primitives": [{
"primitive": "d3m.primitives.data_transformation.extract_columns_by_semantic_types.Common",
"hyperparameters":
{
'semantic_types': ('https://metadata.datadrivendiscovery.org/types/Attribute',),
}
}],
"inputs": ["parser_step"]
},
{
"name": "data_conditioner_step",
"primitives": [{
"primitive": "d3m.primitives.data_transformation.conditioner.Conditioner",
"hyperparameters":
{
"ensure_numeric":[True],
"maximum_expansion": [30]
}
}],
"inputs": ["extract_attribute_step"]
},
{
"name": "model_step",
"primitives": [
{
"primitive": "d3m.primitives.classification.bernoulli_naive_bayes.SKlearn",
"hyperparameters": {
'alpha': [0.1, 1.0],
'binarize': [0.0],
'fit_prior': [False],
'return_result': ["new"],
'use_semantic_types': [False],
'add_index_columns': [False],
'error_on_no_input':[True],
}
},
{
"primitive": "d3m.primitives.regression.gradient_boosting.SKlearn",
"hyperparameters": {
'max_depth': [5, 8],
'learning_rate': [0.3, 0.5],
'min_samples_split': [2, 3, 6],
'min_samples_leaf': [1, 2],
'criterion': ["mse"],
'n_estimators': [100, 150],
'fit_prior': [False],
'return_result': ["new"],
'use_semantic_types': [False],
'add_index_columns': [False],
'error_on_no_input':[True],
}
},
{"primitive": "d3m.primitives.classification.random_forest.SKlearn"
}
],
"inputs": ["extract_attribute_step2", "extract_target_step"]
},
{
"name": "prediction_step",
"primitives": ["d3m.primitives.data_transformation.construct_predictions.Common"],
"inputs": ["model_step", "to_dataframe_step"]
}
]
}
|
{"hexsha": "c978b614564b15ad98ff9be9b231eda20bb8f13d", "size": 6405, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/dsbox/template/template_files/loaded/SRIClassificationTemplate.py", "max_stars_repo_name": "usc-isi-i2/dsbox-ta2", "max_stars_repo_head_hexsha": "85e0e8f5bbda052fa77cb98f4eef1f4b50909fd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-05-10T22:19:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-21T07:28:39.000Z", "max_issues_repo_path": "python/dsbox/template/template_files/loaded/SRIClassificationTemplate.py", "max_issues_repo_name": "usc-isi-i2/dsbox-ta2", "max_issues_repo_head_hexsha": "85e0e8f5bbda052fa77cb98f4eef1f4b50909fd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 187, "max_issues_repo_issues_event_min_datetime": "2018-04-13T17:19:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T00:41:15.000Z", "max_forks_repo_path": "python/dsbox/template/template_files/loaded/SRIClassificationTemplate.py", "max_forks_repo_name": "usc-isi-i2/dsbox-ta2", "max_forks_repo_head_hexsha": "85e0e8f5bbda052fa77cb98f4eef1f4b50909fd2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-07-10T00:14:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-25T17:59:44.000Z", "avg_line_length": 48.1578947368, "max_line_length": 274, "alphanum_fraction": 0.4446526151, "include": true, "reason": "import numpy", "num_tokens": 1129}
|
module SeqAdaptiveIS
using StatsBase, Random
# Struct for holding results of inference.
struct MCPosterior
samples::AbstractMatrix
logW::Vector
end
StatsBase.weights(P::MCPosterior) = softmax(P.logW)
# resample(P::MCPosterior, N::Int) = P.samples[rand(Categorical(weights(P)), N),:]
resample(rng::AbstractRNG, P::MCPosterior, N::Int) = P.samples[multicategorical_kitagawa(rng, weights(P), N),:]
resample(P::MCPosterior, N::Int) = resample(Random.GLOBAL_RNG, P, N)
Base.length(P::MCPosterior) = length(P.logW)
ess(P::MCPosterior) = eff_ss(weights(P))
# useful class for holding components of GMM (unlike native impl, cholesky is not calculated)
# Not especially useful outside of this package, so it is not exported by default.
struct GMMComp{T <: Real}
pis::Vector{T}
mus::AbstractMatrix{T}
covs::AbstractArray{T}
end
# AMIS procedure (and GMM / wEM fitting)
include("inference.jl")
# Application to sequential problems
include("sequential.jl")
export amis, resample, ess, seq_amis
end # module
|
{"hexsha": "910f812653e294f9cf640eb58b1323bde65524e8", "size": 1023, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SeqAdaptiveIS.jl", "max_stars_repo_name": "ornithos/SeqAdaptiveIS", "max_stars_repo_head_hexsha": "b01ef2e24e6cab19549382e159f8ddc7a807a9bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-18T22:13:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T17:52:36.000Z", "max_issues_repo_path": "src/SeqAdaptiveIS.jl", "max_issues_repo_name": "ornithos/SeqAdaptiveIS", "max_issues_repo_head_hexsha": "b01ef2e24e6cab19549382e159f8ddc7a807a9bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SeqAdaptiveIS.jl", "max_forks_repo_name": "ornithos/SeqAdaptiveIS", "max_forks_repo_head_hexsha": "b01ef2e24e6cab19549382e159f8ddc7a807a9bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2285714286, "max_line_length": 111, "alphanum_fraction": 0.7399804497, "num_tokens": 285}
|
// Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Warning! This file is autogenerated.
#include <boost/text/bidirectional.hpp>
#include "bidi_tests.hpp"
#include <gtest/gtest.h>
#include <algorithm>
std::vector<int> expected_levels;
std::vector<int> expected_reordered_indices;
TEST(bidi, bidi_570_000)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// LRI RLO CS ET; 4 ('RTL') (line 285001)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x002C, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO CS AN; 4 ('RTL') (line 285002)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x002C, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO CS CS; 4 ('RTL') (line 285003)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x002C, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO CS NSM; 4 ('RTL') (line 285004)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x002C, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO CS ON; 4 ('RTL') (line 285005)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x002C, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM L; 4 ('RTL') (line 285006)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM R; 4 ('RTL') (line 285007)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM AL; 4 ('RTL') (line 285008)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM EN; 4 ('RTL') (line 285009)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM ES; 4 ('RTL') (line 285010)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_001)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// LRI RLO NSM ET; 4 ('RTL') (line 285011)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM AN; 4 ('RTL') (line 285012)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM CS; 4 ('RTL') (line 285013)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM NSM; 4 ('RTL') (line 285014)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO NSM ON; 4 ('RTL') (line 285015)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0300, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS L; 4 ('RTL') (line 285016)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS R; 4 ('RTL') (line 285017)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS AL; 4 ('RTL') (line 285018)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS EN; 4 ('RTL') (line 285019)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS ES; 4 ('RTL') (line 285020)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_002)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// LRI RLO WS ET; 4 ('RTL') (line 285021)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS AN; 4 ('RTL') (line 285022)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS CS; 4 ('RTL') (line 285023)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS NSM; 4 ('RTL') (line 285024)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO WS ON; 4 ('RTL') (line 285025)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0020, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON L; 4 ('RTL') (line 285026)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON R; 4 ('RTL') (line 285027)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON AL; 4 ('RTL') (line 285028)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON EN; 4 ('RTL') (line 285029)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON ES; 4 ('RTL') (line 285030)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_003)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// LRI RLO ON ET; 4 ('RTL') (line 285031)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON AN; 4 ('RTL') (line 285032)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON CS; 4 ('RTL') (line 285033)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON NSM; 4 ('RTL') (line 285034)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI RLO ON ON; 4 ('RTL') (line 285035)
std::vector<uint32_t> const cps = { 0x2066, 0x202E, 0x0021, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI PDF R R; 4 ('RTL') (line 285036)
std::vector<uint32_t> const cps = { 0x2066, 0x202C, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI PDF R AL; 4 ('RTL') (line 285037)
std::vector<uint32_t> const cps = { 0x2066, 0x202C, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI PDF R NSM; 4 ('RTL') (line 285038)
std::vector<uint32_t> const cps = { 0x2066, 0x202C, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI PDF AL R; 4 ('RTL') (line 285039)
std::vector<uint32_t> const cps = { 0x2066, 0x202C, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI PDF AL AL; 4 ('RTL') (line 285040)
std::vector<uint32_t> const cps = { 0x2066, 0x202C, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_004)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// LRI PDF AL NSM; 4 ('RTL') (line 285041)
std::vector<uint32_t> const cps = { 0x2066, 0x202C, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI BN R R; 4 ('RTL') (line 285042)
std::vector<uint32_t> const cps = { 0x2066, 0x00AD, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI BN R AL; 4 ('RTL') (line 285043)
std::vector<uint32_t> const cps = { 0x2066, 0x00AD, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI BN R NSM; 4 ('RTL') (line 285044)
std::vector<uint32_t> const cps = { 0x2066, 0x00AD, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI BN AL R; 4 ('RTL') (line 285045)
std::vector<uint32_t> const cps = { 0x2066, 0x00AD, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI BN AL AL; 4 ('RTL') (line 285046)
std::vector<uint32_t> const cps = { 0x2066, 0x00AD, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// LRI BN AL NSM; 4 ('RTL') (line 285047)
std::vector<uint32_t> const cps = { 0x2066, 0x00AD, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF R R; 4 ('RTL') (line 285048)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF R AL; 4 ('RTL') (line 285049)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF R ES; 4 ('RTL') (line 285050)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x05BE, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_005)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI PDF R ET; 4 ('RTL') (line 285051)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x05BE, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF R CS; 4 ('RTL') (line 285052)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x05BE, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF R NSM; 4 ('RTL') (line 285053)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF R ON; 4 ('RTL') (line 285054)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x05BE, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF AL R; 4 ('RTL') (line 285055)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF AL AL; 4 ('RTL') (line 285056)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF AL ES; 4 ('RTL') (line 285057)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0608, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF AL ET; 4 ('RTL') (line 285058)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0608, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF AL CS; 4 ('RTL') (line 285059)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0608, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF AL NSM; 4 ('RTL') (line 285060)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_006)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI PDF AL ON; 4 ('RTL') (line 285061)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0608, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ES R; 4 ('RTL') (line 285062)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002B, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ES AL; 4 ('RTL') (line 285063)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002B, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ES ES; 4 ('RTL') (line 285064)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002B, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ES ET; 4 ('RTL') (line 285065)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002B, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ES CS; 4 ('RTL') (line 285066)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002B, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ES NSM; 4 ('RTL') (line 285067)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002B, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ES ON; 4 ('RTL') (line 285068)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002B, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ET R; 4 ('RTL') (line 285069)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0023, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ET AL; 4 ('RTL') (line 285070)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0023, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_007)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI PDF ET ES; 4 ('RTL') (line 285071)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0023, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ET ET; 4 ('RTL') (line 285072)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0023, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ET CS; 4 ('RTL') (line 285073)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0023, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ET NSM; 4 ('RTL') (line 285074)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0023, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ET ON; 4 ('RTL') (line 285075)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0023, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF CS R; 4 ('RTL') (line 285076)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002C, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF CS AL; 4 ('RTL') (line 285077)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002C, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF CS ES; 4 ('RTL') (line 285078)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002C, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF CS ET; 4 ('RTL') (line 285079)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002C, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF CS CS; 4 ('RTL') (line 285080)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002C, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_008)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI PDF CS NSM; 4 ('RTL') (line 285081)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002C, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF CS ON; 4 ('RTL') (line 285082)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x002C, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF NSM R; 4 ('RTL') (line 285083)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF NSM AL; 4 ('RTL') (line 285084)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF NSM ES; 4 ('RTL') (line 285085)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0300, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF NSM ET; 4 ('RTL') (line 285086)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0300, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF NSM CS; 4 ('RTL') (line 285087)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0300, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF NSM NSM; 4 ('RTL') (line 285088)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0300, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF NSM ON; 4 ('RTL') (line 285089)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0300, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF WS R; 4 ('RTL') (line 285090)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_009)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI PDF WS AL; 4 ('RTL') (line 285091)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF WS ES; 4 ('RTL') (line 285092)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0020, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF WS ET; 4 ('RTL') (line 285093)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0020, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF WS CS; 4 ('RTL') (line 285094)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0020, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF WS NSM; 4 ('RTL') (line 285095)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0020, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF WS ON; 4 ('RTL') (line 285096)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0020, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ON R; 4 ('RTL') (line 285097)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ON AL; 4 ('RTL') (line 285098)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ON ES; 4 ('RTL') (line 285099)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0021, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ON ET; 4 ('RTL') (line 285100)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0021, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_010)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI PDF ON CS; 4 ('RTL') (line 285101)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0021, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ON NSM; 4 ('RTL') (line 285102)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0021, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI PDF ON ON; 4 ('RTL') (line 285103)
std::vector<uint32_t> const cps = { 0x2067, 0x202C, 0x0021, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN R R; 4 ('RTL') (line 285104)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN R AL; 4 ('RTL') (line 285105)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN R ES; 4 ('RTL') (line 285106)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x05BE, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN R ET; 4 ('RTL') (line 285107)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x05BE, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN R CS; 4 ('RTL') (line 285108)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x05BE, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN R NSM; 4 ('RTL') (line 285109)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN R ON; 4 ('RTL') (line 285110)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x05BE, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_011)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI BN AL R; 4 ('RTL') (line 285111)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN AL AL; 4 ('RTL') (line 285112)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN AL ES; 4 ('RTL') (line 285113)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0608, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN AL ET; 4 ('RTL') (line 285114)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0608, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN AL CS; 4 ('RTL') (line 285115)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0608, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN AL NSM; 4 ('RTL') (line 285116)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN AL ON; 4 ('RTL') (line 285117)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0608, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ES R; 4 ('RTL') (line 285118)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002B, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ES AL; 4 ('RTL') (line 285119)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002B, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ES ES; 4 ('RTL') (line 285120)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002B, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_012)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI BN ES ET; 4 ('RTL') (line 285121)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002B, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ES CS; 4 ('RTL') (line 285122)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002B, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ES NSM; 4 ('RTL') (line 285123)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002B, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ES ON; 4 ('RTL') (line 285124)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002B, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ET R; 4 ('RTL') (line 285125)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0023, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ET AL; 4 ('RTL') (line 285126)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0023, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ET ES; 4 ('RTL') (line 285127)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0023, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ET ET; 4 ('RTL') (line 285128)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0023, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ET CS; 4 ('RTL') (line 285129)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0023, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ET NSM; 4 ('RTL') (line 285130)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0023, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_013)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI BN ET ON; 4 ('RTL') (line 285131)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0023, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN CS R; 4 ('RTL') (line 285132)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002C, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN CS AL; 4 ('RTL') (line 285133)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002C, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN CS ES; 4 ('RTL') (line 285134)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002C, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN CS ET; 4 ('RTL') (line 285135)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002C, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN CS CS; 4 ('RTL') (line 285136)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002C, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN CS NSM; 4 ('RTL') (line 285137)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002C, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN CS ON; 4 ('RTL') (line 285138)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x002C, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN NSM R; 4 ('RTL') (line 285139)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN NSM AL; 4 ('RTL') (line 285140)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_014)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI BN NSM ES; 4 ('RTL') (line 285141)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0300, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN NSM ET; 4 ('RTL') (line 285142)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0300, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN NSM CS; 4 ('RTL') (line 285143)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0300, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN NSM NSM; 4 ('RTL') (line 285144)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0300, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN NSM ON; 4 ('RTL') (line 285145)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0300, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN WS R; 4 ('RTL') (line 285146)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN WS AL; 4 ('RTL') (line 285147)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN WS ES; 4 ('RTL') (line 285148)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0020, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN WS ET; 4 ('RTL') (line 285149)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0020, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN WS CS; 4 ('RTL') (line 285150)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0020, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_015)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// RLI BN WS NSM; 4 ('RTL') (line 285151)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0020, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN WS ON; 4 ('RTL') (line 285152)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0020, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ON R; 4 ('RTL') (line 285153)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ON AL; 4 ('RTL') (line 285154)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ON ES; 4 ('RTL') (line 285155)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0021, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ON ET; 4 ('RTL') (line 285156)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0021, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ON CS; 4 ('RTL') (line 285157)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0021, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ON NSM; 4 ('RTL') (line 285158)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0021, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// RLI BN ON ON; 4 ('RTL') (line 285159)
std::vector<uint32_t> const cps = { 0x2067, 0x00AD, 0x0021, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ES ES; 4 ('RTL') (line 285160)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002B, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_016)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLE ES ET; 4 ('RTL') (line 285161)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002B, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ES CS; 4 ('RTL') (line 285162)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002B, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ES NSM; 4 ('RTL') (line 285163)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002B, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ES ON; 4 ('RTL') (line 285164)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002B, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ET ES; 4 ('RTL') (line 285165)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0023, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ET ET; 4 ('RTL') (line 285166)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0023, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ET CS; 4 ('RTL') (line 285167)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0023, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ET NSM; 4 ('RTL') (line 285168)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0023, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ET ON; 4 ('RTL') (line 285169)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0023, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE CS ES; 4 ('RTL') (line 285170)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002C, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_017)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLE CS ET; 4 ('RTL') (line 285171)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002C, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE CS CS; 4 ('RTL') (line 285172)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002C, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE CS NSM; 4 ('RTL') (line 285173)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002C, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE CS ON; 4 ('RTL') (line 285174)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x002C, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE NSM ES; 4 ('RTL') (line 285175)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0300, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE NSM ET; 4 ('RTL') (line 285176)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0300, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE NSM CS; 4 ('RTL') (line 285177)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0300, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE NSM NSM; 4 ('RTL') (line 285178)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0300, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE NSM ON; 4 ('RTL') (line 285179)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0300, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE WS ES; 4 ('RTL') (line 285180)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0020, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_018)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLE WS ET; 4 ('RTL') (line 285181)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0020, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE WS CS; 4 ('RTL') (line 285182)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0020, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE WS NSM; 4 ('RTL') (line 285183)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0020, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE WS ON; 4 ('RTL') (line 285184)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0020, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ON ES; 4 ('RTL') (line 285185)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0021, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ON ET; 4 ('RTL') (line 285186)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0021, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ON CS; 4 ('RTL') (line 285187)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0021, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ON NSM; 4 ('RTL') (line 285188)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0021, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLE ON ON; 4 ('RTL') (line 285189)
std::vector<uint32_t> const cps = { 0x2068, 0x202B, 0x0021, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L L; 4 ('RTL') (line 285190)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_019)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLO L R; 4 ('RTL') (line 285191)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L AL; 4 ('RTL') (line 285192)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L EN; 4 ('RTL') (line 285193)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L ES; 4 ('RTL') (line 285194)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L ET; 4 ('RTL') (line 285195)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L AN; 4 ('RTL') (line 285196)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L CS; 4 ('RTL') (line 285197)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L NSM; 4 ('RTL') (line 285198)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO L ON; 4 ('RTL') (line 285199)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0041, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO EN L; 4 ('RTL') (line 285200)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0030, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_020)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLO EN EN; 4 ('RTL') (line 285201)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0030, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO EN ES; 4 ('RTL') (line 285202)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0030, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO EN ET; 4 ('RTL') (line 285203)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0030, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO EN AN; 4 ('RTL') (line 285204)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0030, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO EN CS; 4 ('RTL') (line 285205)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0030, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO EN NSM; 4 ('RTL') (line 285206)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0030, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO EN ON; 4 ('RTL') (line 285207)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0030, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ES L; 4 ('RTL') (line 285208)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002B, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ES EN; 4 ('RTL') (line 285209)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002B, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ES ES; 4 ('RTL') (line 285210)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002B, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_021)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLO ES ET; 4 ('RTL') (line 285211)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002B, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ES AN; 4 ('RTL') (line 285212)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002B, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ES CS; 4 ('RTL') (line 285213)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002B, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ES NSM; 4 ('RTL') (line 285214)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002B, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ES ON; 4 ('RTL') (line 285215)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002B, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ET L; 4 ('RTL') (line 285216)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0023, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ET EN; 4 ('RTL') (line 285217)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0023, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ET ES; 4 ('RTL') (line 285218)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0023, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ET ET; 4 ('RTL') (line 285219)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0023, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ET AN; 4 ('RTL') (line 285220)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0023, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_022)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLO ET CS; 4 ('RTL') (line 285221)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0023, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ET NSM; 4 ('RTL') (line 285222)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0023, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ET ON; 4 ('RTL') (line 285223)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0023, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO AN L; 4 ('RTL') (line 285224)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0660, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO AN EN; 4 ('RTL') (line 285225)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0660, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO AN ES; 4 ('RTL') (line 285226)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0660, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO AN ET; 4 ('RTL') (line 285227)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0660, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO AN AN; 4 ('RTL') (line 285228)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0660, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO AN CS; 4 ('RTL') (line 285229)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0660, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO AN NSM; 4 ('RTL') (line 285230)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0660, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_023)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLO AN ON; 4 ('RTL') (line 285231)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0660, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO CS L; 4 ('RTL') (line 285232)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002C, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO CS EN; 4 ('RTL') (line 285233)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002C, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO CS ES; 4 ('RTL') (line 285234)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002C, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO CS ET; 4 ('RTL') (line 285235)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002C, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO CS AN; 4 ('RTL') (line 285236)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002C, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO CS CS; 4 ('RTL') (line 285237)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002C, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO CS NSM; 4 ('RTL') (line 285238)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002C, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO CS ON; 4 ('RTL') (line 285239)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x002C, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO NSM L; 4 ('RTL') (line 285240)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0300, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_024)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLO NSM EN; 4 ('RTL') (line 285241)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0300, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO NSM ES; 4 ('RTL') (line 285242)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0300, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO NSM ET; 4 ('RTL') (line 285243)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0300, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO NSM AN; 4 ('RTL') (line 285244)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0300, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO NSM CS; 4 ('RTL') (line 285245)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0300, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO NSM NSM; 4 ('RTL') (line 285246)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0300, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO NSM ON; 4 ('RTL') (line 285247)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0300, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO WS L; 4 ('RTL') (line 285248)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0020, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO WS EN; 4 ('RTL') (line 285249)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0020, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO WS ES; 4 ('RTL') (line 285250)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0020, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_025)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLO WS ET; 4 ('RTL') (line 285251)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0020, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO WS AN; 4 ('RTL') (line 285252)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0020, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO WS CS; 4 ('RTL') (line 285253)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0020, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO WS NSM; 4 ('RTL') (line 285254)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0020, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO WS ON; 4 ('RTL') (line 285255)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0020, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ON L; 4 ('RTL') (line 285256)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0021, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ON EN; 4 ('RTL') (line 285257)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0021, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ON ES; 4 ('RTL') (line 285258)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0021, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ON ET; 4 ('RTL') (line 285259)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0021, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ON AN; 4 ('RTL') (line 285260)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0021, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_026)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI RLO ON CS; 4 ('RTL') (line 285261)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0021, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ON NSM; 4 ('RTL') (line 285262)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0021, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI RLO ON ON; 4 ('RTL') (line 285263)
std::vector<uint32_t> const cps = { 0x2068, 0x202E, 0x0021, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF R R; 4 ('RTL') (line 285264)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF R AL; 4 ('RTL') (line 285265)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF R ES; 4 ('RTL') (line 285266)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x05BE, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF R ET; 4 ('RTL') (line 285267)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x05BE, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF R CS; 4 ('RTL') (line 285268)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x05BE, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF R NSM; 4 ('RTL') (line 285269)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF R ON; 4 ('RTL') (line 285270)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x05BE, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_027)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI PDF AL R; 4 ('RTL') (line 285271)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF AL AL; 4 ('RTL') (line 285272)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF AL ES; 4 ('RTL') (line 285273)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0608, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF AL ET; 4 ('RTL') (line 285274)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0608, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF AL CS; 4 ('RTL') (line 285275)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0608, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF AL NSM; 4 ('RTL') (line 285276)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF AL ON; 4 ('RTL') (line 285277)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0608, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF ES R; 4 ('RTL') (line 285278)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x002B, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF ES AL; 4 ('RTL') (line 285279)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x002B, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF ET R; 4 ('RTL') (line 285280)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0023, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_028)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI PDF ET AL; 4 ('RTL') (line 285281)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0023, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF CS R; 4 ('RTL') (line 285282)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x002C, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF CS AL; 4 ('RTL') (line 285283)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x002C, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF NSM R; 4 ('RTL') (line 285284)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF NSM AL; 4 ('RTL') (line 285285)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF WS R; 4 ('RTL') (line 285286)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF WS AL; 4 ('RTL') (line 285287)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF ON R; 4 ('RTL') (line 285288)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI PDF ON AL; 4 ('RTL') (line 285289)
std::vector<uint32_t> const cps = { 0x2068, 0x202C, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN R R; 4 ('RTL') (line 285290)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_029)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI BN R AL; 4 ('RTL') (line 285291)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN R ES; 4 ('RTL') (line 285292)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x05BE, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN R ET; 4 ('RTL') (line 285293)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x05BE, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN R CS; 4 ('RTL') (line 285294)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x05BE, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN R NSM; 4 ('RTL') (line 285295)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN R ON; 4 ('RTL') (line 285296)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x05BE, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN AL R; 4 ('RTL') (line 285297)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN AL AL; 4 ('RTL') (line 285298)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN AL ES; 4 ('RTL') (line 285299)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0608, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN AL ET; 4 ('RTL') (line 285300)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0608, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_030)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI BN AL CS; 4 ('RTL') (line 285301)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0608, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN AL NSM; 4 ('RTL') (line 285302)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN AL ON; 4 ('RTL') (line 285303)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0608, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN ES R; 4 ('RTL') (line 285304)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x002B, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN ES AL; 4 ('RTL') (line 285305)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x002B, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN ET R; 4 ('RTL') (line 285306)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0023, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN ET AL; 4 ('RTL') (line 285307)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0023, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN CS R; 4 ('RTL') (line 285308)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x002C, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN CS AL; 4 ('RTL') (line 285309)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x002C, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN NSM R; 4 ('RTL') (line 285310)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_031)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// FSI BN NSM AL; 4 ('RTL') (line 285311)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN WS R; 4 ('RTL') (line 285312)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN WS AL; 4 ('RTL') (line 285313)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN ON R; 4 ('RTL') (line 285314)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// FSI BN ON AL; 4 ('RTL') (line 285315)
std::vector<uint32_t> const cps = { 0x2068, 0x00AD, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE R R; 5 ('auto') (line 285316)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE R R; 5 ('RTL') (line 285316)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE R AL; 5 ('auto') (line 285317)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE R AL; 5 ('RTL') (line 285317)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE R NSM; 5 ('auto') (line 285318)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE R NSM; 5 ('RTL') (line 285318)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE AL R; 5 ('auto') (line 285319)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE AL R; 5 ('RTL') (line 285319)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE AL AL; 5 ('auto') (line 285320)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE AL AL; 5 ('RTL') (line 285320)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_032)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI LRE AL NSM; 5 ('auto') (line 285321)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI LRE AL NSM; 5 ('RTL') (line 285321)
std::vector<uint32_t> const cps = { 0x2069, 0x202A, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R R; 5 ('auto') (line 285322)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R R; 5 ('RTL') (line 285322)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R AL; 5 ('auto') (line 285323)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R AL; 5 ('RTL') (line 285323)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R ES; 5 ('auto') (line 285324)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R ES; 5 ('RTL') (line 285324)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R ET; 5 ('auto') (line 285325)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R ET; 5 ('RTL') (line 285325)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R CS; 5 ('auto') (line 285326)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R CS; 5 ('RTL') (line 285326)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R NSM; 5 ('auto') (line 285327)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R NSM; 5 ('RTL') (line 285327)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R ON; 5 ('auto') (line 285328)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE R ON; 5 ('RTL') (line 285328)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x05BE, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL R; 5 ('auto') (line 285329)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL R; 5 ('RTL') (line 285329)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL AL; 5 ('auto') (line 285330)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL AL; 5 ('RTL') (line 285330)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_033)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLE AL ES; 5 ('auto') (line 285331)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL ES; 5 ('RTL') (line 285331)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL ET; 5 ('auto') (line 285332)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL ET; 5 ('RTL') (line 285332)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL CS; 5 ('auto') (line 285333)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL CS; 5 ('RTL') (line 285333)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL NSM; 5 ('auto') (line 285334)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL NSM; 5 ('RTL') (line 285334)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL ON; 5 ('auto') (line 285335)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE AL ON; 5 ('RTL') (line 285335)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0608, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ES R; 5 ('auto') (line 285336)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ES R; 5 ('RTL') (line 285336)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ES AL; 5 ('auto') (line 285337)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ES AL; 5 ('RTL') (line 285337)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ES ES; 4 ('RTL') (line 285338)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ES ET; 4 ('RTL') (line 285339)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ES CS; 4 ('RTL') (line 285340)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_034)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLE ES NSM; 4 ('RTL') (line 285341)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ES ON; 4 ('RTL') (line 285342)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002B, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET R; 5 ('auto') (line 285343)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET R; 5 ('RTL') (line 285343)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET AL; 5 ('auto') (line 285344)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET AL; 5 ('RTL') (line 285344)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET ES; 4 ('RTL') (line 285345)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET ET; 4 ('RTL') (line 285346)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET CS; 4 ('RTL') (line 285347)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET NSM; 4 ('RTL') (line 285348)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ET ON; 4 ('RTL') (line 285349)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0023, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE CS R; 5 ('auto') (line 285350)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE CS R; 5 ('RTL') (line 285350)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_035)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLE CS AL; 5 ('auto') (line 285351)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE CS AL; 5 ('RTL') (line 285351)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE CS ES; 4 ('RTL') (line 285352)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE CS ET; 4 ('RTL') (line 285353)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE CS CS; 4 ('RTL') (line 285354)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE CS NSM; 4 ('RTL') (line 285355)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE CS ON; 4 ('RTL') (line 285356)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x002C, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE NSM R; 5 ('auto') (line 285357)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE NSM R; 5 ('RTL') (line 285357)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE NSM AL; 5 ('auto') (line 285358)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE NSM AL; 5 ('RTL') (line 285358)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE NSM ES; 4 ('RTL') (line 285359)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE NSM ET; 4 ('RTL') (line 285360)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_036)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLE NSM CS; 4 ('RTL') (line 285361)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE NSM NSM; 4 ('RTL') (line 285362)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE NSM ON; 4 ('RTL') (line 285363)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0300, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS R; 5 ('auto') (line 285364)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS R; 5 ('RTL') (line 285364)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS AL; 5 ('auto') (line 285365)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS AL; 5 ('RTL') (line 285365)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS ES; 4 ('RTL') (line 285366)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS ET; 4 ('RTL') (line 285367)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS CS; 4 ('RTL') (line 285368)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS NSM; 4 ('RTL') (line 285369)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE WS ON; 4 ('RTL') (line 285370)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0020, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_037)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLE ON R; 5 ('auto') (line 285371)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ON R; 5 ('RTL') (line 285371)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ON AL; 5 ('auto') (line 285372)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ON AL; 5 ('RTL') (line 285372)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ON ES; 4 ('RTL') (line 285373)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ON ET; 4 ('RTL') (line 285374)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ON CS; 4 ('RTL') (line 285375)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ON NSM; 4 ('RTL') (line 285376)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE ON ON; 4 ('RTL') (line 285377)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x0021, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE PDI R; 5 ('auto') (line 285378)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE PDI R; 5 ('RTL') (line 285378)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE PDI AL; 5 ('auto') (line 285379)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE PDI AL; 5 ('RTL') (line 285379)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE PDI ES; 4 ('RTL') (line 285380)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_038)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLE PDI ET; 4 ('RTL') (line 285381)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE PDI CS; 4 ('RTL') (line 285382)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE PDI NSM; 4 ('RTL') (line 285383)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLE PDI ON; 4 ('RTL') (line 285384)
std::vector<uint32_t> const cps = { 0x2069, 0x202B, 0x2069, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L L; 4 ('RTL') (line 285385)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L R; 4 ('RTL') (line 285386)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L AL; 4 ('RTL') (line 285387)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L EN; 4 ('RTL') (line 285388)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L ES; 4 ('RTL') (line 285389)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L ET; 4 ('RTL') (line 285390)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_039)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO L AN; 4 ('RTL') (line 285391)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L CS; 4 ('RTL') (line 285392)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L NSM; 4 ('RTL') (line 285393)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO L ON; 4 ('RTL') (line 285394)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0041, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R L; 5 ('auto') (line 285395)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R L; 5 ('RTL') (line 285395)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R R; 5 ('auto') (line 285396)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R R; 5 ('RTL') (line 285396)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R AL; 5 ('auto') (line 285397)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R AL; 5 ('RTL') (line 285397)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R EN; 5 ('auto') (line 285398)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R EN; 5 ('RTL') (line 285398)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R ES; 5 ('auto') (line 285399)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R ES; 5 ('RTL') (line 285399)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R ET; 5 ('auto') (line 285400)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R ET; 5 ('RTL') (line 285400)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_040)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO R AN; 5 ('auto') (line 285401)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R AN; 5 ('RTL') (line 285401)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R CS; 5 ('auto') (line 285402)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R CS; 5 ('RTL') (line 285402)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R NSM; 5 ('auto') (line 285403)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R NSM; 5 ('RTL') (line 285403)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R ON; 5 ('auto') (line 285404)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO R ON; 5 ('RTL') (line 285404)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x05BE, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL L; 5 ('auto') (line 285405)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL L; 5 ('RTL') (line 285405)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL R; 5 ('auto') (line 285406)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL R; 5 ('RTL') (line 285406)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL AL; 5 ('auto') (line 285407)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL AL; 5 ('RTL') (line 285407)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL EN; 5 ('auto') (line 285408)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL EN; 5 ('RTL') (line 285408)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL ES; 5 ('auto') (line 285409)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL ES; 5 ('RTL') (line 285409)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL ET; 5 ('auto') (line 285410)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL ET; 5 ('RTL') (line 285410)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_041)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO AL AN; 5 ('auto') (line 285411)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL AN; 5 ('RTL') (line 285411)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL CS; 5 ('auto') (line 285412)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL CS; 5 ('RTL') (line 285412)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL NSM; 5 ('auto') (line 285413)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL NSM; 5 ('RTL') (line 285413)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL ON; 5 ('auto') (line 285414)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AL ON; 5 ('RTL') (line 285414)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0608, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN L; 4 ('RTL') (line 285415)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN R; 5 ('auto') (line 285416)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN R; 5 ('RTL') (line 285416)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN AL; 5 ('auto') (line 285417)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN AL; 5 ('RTL') (line 285417)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN EN; 4 ('RTL') (line 285418)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN ES; 4 ('RTL') (line 285419)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN ET; 4 ('RTL') (line 285420)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_042)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO EN AN; 4 ('RTL') (line 285421)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN CS; 4 ('RTL') (line 285422)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN NSM; 4 ('RTL') (line 285423)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO EN ON; 4 ('RTL') (line 285424)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0030, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES L; 4 ('RTL') (line 285425)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES R; 5 ('auto') (line 285426)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES R; 5 ('RTL') (line 285426)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES AL; 5 ('auto') (line 285427)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES AL; 5 ('RTL') (line 285427)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES EN; 4 ('RTL') (line 285428)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES ES; 4 ('RTL') (line 285429)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES ET; 4 ('RTL') (line 285430)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_043)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO ES AN; 4 ('RTL') (line 285431)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES CS; 4 ('RTL') (line 285432)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES NSM; 4 ('RTL') (line 285433)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ES ON; 4 ('RTL') (line 285434)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002B, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET L; 4 ('RTL') (line 285435)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET R; 5 ('auto') (line 285436)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET R; 5 ('RTL') (line 285436)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET AL; 5 ('auto') (line 285437)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET AL; 5 ('RTL') (line 285437)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET EN; 4 ('RTL') (line 285438)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET ES; 4 ('RTL') (line 285439)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET ET; 4 ('RTL') (line 285440)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_044)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO ET AN; 4 ('RTL') (line 285441)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET CS; 4 ('RTL') (line 285442)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET NSM; 4 ('RTL') (line 285443)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ET ON; 4 ('RTL') (line 285444)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0023, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN L; 4 ('RTL') (line 285445)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN R; 5 ('auto') (line 285446)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN R; 5 ('RTL') (line 285446)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN AL; 5 ('auto') (line 285447)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN AL; 5 ('RTL') (line 285447)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN EN; 4 ('RTL') (line 285448)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN ES; 4 ('RTL') (line 285449)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN ET; 4 ('RTL') (line 285450)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_045)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO AN AN; 4 ('RTL') (line 285451)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN CS; 4 ('RTL') (line 285452)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN NSM; 4 ('RTL') (line 285453)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO AN ON; 4 ('RTL') (line 285454)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0660, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS L; 4 ('RTL') (line 285455)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS R; 5 ('auto') (line 285456)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS R; 5 ('RTL') (line 285456)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS AL; 5 ('auto') (line 285457)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS AL; 5 ('RTL') (line 285457)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS EN; 4 ('RTL') (line 285458)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS ES; 4 ('RTL') (line 285459)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS ET; 4 ('RTL') (line 285460)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_046)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO CS AN; 4 ('RTL') (line 285461)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS CS; 4 ('RTL') (line 285462)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS NSM; 4 ('RTL') (line 285463)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO CS ON; 4 ('RTL') (line 285464)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x002C, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM L; 4 ('RTL') (line 285465)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM R; 5 ('auto') (line 285466)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM R; 5 ('RTL') (line 285466)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM AL; 5 ('auto') (line 285467)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM AL; 5 ('RTL') (line 285467)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM EN; 4 ('RTL') (line 285468)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM ES; 4 ('RTL') (line 285469)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM ET; 4 ('RTL') (line 285470)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_047)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO NSM AN; 4 ('RTL') (line 285471)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM CS; 4 ('RTL') (line 285472)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM NSM; 4 ('RTL') (line 285473)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO NSM ON; 4 ('RTL') (line 285474)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0300, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS L; 4 ('RTL') (line 285475)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS R; 5 ('auto') (line 285476)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS R; 5 ('RTL') (line 285476)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS AL; 5 ('auto') (line 285477)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS AL; 5 ('RTL') (line 285477)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS EN; 4 ('RTL') (line 285478)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS ES; 4 ('RTL') (line 285479)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS ET; 4 ('RTL') (line 285480)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_048)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO WS AN; 4 ('RTL') (line 285481)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS CS; 4 ('RTL') (line 285482)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS NSM; 4 ('RTL') (line 285483)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO WS ON; 4 ('RTL') (line 285484)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0020, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON L; 4 ('RTL') (line 285485)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON R; 5 ('auto') (line 285486)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON R; 5 ('RTL') (line 285486)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON AL; 5 ('auto') (line 285487)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON AL; 5 ('RTL') (line 285487)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON EN; 4 ('RTL') (line 285488)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON ES; 4 ('RTL') (line 285489)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON ET; 4 ('RTL') (line 285490)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
TEST(bidi, bidi_570_049)
{
expected_levels = { 1, -1, 3, 3 };
expected_reordered_indices = { 3, 2, 0 };
{
// PDI RLO ON AN; 4 ('RTL') (line 285491)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x0660 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON CS; 4 ('RTL') (line 285492)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x002C };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON NSM; 4 ('RTL') (line 285493)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x0300 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO ON ON; 4 ('RTL') (line 285494)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x0021, 0x0021 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO PDI L; 4 ('RTL') (line 285495)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x2069, 0x0041 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO PDI R; 5 ('auto') (line 285496)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x2069, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO PDI R; 5 ('RTL') (line 285496)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x2069, 0x05BE };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO PDI AL; 5 ('auto') (line 285497)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x2069, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), -1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), -1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, -1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO PDI AL; 5 ('RTL') (line 285497)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x2069, 0x0608 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO PDI EN; 4 ('RTL') (line 285498)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x2069, 0x0030 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO PDI ES; 4 ('RTL') (line 285499)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x2069, 0x002B };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
{
// PDI RLO PDI ET; 4 ('RTL') (line 285500)
std::vector<uint32_t> const cps = { 0x2069, 0x202E, 0x2069, 0x0023 };
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), 1);
int i = 0;
for (int l : expected_levels) {
if (0 <= l) {
EXPECT_EQ(levels[i], l) << "i=" << i;
++i;
}
}
EXPECT_EQ((int)levels.size(), i);
std::vector<int> const reordered =
bidi_reordered_indices(cps.begin(), cps.end(), 1);
i = 0;
for (int idx : expected_reordered_indices) {
// Skip FSI, LRI, RLI, and PDI.
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
std::vector<int> reordered_2;
for (auto subrange :
boost::text::bidirectional_subranges(cps, 1)) {
for (auto cp : subrange) {
reordered_2.push_back(cp);
}
}
i = 0;
for (int idx : expected_reordered_indices) {
if (cps[idx] < 0x2066 || 0x2069 < cps[idx]) {
EXPECT_EQ(reordered_2[i], (int)cps[idx])
<< std::hex
<< " 0x" << reordered_2[i]
<< " 0x" << cps[idx]
<< std::dec << " i=" << i;
}
++i;
}
EXPECT_EQ(i, (int)reordered_2.size());
}
}
|
{"hexsha": "704b87cc9af448c45732a2bdb5a1b658b9d2f6df", "size": 961049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/generated/bidi_test_570.cpp", "max_stars_repo_name": "Ryan-rsm-McKenzie/text", "max_stars_repo_head_hexsha": "15aaea4297e00ec4c74295e7913ead79c90e1502", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 265.0, "max_stars_repo_stars_event_min_datetime": "2017-07-09T23:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T10:14:19.000Z", "max_issues_repo_path": "test/generated/bidi_test_570.cpp", "max_issues_repo_name": "Ryan-rsm-McKenzie/text", "max_issues_repo_head_hexsha": "15aaea4297e00ec4c74295e7913ead79c90e1502", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 185.0, "max_issues_repo_issues_event_min_datetime": "2017-08-30T16:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-13T12:02:46.000Z", "max_forks_repo_path": "test/generated/bidi_test_570.cpp", "max_forks_repo_name": "Ryan-rsm-McKenzie/text", "max_forks_repo_head_hexsha": "15aaea4297e00ec4c74295e7913ead79c90e1502", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T23:07:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T06:31:29.000Z", "avg_line_length": 33.1739385571, "max_line_length": 77, "alphanum_fraction": 0.405551642, "num_tokens": 258540}
|
import os
import json
import sys
import numpy as np
from xml.dom.minidom import Document
import xml.dom.minidom
sys.path.append('../../..')
from utils.tools import makedirs
from libs.utils.coordinate_convert import backward_convert, forward_convert
def make_xml(filename, path, box_list, labels, w, h, d):
# dict_box[filename]=json_dict[filename]
doc = xml.dom.minidom.Document()
root = doc.createElement('annotation')
doc.appendChild(root)
foldername = doc.createElement("folder")
foldername.appendChild(doc.createTextNode("JPEGImages"))
root.appendChild(foldername)
nodeFilename = doc.createElement('filename')
nodeFilename.appendChild(doc.createTextNode(filename))
root.appendChild(nodeFilename)
pathname = doc.createElement("path")
pathname.appendChild(doc.createTextNode("xxxx"))
root.appendChild(pathname)
sourcename=doc.createElement("source")
databasename = doc.createElement("database")
databasename.appendChild(doc.createTextNode("Unknown"))
sourcename.appendChild(databasename)
annotationname = doc.createElement("annotation")
annotationname.appendChild(doc.createTextNode("xxx"))
sourcename.appendChild(annotationname)
imagename = doc.createElement("image")
imagename.appendChild(doc.createTextNode("xxx"))
sourcename.appendChild(imagename)
flickridname = doc.createElement("flickrid")
flickridname.appendChild(doc.createTextNode("0"))
sourcename.appendChild(flickridname)
root.appendChild(sourcename)
nodesize = doc.createElement('size')
nodewidth = doc.createElement('width')
nodewidth.appendChild(doc.createTextNode(str(w)))
nodesize.appendChild(nodewidth)
nodeheight = doc.createElement('height')
nodeheight.appendChild(doc.createTextNode(str(h)))
nodesize.appendChild(nodeheight)
nodedepth = doc.createElement('depth')
nodedepth.appendChild(doc.createTextNode(str(d)))
nodesize.appendChild(nodedepth)
root.appendChild(nodesize)
segname = doc.createElement("segmented")
segname.appendChild(doc.createTextNode("0"))
root.appendChild(segname)
for box, label in zip(box_list, labels):
nodeobject = doc.createElement('object')
nodename = doc.createElement('name')
nodename.appendChild(doc.createTextNode(label))
nodeobject.appendChild(nodename)
nodebndbox = doc.createElement('bndbox')
nodex1 = doc.createElement('x1')
nodex1.appendChild(doc.createTextNode(str(box[0])))
nodebndbox.appendChild(nodex1)
nodey1 = doc.createElement('y1')
nodey1.appendChild(doc.createTextNode(str(box[1])))
nodebndbox.appendChild(nodey1)
nodex2 = doc.createElement('x2')
nodex2.appendChild(doc.createTextNode(str(box[2])))
nodebndbox.appendChild(nodex2)
nodey2 = doc.createElement('y2')
nodey2.appendChild(doc.createTextNode(str(box[3])))
nodebndbox.appendChild(nodey2)
nodex3 = doc.createElement('x3')
nodex3.appendChild(doc.createTextNode(str(box[4])))
nodebndbox.appendChild(nodex3)
nodey3 = doc.createElement('y3')
nodey3.appendChild(doc.createTextNode(str(box[5])))
nodebndbox.appendChild(nodey3)
nodex4 = doc.createElement('x4')
nodex4.appendChild(doc.createTextNode(str(box[6])))
nodebndbox.appendChild(nodex4)
nodey4 = doc.createElement('y4')
nodey4.appendChild(doc.createTextNode(str(box[7])))
nodebndbox.appendChild(nodey4)
# ang = doc.createElement('angle')
# ang.appendChild(doc.createTextNode(str(angle)))
# nodebndbox.appendChild(ang)
nodeobject.appendChild(nodebndbox)
root.appendChild(nodeobject)
fp = open(os.path.join(path, filename), 'w')
doc.writexml(fp, indent='\n')
fp.close()
xml_path = '/data/dataset/HRSID_JPG/xmls'
makedirs(xml_path)
fr = open('/data/dataset/HRSID_JPG/annotations/train2017.json', 'r')
data = json.load(fr)
images = data['images']
data_dict = {}
for i in images:
data_dict[i['id']] = {}
data_dict[i['id']]['file_name'] = i['file_name']
data_dict[i['id']]['height'] = i['height']
data_dict[i['id']]['width'] = i['width']
data_dict[i['id']]['bbox'] = []
data_dict[i['id']]['label'] = []
annotations = data['annotations']
for ann in annotations:
bbox = ann['segmentation'][0]
label = 'ship'
data_dict[ann['image_id']]['bbox'].append(bbox)
data_dict[ann['image_id']]['label'].append(label)
for k in data_dict.keys():
bbox = backward_convert(np.array(data_dict[k]['bbox']), False)
bbox = forward_convert(bbox, False)
labels = data_dict[k]['label']
make_xml(filename=data_dict[k]['file_name'].split('.')[0]+'.xml',
path=xml_path,
box_list=bbox,
labels=labels,
w=data_dict[k]['width'],
h=data_dict[k]['height'],
d=3)
|
{"hexsha": "c5ca4fe447b2ec794ed11dd40fda602013ade1a8", "size": 4957, "ext": "py", "lang": "Python", "max_stars_repo_path": "dataloader/dataset/HRSID/json2xml.py", "max_stars_repo_name": "Artcs1/RotationDetection", "max_stars_repo_head_hexsha": "095be17345ee9984d8de8f24eb6b5a0b2d764a06", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 850, "max_stars_repo_stars_event_min_datetime": "2020-10-27T08:51:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:12:06.000Z", "max_issues_repo_path": "dataloader/dataset/HRSID/json2xml.py", "max_issues_repo_name": "Artcs1/RotationDetection", "max_issues_repo_head_hexsha": "095be17345ee9984d8de8f24eb6b5a0b2d764a06", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 94, "max_issues_repo_issues_event_min_datetime": "2020-12-01T02:18:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:14:27.000Z", "max_forks_repo_path": "dataloader/dataset/HRSID/json2xml.py", "max_forks_repo_name": "Artcs1/RotationDetection", "max_forks_repo_head_hexsha": "095be17345ee9984d8de8f24eb6b5a0b2d764a06", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 149, "max_forks_repo_forks_event_min_datetime": "2020-10-29T03:30:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T09:53:23.000Z", "avg_line_length": 33.9520547945, "max_line_length": 75, "alphanum_fraction": 0.6802501513, "include": true, "reason": "import numpy", "num_tokens": 1117}
|
"""
Gaussian likelihood module for shear bandpowers.
"""
import glob
import os.path
import time
import warnings
import numpy as np
def mvg_logpdf_fixedcov(x, mean, inv_cov):
"""
Log-pdf of the multivariate Gaussian distribution where the determinant and inverse of the covariance matrix are
precomputed and fixed.
Note that this neglects the additive constant: -0.5 * (len(x) * log(2 * pi) + log_det_cov), because it is irrelevant
when comparing pdf values with a fixed covariance, but it means that this is not the normalised pdf.
Args:
x (1D numpy array): Vector value at which to evaluate the pdf.
mean (1D numpy array): Mean vector of the multivariate Gaussian distribution.
inv_cov (2D numpy array): Inverted covariance matrix.
Returns:
float: Log-pdf value.
"""
dev = x - mean
return -0.5 * (dev @ inv_cov @ dev)
def setup(obs_bp_path, n_zbin, cov_path, mixmat_path, binmat_path, she_nl_path, noise_lmin, lmax_in, lmin_in, lmax_like,
lmin_like):
"""
Load/precompute anything fixed across parameter space.
Args:
obs_bp_path (str): Path to observed bandpowers in .npz numpy array of shape (n_spectra, n_bandpowers).
n_zbin (int): Number of redshift bins; it is assumed 1 shear field per z bin.
cov_path (str): Path to precomputed covariance in .npz numpy array
of shape (n_spectra * n_bandpowers, n_spectra * n_bandpowers).
mixmat_path (str): Path to mixing matrix.
binmat_path (str): Path to bandpower binning matrix.
she_nl_path (str): Path to noise power spectrum for shear auto-spectra.
noise_lmin (int): Input lmin for the noise power spectra.
lmax_in (int): Maximum l pre-mixing.
lmin_in (int): Minimum l pre-mixing.
lmax_like (int): Maximum l used for the likelihood.
lmin_like (int): Minimum l used for the likelihood.
Returns:
dict: Config dictionary to pass to execute.
"""
# Load observed bandpowers and prepare into a vector
with np.load(obs_bp_path) as data:
obs_bp = data['obs_bp']
n_spec, n_bandpower = obs_bp.shape
assert n_spec == n_zbin * (n_zbin + 1) // 2
n_data = n_spec * n_bandpower
obs_bp = np.reshape(obs_bp, n_data)
# Load and invert covariance
with np.load(cov_path) as data:
cov = data['cov']
assert cov.shape == (n_data, n_data)
inv_cov = np.linalg.inv(cov)
# Load mixing matrix, allowing for it to run from 0
with np.load(mixmat_path) as data:
mixmat = data['mixmat_ee_to_ee']
n_ell_in = lmax_in - lmin_in + 1
n_ell_like = lmax_like - lmin_like + 1
if mixmat.shape == (n_ell_like + lmin_like, n_ell_in + lmin_in):
mixmat = mixmat[lmin_like:, lmin_in:]
assert mixmat.shape == (n_ell_like, n_ell_in)
# Load binning matrix
with np.load(binmat_path) as data:
binmat = data['pbl']
assert binmat.shape == (n_bandpower, n_ell_like)
# Multiply binning and mixing matrices
binmixmat = binmat @ mixmat
assert binmixmat.shape == (n_bandpower, n_ell_in)
# Load noise and trim/pad to correct length for input to mixing matrices,
# truncating power above input_lmax
she_nl = np.loadtxt(she_nl_path, max_rows=(lmax_in - noise_lmin + 1))
she_nl = np.concatenate((np.zeros(noise_lmin), she_nl))[lmin_in:(lmax_in + 1)]
assert she_nl.shape == (n_ell_in, )
# Prepare config dictionary
config = {
'obs_bp': obs_bp,
'n_zbin': n_zbin,
'inv_cov': inv_cov,
'n_spec': n_spec,
'she_nl': she_nl,
'lmax_in': lmax_in,
'lmin_in': lmin_in,
'n_bandpower': n_bandpower,
'binmixmat': binmixmat
}
return config
def execute(theory_cl, theory_lmin, config):
"""
Calculate the joint log likelihood at a particular point in parameter space.
Args:
theory_cl (2D numpy array): Theory power spectra, in diagonal ordering, with shape (n_spectra, n_ell).
theory_lmin (int): l corresponding to the first Cl in each power spectrum (must be consistent between spectra).
config (dict): Config dictionary returned by setup.
Returns:
float: Log-likelihood value.
"""
# Unpack config dictionary
obs_bp = config['obs_bp']
n_zbin = config['n_zbin']
inv_cov = config['inv_cov']
n_spec = config['n_spec']
she_nl = config['she_nl']
lmax_in = config['lmax_in']
lmin_in = config['lmin_in']
n_bandpower = config['n_bandpower']
binmixmat = config['binmixmat']
# Trim/pad theory Cls to correct length for input to mixing matrices, truncating power above lmax_in:
# 1. Trim so power is truncated above lmax_in
theory_cl = theory_cl[:, :(lmax_in - theory_lmin + 1)]
# 2. Pad so theory power runs from 0
theory_cl = np.concatenate((np.zeros((n_spec, theory_lmin)), theory_cl), axis=-1)
# 3. Truncate so it runs from lmin_in
theory_cl = theory_cl[:, lmin_in:]
n_ell_in = lmax_in - lmin_in + 1
assert theory_cl.shape == (n_spec, n_ell_in)
# Add noise to auto-spectra
theory_cl[:n_zbin] += she_nl
# Apply combined mixing and binning matrix and vectorise
exp_bp = np.einsum('bl,sl->sb', binmixmat, theory_cl) # b = bandpower, s = spectrum, l = ell
exp_bp = np.reshape(exp_bp, n_spec * n_bandpower)
# Evalute log pdf
return mvg_logpdf_fixedcov(obs_bp, exp_bp, inv_cov)
def load_cls(n_zbin, she_she_dir, lmax=None, lmin=0):
"""
Load shear-shear power spectra in the correct order (diagonal / healpy new=True ordering).
Args:
n_zbin (int): Number of redshift bins.
she_she_dir (str): Path to directory containing shear-shear power spectra.
lmax (int, optional): If supplied, maximum l to be read in.
lmin (int, optional): If > 0, output will be padded to start at l = 0.
Returns:
2D numpy array: All Cls, with different spectra along the first axis and increasing l along the second, with \
shape (n_spectra, lmax + 1), where n_spectra = n_zbin * (n_zbin + 1) / 2.
"""
# Calculate number of fields assuming 1 shear field per redshift bin
n_field = n_zbin
# Load power spectra in 'diagonal order'
spectra = []
for diag in range(n_field):
for row in range(n_field - diag):
col = row + diag
# Form the path to the Cls - higher bin index goes first
bins = (row + 1, col + 1)
bin1 = max(bins)
bin2 = min(bins)
cl_path = os.path.join(she_she_dir, f'bin_{bin1}_{bin2}.txt')
# Load with appropriate ell range
max_rows = None if lmax is None else (lmax - lmin + 1)
spec = np.concatenate((np.zeros(lmin), np.loadtxt(cl_path, max_rows=max_rows)))
spectra.append(spec)
return np.asarray(spectra)
def run_likelihood(grid_dir, varied_params, save_path, obs_bp_path, n_zbin, cov_path, mixmat_path, binmat_path,
she_nl_path, noise_lmin, lmax_in, lmin_in, lmax_like, lmin_like):
"""
Evaluate the likelihood on a precomputed theory grid as produced using CosmoSIS, and save the result as a text file.
Args:
grid_dir (str): Path to CosmoSIS grid.
varied_params (list): List of varied parameter names as they appear in the cosmological_parameters/values.txt
file.
save_path (str): Path to save output text file to.
obs_bp_path (str): Path to observed bandpowers in .npz format as produced by simulation.get_obs.
n_zbin (int): Number of redshift bins. It will be assumed that there is one shear field per redshift bin.
cov_path (str): Path to covariance matrix, as produced by post_processing.get_composite_covs.
mixmat_path (str): Path to mixing matrix, as produced by post_processing.get_mixmat.
binmat_path (str): Path to bandpower binning matrix.
she_nl_path (str): Path to shear noise power spectrum as a text file.
noise_lmin (int): Minimum l in the input shear noise power spectrun.
lmax_in (int): Maximum l pre-mixing.
lmin_in (int): Minimum l pre-mixing.
lmax_like (int): Maximum l to use in the likelihood.
lmin_like (int): Minimum l to use in the likelihood.
"""
print(f'Starting at {time.strftime("%c")}')
# Setup the likelihood module
print(f'Setting up likelihood module at {time.strftime("%c")}')
config = setup(obs_bp_path, n_zbin, cov_path, mixmat_path, binmat_path, she_nl_path, noise_lmin, lmax_in,
lmin_in, lmax_like, lmin_like)
print(f'Setup complete at {time.strftime("%c")}')
# Loop over every input directory
source_dirs = glob.glob(os.path.join(grid_dir, '_[0-9]*/'))
n_dirs = len(source_dirs)
if n_dirs == 0:
warnings.warn(f'No matching directories. Terminating at {time.strftime("%c")}')
return
n_params = len(varied_params)
if n_params == 0:
warnings.warn(f'No parameters specified. Terminating at {time.strftime("%c")}')
return
first_dir = True
res = []
for i, source_dir in enumerate(source_dirs):
print(f'Calculating likelihood {i + 1} / {n_dirs} at {time.strftime("%c")}')
# Extract cosmological parameters
params = [None]*n_params
values_path = os.path.join(source_dir, 'cosmological_parameters/values.txt')
with open(values_path) as f:
for line in f:
for param_idx, param in enumerate(varied_params):
param_str = f'{param} = '
if param_str in line:
params[param_idx] = float(line[len(param_str):])
err_str = f'Not all parameters in varied_params found in {values_path}'
assert np.all([param is not None for param in params]), err_str
# Check the ells for consistency
if first_dir:
ell = np.loadtxt(os.path.join(source_dir, 'shear_cl/ell.txt'))
theory_lmin = int(ell[0])
first_dir = False
else:
ell_test = np.loadtxt(os.path.join(source_dir, 'shear_cl/ell.txt'))
assert np.allclose(ell, ell_test)
# Load theory Cls
she_she_dir = os.path.join(source_dir, 'shear_cl/')
theory_cl = load_cls(n_zbin, she_she_dir, lmax_in, theory_lmin)
# Evaluate likelihood - theory lmin is now 0 because padded by the above step
log_like_gauss = execute(theory_cl, 0, config)
# Store cosmological params & likelihood
res.append([*params, log_like_gauss])
# Save results to file
res_grid = np.asarray(res)
param_names = ' '.join(varied_params)
header = (f'Output from {__file__}.run_likelihood for parameters:\ngrid_dir = {grid_dir}\n'
f'obs_bp_path = {obs_bp_path}\n,n_zbin = {n_zbin}\ncov_path = {cov_path}\nmixmat_path = {mixmat_path}\n'
f'binmat_path = {binmat_path}\n,she_nl_path = {she_nl_path}\nnoise_lmin = {noise_lmin}\n'
f'lmax_in = {lmax_in}\nlmin_in = {lmin_in}\nlmax_like = {lmax_like}\nlmin_like = {lmin_like}\n'
f'at {time.strftime("%c")}\n\n'
f'{param_names} log_like_gauss')
np.savetxt(save_path, res_grid, header=header)
print('Saved ' + save_path)
print(f'Done at {time.strftime("%c")}')
|
{"hexsha": "b8ba5c723566ddcdc274fdd23c2a658b0917431d", "size": 11429, "ext": "py", "lang": "Python", "max_stars_repo_path": "shear_pcl_cov/likelihood.py", "max_stars_repo_name": "robinupham/shear_pcl_cov", "max_stars_repo_head_hexsha": "6afc8bb48f714b87d4b7143575033b9723ef9df4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shear_pcl_cov/likelihood.py", "max_issues_repo_name": "robinupham/shear_pcl_cov", "max_issues_repo_head_hexsha": "6afc8bb48f714b87d4b7143575033b9723ef9df4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shear_pcl_cov/likelihood.py", "max_forks_repo_name": "robinupham/shear_pcl_cov", "max_forks_repo_head_hexsha": "6afc8bb48f714b87d4b7143575033b9723ef9df4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3851590106, "max_line_length": 120, "alphanum_fraction": 0.6504506081, "include": true, "reason": "import numpy", "num_tokens": 3042}
|
[STATEMENT]
theorem harry_sum_closed_form: "harry_sum n = n * (n + 1) * 2 ^ n div 4"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. harry_sum n = n * (n + 1) * 2 ^ n div 4
[PROOF STEP]
using harry_sum_closed_form_aux[of n]
[PROOF STATE]
proof (prove)
using this:
4 * harry_sum n = n * (n + 1) * 2 ^ n
goal (1 subgoal):
1. harry_sum n = n * (n + 1) * 2 ^ n div 4
[PROOF STEP]
by simp
|
{"llama_tokens": 193, "file": "IMO2019_IMO2019_Q5", "length": 2}
|
import random
import numpy as np
import torch
def get_patch(*args, patch_size=48, scale=2):
ih, iw = args[0].shape[:2]
ip = patch_size
tp = ip * scale
ix = random.randrange(0, iw - ip + 1)
iy = random.randrange(0, ih - ip + 1)
tx, ty = scale * ix, scale * iy
ret = [
args[0][iy:iy + ip, ix:ix + ip, :],
*[a[ty:ty + tp, tx:tx + tp, :] for a in args[1:]]
]
return ret
def set_channel(*args):
return [np.expand_dims(a, axis=2) for a in args]
def np2Tensor(*args):
def _np2Tensor(img):
np_transpose = np.ascontiguousarray(img.transpose((2, 0, 1)))
tensor = torch.from_numpy(np_transpose).float()
return tensor
return [_np2Tensor(a) for a in args]
def augment(*args, hflip=True, rot=True):
hflip = hflip and random.random() < 0.5
vflip = rot and random.random() < 0.5
rot90 = rot and random.random() < 0.5
def _augment(img):
if hflip: img = img[:, ::-1, :]
if vflip: img = img[::-1, :, :]
if rot90: img = img.transpose(1, 0, 2)
return img
return [_augment(a) for a in args]
def normal(lr, hr):
ma = max(hr.max(), lr.max())
mi = min(hr.min(), lr.min())
lr = (lr - mi) / (ma - mi)
hr = (hr - mi) / (ma - mi)
return [lr, hr], [ma, mi]
|
{"hexsha": "20465cda10f50dc996580da4a35e6ba6bd13174e", "size": 1311, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/data/common.py", "max_stars_repo_name": "JintaoLee-Roger/SeismicSuperResolution", "max_stars_repo_head_hexsha": "d89cde2d88f6e523c4133776b40a4987ebbaa880", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-05-17T11:47:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:16:06.000Z", "max_issues_repo_path": "src/data/common.py", "max_issues_repo_name": "JintaoLee-Roger/SeismicSuperResolution", "max_issues_repo_head_hexsha": "d89cde2d88f6e523c4133776b40a4987ebbaa880", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-08T07:25:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T06:29:27.000Z", "max_forks_repo_path": "src/data/common.py", "max_forks_repo_name": "JintaoLee-Roger/SeismicSuperResolution", "max_forks_repo_head_hexsha": "d89cde2d88f6e523c4133776b40a4987ebbaa880", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-12-31T11:03:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T06:39:14.000Z", "avg_line_length": 23.4107142857, "max_line_length": 69, "alphanum_fraction": 0.5476735317, "include": true, "reason": "import numpy", "num_tokens": 430}
|
\chapter{Moves in Detail}
\index{Moves in Detail} \index{Moves} \index{Detail}
|
{"hexsha": "0601652ba9bf11a0fb9872417f46eea0f6b6d750", "size": 89, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/dwpocket_038_Moves_in_Detail.tex", "max_stars_repo_name": "maxlambertini/DungeonWorld-ConTeXt", "max_stars_repo_head_hexsha": "3066435d403380cd603436bc0523a04c874c03f1", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-10-07T08:56:40.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-07T08:56:40.000Z", "max_issues_repo_path": "tex/dwpocket_038_Moves_in_Detail.tex", "max_issues_repo_name": "maxlambertini/DungeonWorld-ConTeXt", "max_issues_repo_head_hexsha": "3066435d403380cd603436bc0523a04c874c03f1", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/dwpocket_038_Moves_in_Detail.tex", "max_forks_repo_name": "maxlambertini/DungeonWorld-ConTeXt", "max_forks_repo_head_hexsha": "3066435d403380cd603436bc0523a04c874c03f1", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-04-19T20:29:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T18:19:27.000Z", "avg_line_length": 14.8333333333, "max_line_length": 54, "alphanum_fraction": 0.6629213483, "num_tokens": 26}
|
import os
import cv2
import numpy as np
from os.path import join, dirname
# Trained XML car classifier that describes some features of cars which we want to detect
cascade_file = join(dirname(__file__), "haarcascade_car.xml")
cars_cascade = cv2.CascadeClassifier(cascade_file)
videos_directory = join(os.getcwd(), "videos")
video_file = "cars.mp4"
writer = cv2.VideoWriter_fourcc(*'MJPG')
def main():
video = cv2.VideoCapture(f"{join(videos_directory,video_file)}")
# create vi
out_file = join(videos_directory, "output.avi")
out = cv2.VideoWriter(out_file, writer,
30, (1280, 720))
while video.isOpened():
ret, frame = video.read()
'''
# get the frame dimensions to use in the VideoWriter object
fshape = frame.shape
fheight = fshape[0]
fwidth = fshape[1]
print(fwidth, fheight)
'''
controlkey = cv2.waitKey(1)
if ret:
cars = cars_cascade.detectMultiScale(frame, 1.25, 4)
for (x, y, w, h) in cars:
cv2.rectangle(frame, (x, y), (x+w, y+h),
color=(0, 255, 0), thickness=2)
out.write(frame)
cv2.imshow('frame', frame)
else:
break
if controlkey == ord('q'):
break
video.release()
out.release()
cv2.destroyAllWindows()
def test():
# test video saving
writer = cv2.VideoWriter("output.avi",
cv2.VideoWriter_fourcc(*"MJPG"), 30, (640, 480))
for frame in range(1000):
writer.write(np.random.randint(0, 255, (480, 640, 3)).astype('uint8'))
writer.release()
if __name__ == "__main__":
main()
|
{"hexsha": "03ef973a9345dd8b96d75ef6f07b72387c9b1dec", "size": 1720, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/car_detection/car_detect.py", "max_stars_repo_name": "DanNduati/Parking-Management-System", "max_stars_repo_head_hexsha": "0bd9c254c49f9685b4442fbec43e36b5fb2b471b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/car_detection/car_detect.py", "max_issues_repo_name": "DanNduati/Parking-Management-System", "max_issues_repo_head_hexsha": "0bd9c254c49f9685b4442fbec43e36b5fb2b471b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/car_detection/car_detect.py", "max_forks_repo_name": "DanNduati/Parking-Management-System", "max_forks_repo_head_hexsha": "0bd9c254c49f9685b4442fbec43e36b5fb2b471b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6551724138, "max_line_length": 89, "alphanum_fraction": 0.5854651163, "include": true, "reason": "import numpy", "num_tokens": 438}
|
#!/bin/julia
include("./lib/core/eq-core.jl")
include("./lib/core/score-engine.jl")
include("./lib/core/dealer.jl")
using CSV
using DelimitedFiles
chan = Channel(256)
function main(args)
num_players = parse(Int, args[1])
trials = parse(Int, args[2])
player_range = CSV.read(args[3])
output = args[4]
range_equity::Array{Float64, 2} = zeros(Float64, 13, 13)
for i in 1:13
for j in 1:13
start(num_players, trials, player_range, i, j)
end
end
for _ in 1:13
for _ in 1:13
i, j, equity = take!(chan)
range_equity[i, j] = round(equity, digits=4)
end
end
writedlm(output, ["A" "K" "Q" "J" "T" "9" "8" "7" "6" "5" "4" "3" "2"], ",")
open(output, "a") do io
writedlm(io, range_equity, ",")
end
end
function start(num_players::Int, trials::Int, player_range, i::Int, j::Int)
pot::Float64 = trials
deck::Deck = generate_deck()
k_i = length(deck.cards)-i+1
k_j = if j <= i
length(deck.cards)-13-j+1
else
length(deck.cards)-j+1
end
player::Player = Player(1, Hole(1, deck.cards[k_i], deck.cards[k_j]))
if k_i < k_j
deleteat!(deck.cards, k_j)
deleteat!(deck.cards, k_i)
else
deleteat!(deck.cards, k_i)
deleteat!(deck.cards, k_j)
end
players::Vector{Player} = []
for p in 2:num_players
push!(players, Player(p, Hole(p, Card(Ranks.NULL, Suits.NULL), Card(Ranks.NULL, Suits.NULL))))
end
board::Board = Board(Card(Ranks.NULL, Suits.NULL), Card(Ranks.NULL, Suits.NULL), Card(Ranks.NULL, Suits.NULL), Card(Ranks.NULL, Suits.NULL), Card(Ranks.NULL, Suits.NULL))
predeal_shuffle!(deck)
for t in 1:trials
pot -= 1
deal!(deck, players...)
flop!(deck, board)
turn!(deck, board)
river!(deck, board)
hands::Vector{Hand} = []
push!(hands, score(player, board))
for p in players
p_i, p_j = 0, 0
if compare(p.hole.card1, p.hole.card2) >= 0
if p.hole.card1.suit == p.hole.card2.suit
p_i = 15-Int(p.hole.card1.rank)
p_j = 15-Int(p.hole.card2.rank)
else
p_i = 15-Int(p.hole.card2.rank)
p_j = 15-Int(p.hole.card1.rank)
end
else
if p.hole.card1.suit == p.hole.card2.suit
p_i = 15-Int(p.hole.card2.rank)
p_j = 15-Int(p.hole.card1.rank)
else
p_i = 15-Int(p.hole.card1.rank)
p_j = 15-Int(p.hole.card2.rank)
end
end
if player_range[p_i, p_j] == 0
continue
end
push!(hands, score(p, board))
end
if length(hands) == 1
pot += 1
reshuffle!(deck)
continue
end
best_hands::Vector{Hand} = compare_hands(hands...)
for hand in best_hands
if hand.playerID == 1
pot += num_players / length(best_hands)
end
end
reshuffle!(deck)
end
equity = pot / (num_players * trials)
put!(chan, (i, j, equity))
end
@time main(ARGS)
|
{"hexsha": "36ce7766755cc3de16eb9836f8db9b6de158797a", "size": 3299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "EQPoker.jl", "max_stars_repo_name": "ttowncompiled/EQPoker", "max_stars_repo_head_hexsha": "6a984b2e1d114e8437b3af11392cff68adda32dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-30T22:19:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-30T22:19:33.000Z", "max_issues_repo_path": "EQPoker.jl", "max_issues_repo_name": "ttowncompiled/EQPoker", "max_issues_repo_head_hexsha": "6a984b2e1d114e8437b3af11392cff68adda32dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-24T21:08:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-24T21:08:43.000Z", "max_forks_repo_path": "EQPoker.jl", "max_forks_repo_name": "ttowncompiled/EQPoker", "max_forks_repo_head_hexsha": "6a984b2e1d114e8437b3af11392cff68adda32dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9909090909, "max_line_length": 174, "alphanum_fraction": 0.5186420127, "num_tokens": 974}
|
;; ---------------------------------------------------------------------
;; text_manipulate.jl
;;
;; Mar/02/2011
;;
;; --------------------------------------------------------------------
(require 'tables)
;; --------------------------------------------------------------------
(defun dict_display_proc_single (key unit_bb)
(format t (concat key "\t"
(table-ref unit_bb "name") "\t"
(table-ref unit_bb "population") "\t"
(table-ref unit_bb "date_mod")))
)
;; --------------------------------------------------------------------
(define (text_read_line_proc out_str delimit dict_aa)
(string-match delimit out_str)
(setq id (substring out_str 0 (match-start 0) ))
(setq str_bb (substring out_str (+ (match-start 0) 1)))
(string-match delimit str_bb)
(setq name (substring str_bb 0 (match-start 0)))
(setq str_cc (substring str_bb (+ (match-start 0) 1)))
(string-match delimit str_cc)
(setq population (substring str_cc 0 (match-start 0)))
; (setq date_mod (substring str_cc (+ (match-start 0) 1)))
(setq str_dd (substring str_cc (+ (match-start 0) 1)))
(string-match "\n" str_dd)
(setq date_mod (substring str_dd 0 (match-start 0)))
(dict_append_proc dict_aa id name population date_mod)
)
;; --------------------------------------------------------------------
(define (text_read_proc port dict_aa)
(let ((out_str (read-line port)))
(if out_str (progn
(setq delimit "\t")
; (format standard-output "%1$s" out_str)
(text_read_line_proc out_str delimit dict_aa)
(text_read_proc port dict_aa)
)
)
)
)
;; --------------------------------------------------------------------
(defun dict_append_proc (dict_aa id_in name population date_mod)
(setq unit_pp (make-table string-hash string=))
(table-set unit_pp "name" name)
(table-set unit_pp "population" population)
(table-set unit_pp "date_mod" date_mod)
(table-set dict_aa id_in unit_pp)
;
dict_aa)
;; --------------------------------------------------------------------
(defun dict_write_proc_single (fp-file key unit_bb delimit)
(write fp-file (concat key delimit
(table-ref unit_bb "name") delimit
(table-ref unit_bb "population") delimit
(table-ref unit_bb "date_mod") "\n"))
)
;; --------------------------------------------------------------------
(defun text_write_proc (file_out dict_aa)
(setq delimit "\t")
(let ((fp-file (open-file file_out 'write)))
(table-walk (lambda (key value)
(dict_write_proc_single fp-file key value delimit)) dict_aa)
)
)
;; --------------------------------------------------------------------
(define (dict_update_proc doc_aa id_in population_in)
(format t "%1$s" (tablep doc_aa))
;
(let ((uu (table-ref doc_aa id_in))
(today (current-time-string nil "%Y-%m-%d")))
(progn
(print "*** dict_update_proc *** pppp ***")
(format t (table-ref uu "population"))
(table-set uu "population" population_in)
(table-set uu "date_mod" today)
(print "*** dict_update_proc *** end ***\n")
)
)
)
;; --------------------------------------------------------------------
(define (csv_read_proc port dict_aa)
(let ((out_str (read-line port)))
(if out_str (progn
(setq delimit ",")
(text_read_line_proc out_str delimit dict_aa)
(csv_read_proc port dict_aa)
)
)
)
)
;; --------------------------------------------------------------------
(defun csv_write_proc (file_out dict_aa)
(setq delimit ",")
(let ((fp-file (open-file file_out 'write)))
(table-walk (lambda (key value)
(dict_write_proc_single fp-file key value delimit)) dict_aa)
)
)
;; --------------------------------------------------------------------
|
{"hexsha": "039a5a6e58b438640daba00af3a5395baa84f7e7", "size": 3567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "common/rep_common/text_manipulate.jl", "max_stars_repo_name": "ekzemplaro/data_base_language", "max_stars_repo_head_hexsha": "e77030367ffc595f1fac8583f03f9a3ce5eb1611", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-05-12T16:44:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T00:39:24.000Z", "max_issues_repo_path": "common/rep_common/text_manipulate.jl", "max_issues_repo_name": "ekzemplaro/data_base_language", "max_issues_repo_head_hexsha": "e77030367ffc595f1fac8583f03f9a3ce5eb1611", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/rep_common/text_manipulate.jl", "max_forks_repo_name": "ekzemplaro/data_base_language", "max_forks_repo_head_hexsha": "e77030367ffc595f1fac8583f03f9a3ce5eb1611", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5663716814, "max_line_length": 72, "alphanum_fraction": 0.5298570227, "num_tokens": 807}
|
### A Pluto.jl notebook ###
# v0.12.15
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
el
end
end
# ╔═╡ 9795c3e0-33f9-11eb-14f0-d12d158539e2
using Plots
# ╔═╡ d6ba3460-33fa-11eb-314e-a102bf58747d
using PlutoUI
# ╔═╡ 9fd82cf0-33f9-11eb-1bcb-afef2c71688b
cardioid(a, t) = a * (1 - cos(t)) .* (cos(t), sin(t))
# ╔═╡ ae072830-33f9-11eb-00dd-87760f6fdbbd
md"""
Vary the $\theta$-slider to draw the cardioid $r = a(1 - \cos \theta),~ 0 \leq \theta \leq 2\pi,~ a = 1$.
"""
# ╔═╡ bceec510-33f9-11eb-3d94-a3d7d660dee5
begin
θ_slider = @bind θ Slider(0.:1e-3:2π)
md"""
θ: $(θ_slider)
"""
end
# ╔═╡ d508a940-33f9-11eb-2550-1984c73124f8
plot(cardioid.(1, 0:1e-3:θ), label = "Cardioid", xlims=(-2.25,0.75), ylims=(-1.5,1.5))
# ╔═╡ cf4745c0-33f9-11eb-39ce-efbae4b35676
log_spiral(a, b, θ) = a * exp(b * θ) .* (cos(θ), sin(θ))
# ╔═╡ d995f990-33f9-11eb-372c-adc2227982a5
φ = (1 + √5) / 2
# ╔═╡ dfd58dc0-33f9-11eb-2213-014573741740
# Fibonacci constant
b = log(φ) / (π/2)
# ╔═╡ e96ead30-33f9-11eb-29bb-2b64474204b2
md"""
Draw the Fibonacci spiral!
"""
# ╔═╡ fcf32abe-33f9-11eb-0456-cf2e17bc6995
begin
t_slider = @bind t Slider(0.:1e-2:15π)
md"""
θ: $(t_slider)
"""
end
# ╔═╡ 0da9bb40-33fa-11eb-19df-673cb9106c7a
plot(log_spiral.(1, atan(b), 0:1e-3:t), label = "Fibonacci Spiral")
# ╔═╡ f5f9bc70-33f9-11eb-0b55-5f73e5b1ec96
dickbutt(t) = (((sign(t)*sign(1-t)+1)*(1315*t^3-1905*t^2+840*t+15775)+(sign(t-1)*sign(2-t)+1)*(5455*t^3-36015*t^2+66090*t-19505)+(sign(t-2)*sign(3-t)+1)*(3164*t^3-27165*t^2+78981*t-58723)+(sign(t-3)*sign(4-t)+1)*(-528*t^3+5544*t^2-19008*t+38475)+(sign(t-4)*sign(5-t)+1)*(-273*t^3+222*t^2+17928*t-41156)+(sign(t-5)*sign(6-t)+1)*(3154*t^3-54165*t^2+304623*t-543331)+(sign(t-6)*sign(7-t)+1)*(-1239*t^3+24840*t^2-167043*t+391373)+(sign(t-7)*sign(8-t)+1)*(-1175*t^3+30597*t^2-260517*t+741646)+(sign(t-8)*sign(9-t)+1)*(-354*t^3+8658*t^2-69795*t+199614)+(sign(t-9)*sign(10-t)+1)*(-6562*t^3+195444*t^2-1940280*t+6429945)+(sign(t-10)*sign(11-t)+1)*(-2770*t^3+87867*t^2-926556*t+3258405)+(sign(t-11)*sign(12-t)+1)*(-2673*t^3+96666*t^2-1166910*t+4712751)+(sign(t-12)*sign(13-t)+1)*(578*t^3-20832*t^2+247758*t-960343)+(sign(t-13)*sign(14-t)+1)*(629*t^3-21423*t^2+234534*t-800599)+(sign(t-14)*sign(15-t)+1)*(196*t^3-8433*t^2+122160*t-585251)+(sign(t-15)*sign(16-t)+1)*(588*t^3-28224*t^2+450084*t-2370410)+(sign(t-16)*sign(17-t)+1)*(-1013*t^3+46845*t^2-718551*t+3667782)+(sign(t-17)*sign(18-t)+1)*(1556*t^3-81867*t^2+1434753*t-8362102)+(sign(t-18)*sign(19-t)+1)*(-308*t^3+17067*t^2-316209*t+1972565)+(sign(t-19)*sign(20-t)+1)*(2256*t^3-128730*t^2+2446311*t-15469074)+(sign(t-20)*sign(21-t)+1)*(-1204*t^3+69690*t^2-1339521*t+8567133)+(sign(t-21)*sign(22-t)+1)*(5577*t^3-362229*t^2+7844511*t-56622289)+(sign(t-22)*sign(23-t)+1)*(3443*t^3-234849*t^2+5337006*t-40386267)+(sign(t-23)*sign(24-t)+1)*(138*t^3-8718*t^2+181218*t-1214507)+(sign(t-24)*sign(25-t)+1)*(-1606*t^3+116121*t^2-2797179*t+22468813)+(sign(t-25)*sign(26-t)+1)*(510*t^3-39015*t^2+994500*t-8430184)+(sign(t-26)*sign(27-t)+1)*(874*t^3-68583*t^2+1793244*t-15606096)+(sign(t-27)*sign(28-t)+1)*(4520*t^3-369750*t^2+10079733*t-91558537)+(sign(t-28)*sign(29-t)+1)*(-72*t^3+5118*t^2-115953*t+827743)+(sign(t-29)*sign(30-t)+1)*(-2688*t^3+233913*t^2-6782205*t+65536125)+(sign(t-30)*sign(31-t)+1)*(2466*t^3-221274*t^2+6614814*t-65864145)+(sign(t-31)*sign(32-t)+1)*(-443*t^3+39552*t^2-1173078*t+11568742)+(sign(t-32)*sign(33-t)+1)*(-919*t^3+92427*t^2-3095331*t+34534406)+(sign(t-33)*sign(34-t)+1)*(570*t^3-61758*t^2+2217627*t-26398769)+(sign(t-34)*sign(35-t)+1)*(744*t^3-73845*t^2+2439450*t-26807075)+(sign(t-35)*sign(36-t)+1)*(445*t^3-49371*t^2+1822152*t-22362801)+(sign(t-36)*sign(37-t)+1)*(-1513*t^3+167979*t^2-6214362*t+76618551))/10000, ((sign(t)*sign(1-t)+1)*(552*t^3-1179*t^2+2877*t+12350)+(sign(t-1)*sign(2-t)+1)*(-7*t^3-14604*t^2+50079*t-20868)+(sign(t-2)*sign(3-t)+1)*(-218*t^3+585*t^2+495*t+11511)+(sign(t-3)*sign(4-t)+1)*(836*t^3-8778*t^2+30096*t-21231)+(sign(t-4)*sign(5-t)+1)*(2427*t^3-35316*t^2+167970*t-250507)+(sign(t-5)*sign(6-t)+1)*(2869*t^3-43467*t^2+215052*t-337392)+(sign(t-6)*sign(7-t)+1)*(2650*t^3-49278*t^2+301407*t-599022)+(sign(t-7)*sign(8-t)+1)*(-3964*t^3+84990*t^2-603525*t+1424972)+(sign(t-8)*sign(9-t)+1)*(-390*t^3+9960*t^2-83472*t+236580)+(sign(t-9)*sign(10-t)+1)*(-3567*t^3+103950*t^2-1001430*t+3201045)+(sign(t-10)*sign(11-t)+1)*(-3200*t^3+100104*t^2-1038042*t+3584765)+(sign(t-11)*sign(12-t)+1)*(-183*t^3+6231*t^2-69453*t+270896)+(sign(t-12)*sign(13-t)+1)*(1338*t^3-47853*t^2+566463*t-2210004)+(sign(t-13)*sign(14-t)+1)*(-6596*t^3+262383*t^2-3475191*t+15332612)+(sign(t-14)*sign(15-t)+1)*(-567*t^3+24870*t^2-361902*t+1755538)+(sign(t-15)*sign(16-t)+1)*(-513*t^3+23949*t^2-375684*t+1993260)+(sign(t-16)*sign(17-t)+1)*(1025*t^3-49179*t^2+784419*t-4147268)+(sign(t-17)*sign(18-t)+1)*(1245*t^3-63030*t^2+1061832*t-5940923)+(sign(t-18)*sign(19-t)+1)*(4519*t^3-249483*t^2+4586385*t-28061937)+(sign(t-19)*sign(20-t)+1)*(2191*t^3-128025*t^2+2492208*t-16151160)+(sign(t-20)*sign(21-t)+1)*(3221*t^3-196482*t^2+3992868*t-27022060)+(sign(t-21)*sign(22-t)+1)*(-4713*t^3+300819*t^2-6395349*t+45300018)+(sign(t-22)*sign(23-t)+1)*(1193*t^3-80574*t^2+1810695*t-13525826)+(sign(t-23)*sign(24-t)+1)*(416*t^3-29037*t^2+675039*t-5215052)+(sign(t-24)*sign(25-t)+1)*(-352*t^3+24447*t^2-565107*t+4358500)+(sign(t-25)*sign(26-t)+1)*(582*t^3-44523*t^2+1134900*t-9629639)+(sign(t-26)*sign(27-t)+1)*(811*t^3-64980*t^2+1734936*t-15425356)+(sign(t-27)*sign(28-t)+1)*(-772*t^3+63432*t^2-1738410*t+15910109)+(sign(t-28)*sign(29-t)+1)*(-802*t^3+69090*t^2-1983174*t+18986189)+(sign(t-29)*sign(30-t)+1)*(-3662*t^3+324837*t^2-9602070*t+94602487)+(sign(t-30)*sign(31-t)+1)*(2270*t^3-208773*t^2+6397752*t-65307173)+(sign(t-31)*sign(32-t)+1)*(2160*t^3-203499*t^2+6389070*t-66827661)+(sign(t-32)*sign(33-t)+1)*(-1965*t^3+191052*t^2-6190248*t+66858291)+(sign(t-33)*sign(34-t)+1)*(4280*t^3-428631*t^2+14306211*t-159115377)+(sign(t-34)*sign(35-t)+1)*(-2519*t^3+260031*t^2-8945484*t+102576877)+(sign(t-35)*sign(36-t)+1)*(1757*t^3-185985*t^2+6560850*t-77108863)+(sign(t-36)*sign(37-t)+1)*(-1907*t^3+207681*t^2-7537566*t+91190561))/10000)
# ╔═╡ ccb66c40-33fa-11eb-1089-6921936f1b1f
begin
butt_slider = @bind butt Slider(0.:1e-3:37)
md"""
butt: $(butt_slider)
"""
end
# ╔═╡ 19671a40-33fa-11eb-2902-6ba2b9d566e2
plot(dickbutt.(0:1e-3:butt), label = "Economist")
# ╔═╡ Cell order:
# ╠═9795c3e0-33f9-11eb-14f0-d12d158539e2
# ╠═d6ba3460-33fa-11eb-314e-a102bf58747d
# ╠═9fd82cf0-33f9-11eb-1bcb-afef2c71688b
# ╟─ae072830-33f9-11eb-00dd-87760f6fdbbd
# ╟─bceec510-33f9-11eb-3d94-a3d7d660dee5
# ╟─d508a940-33f9-11eb-2550-1984c73124f8
# ╠═cf4745c0-33f9-11eb-39ce-efbae4b35676
# ╠═d995f990-33f9-11eb-372c-adc2227982a5
# ╠═dfd58dc0-33f9-11eb-2213-014573741740
# ╟─e96ead30-33f9-11eb-29bb-2b64474204b2
# ╟─fcf32abe-33f9-11eb-0456-cf2e17bc6995
# ╟─0da9bb40-33fa-11eb-19df-673cb9106c7a
# ╟─f5f9bc70-33f9-11eb-0b55-5f73e5b1ec96
# ╟─ccb66c40-33fa-11eb-1089-6921936f1b1f
# ╠═19671a40-33fa-11eb-2902-6ba2b9d566e2
|
{"hexsha": "75f8c088fce4a9a8827a12e3596b2a89e45087da", "size": 7311, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/Plotting.jl", "max_stars_repo_name": "MathAero/IndEco", "max_stars_repo_head_hexsha": "b4179ee32fed85f87931b8f12afe6bee24113879", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Plotting.jl", "max_issues_repo_name": "MathAero/IndEco", "max_issues_repo_head_hexsha": "b4179ee32fed85f87931b8f12afe6bee24113879", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Plotting.jl", "max_forks_repo_name": "MathAero/IndEco", "max_forks_repo_head_hexsha": "b4179ee32fed85f87931b8f12afe6bee24113879", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.3711340206, "max_line_length": 4763, "alphanum_fraction": 0.6611954589, "num_tokens": 3719}
|
#!/usr/bin/python
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Extract flight path from h5 log and produce Google Earth KML file.
"""
import sys
import textwrap
import gflags
import h5py
from makani.common.c_math import coord_trans
from makani.control import control_types
from makani.control import ground_frame
from makani.lib.python import c_helpers
import numpy as np
_FLIGHT_MODE_HELPER = c_helpers.EnumHelper('FlightMode', control_types)
gflags.DEFINE_string('output_file', None, 'Name of output KML file.')
gflags.DEFINE_boolean('quiet', False, 'Suppress progress messages.')
gflags.MarkFlagAsRequired('output_file')
FLAGS = gflags.FLAGS
def GetGsPosLlhVec3(control_telemetry):
"""Get ground station position in latitude, longitude, and height (LLH).
Args:
control_telemetry: ControlDebug or ControlTelemetry message
structure from h5 log.
Returns:
Ground station position in LLH as Vec3 object.
"""
gs_pos_ecef = control_telemetry['control_input']['gs_gps']['pos']
gs_pos_ecef_vec3 = coord_trans.Vec3(x=gs_pos_ecef['x'][-1],
y=gs_pos_ecef['y'][-1],
z=gs_pos_ecef['z'][-1])
gs_pos_llh_vec3 = coord_trans.Vec3()
coord_trans.EcefToLlh(gs_pos_ecef_vec3, gs_pos_llh_vec3)
return gs_pos_llh_vec3
def PrintKmlHeader(f, description=None):
"""Write KML header."""
f.write(textwrap.dedent("""\
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Paths</name>
"""))
if description is not None:
f.write('<description>' + description + '</description>\n')
def PrintStyle(f, name, line_color=None, line_width=None, color=None):
"""Write a KML <Style> tag."""
f.write('<Style id="%s">' % name)
if line_color is not None or line_width is not None:
f.write('<LineStyle>')
if line_color is not None:
f.write('<color>%s</color>' % line_color)
if line_width is not None:
f.write('<width>%d</width>' % line_width)
f.write('</LineStyle>')
if color is not None:
f.write('<PolyStyle><color>%s</color></PolyStyle>' % color)
f.write('</Style>\n')
# Infuriatingly, KML uses the color order alpha-blue-green-red
# instead of the otherwise-standard alpha-red-green-blue. So HTML
# color codes need to be permuted.
hover_modes = ['HoverAscend', 'HoverPayOut', 'HoverFullLength', 'HoverAccel',
'HoverTransOut', 'HoverReelIn', 'HoverDescend',
'HoverTransformGsDown', 'HoverTransformGsUp']
for (flight_mode_name, color) in (
[('Perched', 'ff5733ff'),
('PilotHover', 'ff58eeff')] +
[(hover_mode, 'ff00c3ff') for hover_mode in hover_modes] +
[('TransIn', 'ff5733ff'),
('CrosswindNormal', 'ffb98029'),
('CrosswindPrepTransOut', 'ff85a016'),
('OffTether', 'ffff007f')]):
PrintStyle(f, name=flight_mode_name, line_color=color, line_width=4)
def PrintKmlFooter(f):
"""Write KML footer."""
f.write('</Document>\n</kml>\n')
def PrintCoordsLlh(f, wing_pos_g, g_heading, gs_pos_llh_vec3):
"""Write a list of LLH coordinates.
Args:
f: file handle.
wing_pos_g: wing position in ground coordinates.
g_heading: Ground frame heading w.r.t. true north.
gs_pos_llh_vec3: Vec3 object containing ground station LLH.
"""
wing_pos_g_vec3 = ground_frame.Vec3()
wing_pos_ned_vec3 = ground_frame.Vec3()
wing_pos_llh_vec3 = coord_trans.Vec3()
for wing_pos in wing_pos_g:
wing_pos_g_vec3.x = wing_pos['x']
wing_pos_g_vec3.y = wing_pos['y']
wing_pos_g_vec3.z = wing_pos['z']
ground_frame.GToNed(wing_pos_g_vec3, g_heading, wing_pos_ned_vec3)
coord_trans.NedToLlh(coord_trans.Vec3(x=wing_pos_ned_vec3.x,
y=wing_pos_ned_vec3.y,
z=wing_pos_ned_vec3.z),
gs_pos_llh_vec3, wing_pos_llh_vec3)
# Signed Longitude, Signed Latitude, Altitude [m].
# NOTE: Order is not quite what you would expect!
f.write('{longitude:12.10f},{latitude:12.10f},{altitude:12.10f}\n'.format(
latitude=wing_pos_llh_vec3.x,
longitude=wing_pos_llh_vec3.y,
altitude=wing_pos_llh_vec3.z))
def PrintCoordSegment(f, wing_pos_g, g_heading, gs_pos_llh_vec3, name=None,
description=None, style_url=None):
"""Write a segment of LLH coordinates to a <placemark> tag in a KML file.
Args:
f: file handle.
wing_pos_g: wing position in ground coordinates.
g_heading: ground frame heading w.r.t. true north.
gs_pos_llh_vec3: Vec3 object containing ground station LLH.
name (string, optional): Name of this segment.
description (string, optional): Description of this segment.
style_url (string, optional): Name of style to apply.
"""
f.write('<Placemark>\n')
if name is not None:
f.write('<name>' + name + '</name>\n')
if description is not None:
f.write('<description>' + description + '</description>\n')
if style_url is not None:
f.write('<styleUrl>' + style_url + '</styleUrl>\n')
f.write(textwrap.dedent("""\
<LineString>
<altitudeMode>absolute</altitudeMode>
<coordinates>
"""))
PrintCoordsLlh(f, wing_pos_g, g_heading, gs_pos_llh_vec3)
f.write(textwrap.dedent("""\
</coordinates>
</LineString>
</Placemark>
"""))
def main(argv):
def PrintUsage(argv, error=None):
if error:
print '\nError: %s\n' % error
print 'Usage: %s --output_file my_file.kml log.h5 [log2.h5 ...]\n%s' % (
argv[0], FLAGS)
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
PrintUsage(argv, e)
sys.exit(1)
if len(argv) <= 1:
PrintUsage(argv, 'Must specify at least one logfile.')
sys.exit(1)
log_filenames = argv[1:]
with open(FLAGS.output_file, 'w') as f:
PrintKmlHeader(f)
for log_filename in log_filenames:
if not FLAGS.quiet:
print 'Processing', log_filename
log = h5py.File(log_filename, 'r')
node_name = 'kAioNodeControllerA'
if 'kMessageTypeControlDebug' in log['messages'][node_name]:
message_name = 'kMessageTypeControlDebug'
elif 'kMessageTypeControlTelemetry' in log['messages'][node_name]:
message_name = 'kMessageTypeControlTelemetry'
else:
print 'Could not find control telemetry in {filename}'.format(
filename=log_filename)
sys.exit(1)
control_telemetry = log['messages'][node_name][message_name]['message']
g_heading = (
log['parameters']['system_params']['ground_frame']['heading'])
gs_pos_llh_vec3 = GetGsPosLlhVec3(control_telemetry)
# Find indicies at which the flight mode changes.
fm = control_telemetry['flight_mode']
fm_change_logical = fm[:-1] != fm[1:]
fm_change_logical[-1] = True
fm_change_indicies = np.where(fm_change_logical)[0]
# Process each segment between flight mode changes.
i_prev = 0
for i in fm_change_indicies:
fm = control_telemetry['flight_mode'][i-1]
fm_name = _FLIGHT_MODE_HELPER.ShortName(int(fm))
PrintCoordSegment(f, control_telemetry['state_est']['Xg'][i_prev:i],
g_heading, gs_pos_llh_vec3,
name=fm_name,
style_url='#' + fm_name)
i_prev = i
PrintKmlFooter(f)
if __name__ == '__main__':
main(sys.argv)
|
{"hexsha": "87eeeefc15220e8943b53c0d3d3db646da08f48a", "size": 8037, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/flight_data/h5_to_google_earth.py", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "analysis/flight_data/h5_to_google_earth.py", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "analysis/flight_data/h5_to_google_earth.py", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 34.3461538462, "max_line_length": 79, "alphanum_fraction": 0.6614408361, "include": true, "reason": "import numpy", "num_tokens": 2124}
|
import torch
import torch.nn as nn
from timm.models.layers import DropPath, trunc_normal_
from .dgcnn_group import DGCNN_Grouper
import numpy as np
from knn_cuda import KNN
knn = KNN(k=8, transpose_mode=False)
def get_knn_index(coor_q, coor_k=None):
coor_k = coor_k if coor_k is not None else coor_q
# coor: bs, 3, np
batch_size, _, num_points = coor_q.size()
num_points_k = coor_k.size(2)
with torch.no_grad():
_, idx = knn(coor_k, coor_q) # bs k np
idx_base = torch.arange(
0, batch_size, device=coor_q.device).view(-1, 1, 1) * num_points_k
idx = idx + idx_base
idx = idx.view(-1)
return idx # bs*k*np
def get_graph_feature(x, knn_index, x_q=None):
# x: bs, np, c, knn_index: bs*k*np
k = 8
batch_size, num_points, num_dims = x.size()
num_query = x_q.size(1) if x_q is not None else num_points
feature = x.view(batch_size * num_points, num_dims)[knn_index, :]
feature = feature.view(batch_size, k, num_query, num_dims)
x = x_q if x_q is not None else x
x = x.view(batch_size, 1, num_query, num_dims).expand(-1, k, -1, -1)
feature = torch.cat((feature - x, x), dim=-1)
return feature # b k np c
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C //
self.num_heads).permute(2, 0, 3, 1, 4)
# make torchscript happy (cannot use tensor as tuple)
q, k, v = qkv[0], qkv[1], qkv[2]
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class CrossAttention(nn.Module):
def __init__(self, dim, out_dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
self.dim = dim
self.out_dim = out_dim
head_dim = out_dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.q_map = nn.Linear(dim, out_dim, bias=qkv_bias)
self.k_map = nn.Linear(dim, out_dim, bias=qkv_bias)
self.v_map = nn.Linear(dim, out_dim, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(out_dim, out_dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, q, v):
B, N, _ = q.shape
C = self.out_dim
k = v
NK = k.size(1)
q = self.q_map(q).view(B, N, self.num_heads, C //
self.num_heads).permute(0, 2, 1, 3)
k = self.k_map(k).view(B, NK, self.num_heads, C //
self.num_heads).permute(0, 2, 1, 3)
v = self.v_map(v).view(B, NK, self.num_heads, C //
self.num_heads).permute(0, 2, 1, 3)
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class DecoderBlock(nn.Module):
def __init__(self, dim, num_heads, dim_q=None, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.self_attn = Attention(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
dim_q = dim_q or dim
self.norm_q = norm_layer(dim_q)
self.norm_v = norm_layer(dim)
self.attn = CrossAttention(
dim, dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(
drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
act_layer=act_layer, drop=drop)
self.knn_map = nn.Sequential(
nn.Linear(dim * 2, dim),
nn.LeakyReLU(negative_slope=0.2)
)
self.merge_map = nn.Linear(dim*2, dim)
self.knn_map_cross = nn.Sequential(
nn.Linear(dim * 2, dim),
nn.LeakyReLU(negative_slope=0.2)
)
self.merge_map_cross = nn.Linear(dim*2, dim)
def forward(self, q, v, self_knn_index=None, cross_knn_index=None):
# q = q + self.drop_path(self.self_attn(self.norm1(q)))
norm_q = self.norm1(q)
q_1 = self.self_attn(norm_q)
if self_knn_index is not None:
knn_f = get_graph_feature(norm_q, self_knn_index)
knn_f = self.knn_map(knn_f)
knn_f = knn_f.max(dim=1, keepdim=False)[0]
q_1 = torch.cat([q_1, knn_f], dim=-1)
q_1 = self.merge_map(q_1)
q = q + self.drop_path(q_1)
norm_q = self.norm_q(q)
norm_v = self.norm_v(v)
q_2 = self.attn(norm_q, norm_v)
if cross_knn_index is not None:
knn_f = get_graph_feature(norm_v, cross_knn_index, norm_q)
knn_f = self.knn_map_cross(knn_f)
knn_f = knn_f.max(dim=1, keepdim=False)[0]
q_2 = torch.cat([q_2, knn_f], dim=-1)
q_2 = self.merge_map_cross(q_2)
q = q + self.drop_path(q_2)
# q = q + self.drop_path(self.attn(self.norm_q(q), self.norm_v(v)))
q = q + self.drop_path(self.mlp(self.norm2(q)))
return q
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(
drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.knn_map = nn.Sequential(
nn.Linear(dim * 2, dim),
nn.LeakyReLU(negative_slope=0.2)
)
self.merge_map = nn.Linear(dim*2, dim)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
act_layer=act_layer, drop=drop)
def forward(self, x, knn_index=None):
# x = x + self.drop_path(self.attn(self.norm1(x)))
norm_x = self.norm1(x)
x_1 = self.attn(norm_x)
if knn_index is not None:
knn_f = get_graph_feature(norm_x, knn_index)
knn_f = self.knn_map(knn_f)
knn_f = knn_f.max(dim=1, keepdim=False)[0]
x_1 = torch.cat([x_1, knn_f], dim=-1)
x_1 = self.merge_map(x_1)
x = x + self.drop_path(x_1)
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class PCTransformer(nn.Module):
""" Vision Transformer with support for point cloud completion
"""
def __init__(self, in_chans=3, embed_dim=768, depth=[6, 6], num_heads=6, mlp_ratio=2., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
num_query=224, knn_layer=-1):
super().__init__()
self.num_features = self.embed_dim = embed_dim
self.knn_layer = knn_layer
# print_log(' Transformer with knn_layer %d' % self.knn_layer, logger='MODEL')
self.grouper = DGCNN_Grouper() # B 3 N to B C(3) N(128) and B C(128) N(128)
self.pos_embed = nn.Sequential(
nn.Conv1d(in_chans, 128, 1),
nn.BatchNorm1d(128),
nn.LeakyReLU(negative_slope=0.2),
nn.Conv1d(128, embed_dim, 1)
)
# self.pos_embed_wave = nn.Sequential(
# nn.Conv1d(60, 128, 1),
# nn.BatchNorm1d(128),
# nn.LeakyReLU(negative_slope=0.2),
# nn.Conv1d(128, embed_dim, 1)
# )
# self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
# self.cls_pos = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.input_proj = nn.Sequential(
nn.Conv1d(128, embed_dim, 1),
nn.BatchNorm1d(embed_dim),
nn.LeakyReLU(negative_slope=0.2),
nn.Conv1d(embed_dim, embed_dim, 1)
)
self.encoder = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate)
for i in range(depth[0])])
# self.increase_dim = nn.Sequential(
# nn.Linear(embed_dim,1024),
# nn.ReLU(inplace=True),
# nn.Linear(1024, 1024)
# )
self.increase_dim = nn.Sequential(
nn.Conv1d(embed_dim, 1024, 1),
nn.BatchNorm1d(1024),
nn.LeakyReLU(negative_slope=0.2),
nn.Conv1d(1024, 1024, 1)
)
self.num_query = num_query
self.coarse_pred = nn.Sequential(
nn.Linear(1024, 1024),
nn.ReLU(inplace=True),
nn.Linear(1024, 3 * num_query)
)
self.mlp_query = nn.Sequential(
nn.Conv1d(1024 + 3, 1024, 1),
# nn.BatchNorm1d(1024),
nn.LeakyReLU(negative_slope=0.2),
nn.Conv1d(1024, 1024, 1),
# nn.BatchNorm1d(1024),
nn.LeakyReLU(negative_slope=0.2),
nn.Conv1d(1024, embed_dim, 1)
)
self.decoder = nn.ModuleList([
DecoderBlock(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate)
for i in range(depth[1])])
# trunc_normal_(self.cls_token, std=.02)
# trunc_normal_(self.cls_pos, std=.02)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
elif isinstance(m, nn.Conv1d):
nn.init.xavier_normal_(m.weight.data, gain=1)
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight.data, 1)
nn.init.constant_(m.bias.data, 0)
def pos_encoding_sin_wave(self, coor):
# ref to https://arxiv.org/pdf/2003.08934v2.pdf
D = 64
# normal the coor into [-1, 1], batch wise
normal_coor = 2 * ((coor - coor.min()) / (coor.max() - coor.min())) - 1
# define sin wave freq
freqs = torch.arange(D, dtype=torch.float).cuda()
freqs = np.pi * (2**freqs)
freqs = freqs.view(*[1]*len(normal_coor.shape), -1) # 1 x 1 x 1 x D
normal_coor = normal_coor.unsqueeze(-1) # B x 3 x N x 1
k = normal_coor * freqs # B x 3 x N x D
s = torch.sin(k) # B x 3 x N x D
c = torch.cos(k) # B x 3 x N x D
x = torch.cat([s, c], -1) # B x 3 x N x 2D
# B 6D N
pos = x.transpose(-1, -2).reshape(coor.shape[0], -1, coor.shape[-1])
# zero_pad = torch.zeros(x.size(0), 2, x.size(-1)).cuda()
# pos = torch.cat([x, zero_pad], dim = 1)
# pos = self.pos_embed_wave(x)
return pos
def forward(self, inpc):
'''
inpc : input incomplete point cloud with shape B N(2048) C(3)
'''
# build point proxy
bs = inpc.size(0)
coor, f = self.grouper(inpc.transpose(1, 2).contiguous())
# add
# vis_point(coor[0].cpu().detach(), "coor")
knn_index = get_knn_index(coor)
# NOTE: try to use a sin wave coor B 3 N, change the pos_embed input dim
# pos = self.pos_encoding_sin_wave(coor).transpose(1,2)
pos = self.pos_embed(coor).transpose(1, 2)
# pos = None
x = self.input_proj(f).transpose(1, 2)
# cls_pos = self.cls_pos.expand(bs, -1, -1)
# cls_token = self.cls_pos.expand(bs, -1, -1)
# x = torch.cat([cls_token, x], dim=1)
# pos = torch.cat([cls_pos, pos], dim=1)
# encoder
for i, blk in enumerate(self.encoder):
if i < self.knn_layer:
# x = blk(x, knn_index)
x = blk(x + pos, knn_index) # B N C
else:
# x = blk(x)
x = blk(x + pos)
# build the query feature for decoder
# global_feature = x[:, 0] # B C
global_feature = self.increase_dim(x.transpose(1, 2)) # B 1024 N
global_feature = torch.max(global_feature, dim=-1)[0] # B 1024
coarse_point_cloud = self.coarse_pred(
global_feature).reshape(bs, -1, 3) # B M C(3)
new_knn_index = get_knn_index(
coarse_point_cloud.transpose(1, 2).contiguous())
cross_knn_index = get_knn_index(
coor_k=coor, coor_q=coarse_point_cloud.transpose(1, 2).contiguous())
query_feature = torch.cat([
global_feature.unsqueeze(1).expand(-1, self.num_query, -1),
coarse_point_cloud], dim=-1) # B M C+3
q = self.mlp_query(query_feature.transpose(
1, 2)).transpose(1, 2).contiguous() # B M C
# decoder
for i, blk in enumerate(self.decoder):
if i < self.knn_layer:
q = blk(q, x, new_knn_index, cross_knn_index) # B M C
else:
q = blk(q, x)
return q, coarse_point_cloud
|
{"hexsha": "55e8aaade17ab386bc9fac7914015780168c6e96", "size": 15397, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/PoinTr/models/Transformer.py", "max_stars_repo_name": "Sakura176/PointRCNN", "max_stars_repo_head_hexsha": "a7fbb25e931609a39c32cb821a7c98a326e8b0c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/PoinTr/models/Transformer.py", "max_issues_repo_name": "Sakura176/PointRCNN", "max_issues_repo_head_hexsha": "a7fbb25e931609a39c32cb821a7c98a326e8b0c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/PoinTr/models/Transformer.py", "max_forks_repo_name": "Sakura176/PointRCNN", "max_forks_repo_head_hexsha": "a7fbb25e931609a39c32cb821a7c98a326e8b0c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.190821256, "max_line_length": 154, "alphanum_fraction": 0.5774501526, "include": true, "reason": "import numpy", "num_tokens": 4427}
|
#%%
import pandas as pd
import numpy as np
import re
import yaml
from azure.storage.blob import BlobClient
acceptable_image_types = ["png", "jpg"]
params = yaml.safe_load(open("../blob_keys.yaml"))
def get_blob(name):
blob = BlobClient.from_connection_string(
conn_str=params["conn_str"],
container_name=params["container_name"],
blob_name=name,
)
return blob
def clean_string(s):
s2 = str(s.replace('\\','+'))
s2 = re.sub(r'\W+', '', s2)
return s2
def clean_tags(pic):
acceptable_keys = [k for k in list(pic.keys()) if k not in ["Unnamed: 0","fullpath","isdir","size"]]
clean_pic = {k: clean_string(pic[k]) for k in acceptable_keys}
return clean_pic
df = pd.read_csv("../data/files.csv")
df = df[df["extension"].isin(acceptable_image_types)].dropna()
pictures = df.to_dict(orient="records")
print(f'uploading {len(pictures)} documents to {params["container_name"]}')
unable_to_upload = []
for i, pic in enumerate(pictures):
if i % 100 == 0:
print(np.round((i / len(pictures) * 100), decimals=4), "% completed")
get_blob(clean_string(pic.get("item"))).upload_blob(
open(pic.get("fullpath"), "rb"),
tags=clean_tags(pic),
overwrite=params["overwrite_blob"],
)
pd.DataFrame(unable_to_upload).to_csv("../data/unable_to_upload.csv")
|
{"hexsha": "6addd2a24e7650dba717e0c824ba52eb2b95a9ef", "size": 1343, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/upload_pictures.py", "max_stars_repo_name": "BillmanH/opensocial", "max_stars_repo_head_hexsha": "f6a2d7f6792607a33eebd3a09b3f20e846e32fa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-17T15:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T15:53:18.000Z", "max_issues_repo_path": "scripts/upload_pictures.py", "max_issues_repo_name": "BillmanH/opensocial", "max_issues_repo_head_hexsha": "f6a2d7f6792607a33eebd3a09b3f20e846e32fa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/upload_pictures.py", "max_forks_repo_name": "BillmanH/opensocial", "max_forks_repo_head_hexsha": "f6a2d7f6792607a33eebd3a09b3f20e846e32fa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4081632653, "max_line_length": 104, "alphanum_fraction": 0.6597170514, "include": true, "reason": "import numpy", "num_tokens": 342}
|
[STATEMENT]
lemma Lindelof_space_perfect_map_image:
"\<lbrakk>Lindelof_space X; perfect_map X Y f\<rbrakk> \<Longrightarrow> Lindelof_space Y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>Lindelof_space X; perfect_map X Y f\<rbrakk> \<Longrightarrow> Lindelof_space Y
[PROOF STEP]
using Lindelof_space_quotient_map_image perfect_imp_quotient_map
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>quotient_map ?X ?Y ?q; Lindelof_space ?X\<rbrakk> \<Longrightarrow> Lindelof_space ?Y
perfect_map ?X ?Y ?f \<Longrightarrow> quotient_map ?X ?Y ?f
goal (1 subgoal):
1. \<lbrakk>Lindelof_space X; perfect_map X Y f\<rbrakk> \<Longrightarrow> Lindelof_space Y
[PROOF STEP]
by blast
|
{"llama_tokens": 279, "file": null, "length": 2}
|
-makelib ies_lib/xil_defaultlib -sv \
"/data/opt/Xilinx/Vivado/2017.4/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv" \
"/data/opt/Xilinx/Vivado/2017.4/data/ip/xpm/xpm_fifo/hdl/xpm_fifo.sv" \
"/data/opt/Xilinx/Vivado/2017.4/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv" \
-endlib
-makelib ies_lib/xpm \
"/data/opt/Xilinx/Vivado/2017.4/data/ip/xpm/xpm_VCOMP.vhd" \
-endlib
-makelib ies_lib/xlconcat_v2_1_1 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/2f66/hdl/xlconcat_v2_1_vl_rfs.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_irqConcat_0/sim/flute_irqConcat_0.v" \
-endlib
-makelib ies_lib/lib_cdc_v1_0_2 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ef1e/hdl/lib_cdc_v1_0_rfs.vhd" \
-endlib
-makelib ies_lib/proc_sys_reset_v5_0_12 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/f86a/hdl/proc_sys_reset_v5_0_vh_rfs.vhd" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_porReset_0/sim/flute_porReset_0.vhd" \
-endlib
-makelib ies_lib/axi_infrastructure_v1_1_0 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec67/hdl/axi_infrastructure_v1_1_vl_rfs.v" \
-endlib
-makelib ies_lib/smartconnect_v1_0 -sv \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/02c8/hdl/sc_util_v1_0_vl_rfs.sv" \
-endlib
-makelib ies_lib/axi_protocol_checker_v2_0_1 -sv \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/3b24/hdl/axi_protocol_checker_v2_0_vl_rfs.sv" \
-endlib
-makelib ies_lib/axi_vip_v1_1_1 -sv \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/a16a/hdl/axi_vip_v1_1_vl_rfs.sv" \
-endlib
-makelib ies_lib/processing_system7_vip_v1_0_3 -sv \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/1313/hdl/processing_system7_vip_v1_0_vl_rfs.sv" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_processing_system7_0_0/sim/flute_processing_system7_0_0.v" \
-endlib
-makelib ies_lib/axi_lite_ipif_v3_0_4 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/cced/hdl/axi_lite_ipif_v3_0_vh_rfs.vhd" \
-endlib
-makelib ies_lib/axi_intc_v4_1_10 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/cf04/hdl/axi_intc_v4_1_vh_rfs.vhd" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_psInterruptController_0/sim/flute_psInterruptController_0.vhd" \
-endlib
-makelib ies_lib/xlslice_v1_0_1 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/f3db/hdl/xlslice_v1_0_vl_rfs.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_resetSlice_0/sim/flute_resetSlice_0.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/flute_subprocessorClk_0_mmcm_pll_drp.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/proc_common_v3_00_a/hdl/src/vhdl/flute_subprocessorClk_0_conv_funs_pkg.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/proc_common_v3_00_a/hdl/src/vhdl/flute_subprocessorClk_0_proc_common_pkg.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/proc_common_v3_00_a/hdl/src/vhdl/flute_subprocessorClk_0_ipif_pkg.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/proc_common_v3_00_a/hdl/src/vhdl/flute_subprocessorClk_0_family_support.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/proc_common_v3_00_a/hdl/src/vhdl/flute_subprocessorClk_0_family.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/proc_common_v3_00_a/hdl/src/vhdl/flute_subprocessorClk_0_soft_reset.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/proc_common_v3_00_a/hdl/src/vhdl/flute_subprocessorClk_0_pselect_f.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/axi_lite_ipif_v1_01_a/hdl/src/vhdl/flute_subprocessorClk_0_address_decoder.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/axi_lite_ipif_v1_01_a/hdl/src/vhdl/flute_subprocessorClk_0_slave_attachment.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/axi_lite_ipif_v1_01_a/hdl/src/vhdl/flute_subprocessorClk_0_axi_lite_ipif.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/flute_subprocessorClk_0_clk_wiz_drp.vhd" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/flute_subprocessorClk_0_axi_clk_config.vhd" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/flute_subprocessorClk_0_clk_wiz.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_subprocessorClk_0/flute_subprocessorClk_0.v" \
-endlib
-makelib ies_lib/generic_baseblocks_v2_1_0 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/b752/hdl/generic_baseblocks_v2_1_vl_rfs.v" \
-endlib
-makelib ies_lib/axi_register_slice_v2_1_15 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/3ed1/hdl/axi_register_slice_v2_1_vl_rfs.v" \
-endlib
-makelib ies_lib/fifo_generator_v13_2_1 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/5c35/simulation/fifo_generator_vlog_beh.v" \
-endlib
-makelib ies_lib/fifo_generator_v13_2_1 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/5c35/hdl/fifo_generator_v13_2_rfs.vhd" \
-endlib
-makelib ies_lib/fifo_generator_v13_2_1 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/5c35/hdl/fifo_generator_v13_2_rfs.v" \
-endlib
-makelib ies_lib/axi_data_fifo_v2_1_14 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/9909/hdl/axi_data_fifo_v2_1_vl_rfs.v" \
-endlib
-makelib ies_lib/axi_crossbar_v2_1_16 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/c631/hdl/axi_crossbar_v2_1_vl_rfs.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_xbar_1/sim/flute_xbar_1.v" \
-endlib
-makelib ies_lib/blk_mem_gen_v8_3_6 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/2751/simulation/blk_mem_gen_v8_3.v" \
-endlib
-makelib ies_lib/axi_bram_ctrl_v4_0_13 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/20fd/hdl/axi_bram_ctrl_v4_0_rfs.vhd" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_procBramController_0/sim/flute_procBramController_0.vhd" \
-endlib
-makelib ies_lib/axi_protocol_converter_v2_1_15 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ff69/hdl/axi_protocol_converter_v2_1_vl_rfs.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_procProtocolConv_0/sim/flute_procProtocolConv_0.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_procXbar_0/sim/flute_procXbar_0.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_psBramController_0/sim/flute_psBramController_0.vhd" \
-endlib
-makelib ies_lib/axi_clock_converter_v2_1_14 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/445f/hdl/axi_clock_converter_v2_1_vl_rfs.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_psClockConv_0/sim/flute_psClockConv_0.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_psCrossbar_0/sim/flute_psCrossbar_0.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_psProtocolConv_0/sim/flute_psProtocolConv_0.v" \
-endlib
-makelib ies_lib/blk_mem_gen_v8_4_1 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/67d8/simulation/blk_mem_gen_v8_4.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_riscvBram_0/sim/flute_riscvBram_0.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_riscvReset_0/sim/flute_riscvReset_0.vhd" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_xbar_0/sim/flute_xbar_0.v" \
"../../../../flute.srcs/sources_1/bd/flute/sim/flute.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/BRAM2.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/FIFO2.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/FIFO20.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/RegFile.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkBranch_Predictor.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkCPU.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkCSR_MIE.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkCSR_MIP.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkCSR_RegFile.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkGPR_RegFile.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkMMU_Cache.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkNear_Mem.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkNear_Mem_IO.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkRISCV_MBox.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkSoC_Map.v" \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/ec93/src/mkCore.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_flute3_0_0/sim/flute_flute3_0_0.v" \
-endlib
-makelib ies_lib/axi_dwidth_converter_v2_1_15 \
"../../../../flute.srcs/sources_1/bd/flute/ipshared/1cdc/hdl/axi_dwidth_converter_v2_1_vl_rfs.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_auto_ds_1/sim/flute_auto_ds_1.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_auto_pc_1/sim/flute_auto_pc_1.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_auto_pc_2/sim/flute_auto_pc_2.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_auto_us_0/sim/flute_auto_us_0.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_auto_cc_0/sim/flute_auto_cc_0.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_auto_ds_0/sim/flute_auto_ds_0.v" \
"../../../../flute.srcs/sources_1/bd/flute/ip/flute_auto_pc_0/sim/flute_auto_pc_0.v" \
-endlib
-makelib ies_lib/xil_defaultlib \
glbl.v
-endlib
|
{"hexsha": "f3b71a72a87f835d9bbb1433532d28c0dab3d41d", "size": 10240, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "riscvonpynq/flute/tcm/flute/flute.ip_user_files/sim_scripts/flute/ies/run.f", "max_stars_repo_name": "indirajhenny/RISC-V-On-PYNQ", "max_stars_repo_head_hexsha": "d27bbd6fb037b63034956b4065e55c8e515395f7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "riscvonpynq/flute/tcm/flute/flute.ip_user_files/sim_scripts/flute/ies/run.f", "max_issues_repo_name": "indirajhenny/RISC-V-On-PYNQ", "max_issues_repo_head_hexsha": "d27bbd6fb037b63034956b4065e55c8e515395f7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "riscvonpynq/flute/tcm/flute/flute.ip_user_files/sim_scripts/flute/ies/run.f", "max_forks_repo_name": "indirajhenny/RISC-V-On-PYNQ", "max_forks_repo_head_hexsha": "d27bbd6fb037b63034956b4065e55c8e515395f7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.1907514451, "max_line_length": 154, "alphanum_fraction": 0.736328125, "num_tokens": 3639}
|
from __future__ import print_function
import numpy as np
from discretize import utils
from .base import BaseRectangularMesh, BaseTensorMesh
from .View import TensorView
from .DiffOperators import DiffOperators
from .InnerProducts import InnerProducts
from .MeshIO import TensorMeshIO
class TensorMesh(
BaseTensorMesh, BaseRectangularMesh, TensorView, DiffOperators,
InnerProducts, TensorMeshIO
):
"""
TensorMesh is a mesh class that deals with tensor product meshes.
Any Mesh that has a constant width along the entire axis
such that it can defined by a single width vector, called 'h'.
.. plot::
:include-source:
import discretize
hx = np.array([1, 1, 1])
hy = np.array([1, 2])
hz = np.array([1, 1, 1, 1])
mesh = discretize.TensorMesh([hx, hy, hz])
mesh.plotGrid()
Example of a padded tensor mesh using
:func:`discretize.utils.meshTensor`:
.. plot::
:include-source:
import discretize
mesh = discretize.TensorMesh([
[(10, 10, -1.3), (10, 40), (10, 10, 1.3)],
[(10, 10, -1.3), (10, 20)]
])
mesh.plotGrid()
For a quick tensor mesh on a (10x12x15) unit cube
.. code:: python
import discretize
mesh = discretize.TensorMesh([10, 12, 15])
"""
_meshType = 'TENSOR'
def __init__(self, h=None, x0=None, **kwargs):
BaseTensorMesh.__init__(self, h=h, x0=x0, **kwargs)
def __repr__(self):
"""Plain text representation."""
fmt = "\n {}: {:,} cells\n\n".format(type(self).__name__, self.nC)
fmt += 22*" "+"MESH EXTENT"+13*" "+"CELL WIDTH FACTOR\n"
fmt += " dir nC min max min max "
fmt += " max\n --- --- "+27*"-"+" "+18*"-"+" ------\n"
# Get attributes and put into table.
attrs = self._repr_attributes()
for i in range(self.dim):
name = attrs['names'][i]
iattr = attrs[name]
fmt += " {}".format(name)
fmt += " {:6}".format(iattr['nC'])
for p in ['min', 'max']:
fmt += " {:13,.2f}".format(iattr[p])
for p in ['h_min', 'h_max']:
fmt += " {:9,.2f}".format(iattr[p])
fmt += "{:8,.2f}".format(iattr['max_fact'])
fmt += "\n" # End row
fmt += "\n"
return fmt
def _repr_html_(self):
"""HTML representation."""
style = " style='padding: 5px 20px 5px 20px;'"
fmt = "<table>\n"
fmt += " <tr>\n"
fmt += " <td style='font-weight: bold; font-size: 1.2em; text-align"
fmt += ": center;' colspan='3'>{}</td>\n".format(type(self).__name__)
fmt += " <td style='font-size: 1.2em; text-align: center;'"
fmt += "colspan='4'>{:,} cells</td>\n".format(self.nC)
fmt += " </tr>\n"
fmt += " <tr>\n"
fmt += " <th></th>\n"
fmt += " <th></th>\n"
fmt += " <th colspan='2'"+style+">MESH EXTENT</th>\n"
fmt += " <th colspan='2'"+style+">CELL WIDTH</th>\n"
fmt += " <th"+style+">FACTOR</th>\n"
fmt += " </tr>\n"
fmt += " <tr>\n"
fmt += " <th"+style+">dir</th>\n"
fmt += " <th"+style+">nC</th>\n"
fmt += " <th"+style+">min</th>\n"
fmt += " <th"+style+">max</th>\n"
fmt += " <th"+style+">min</th>\n"
fmt += " <th"+style+">max</th>\n"
fmt += " <th"+style+">max</th>\n"
fmt += " </tr>\n"
# Get attributes and put into table.
attrs = self._repr_attributes()
for i in range(self.dim):
name = attrs['names'][i]
iattr = attrs[name]
fmt += " <tr>\n" # Start row
fmt += " <td"+style+">{}</td>\n".format(name)
fmt += " <td"+style+">{}</td>\n".format(iattr['nC'])
for p in ['min', 'max', 'h_min', 'h_max', 'max_fact']:
fmt += " <td"+style+">{:,.2f}</td>\n".format(iattr[p])
fmt += " </tr>\n" # End row
fmt += "</table>\n"
return fmt
# --------------- Geometries ---------------------
@property
def vol(self):
"""Construct cell volumes of the 3D model as 1d array."""
if getattr(self, '_vol', None) is None:
vh = self.h
# Compute cell volumes
if self.dim == 1:
self._vol = utils.mkvc(vh[0])
elif self.dim == 2:
# Cell sizes in each direction
self._vol = utils.mkvc(np.outer(vh[0], vh[1]))
elif self.dim == 3:
# Cell sizes in each direction
self._vol = utils.mkvc(
np.outer(utils.mkvc(np.outer(vh[0], vh[1])), vh[2])
)
return self._vol
@property
def areaFx(self):
"""
Area of the x-faces
"""
if getattr(self, '_areaFx', None) is None:
# Ensure that we are working with column vectors
vh = self.h
# The number of cell centers in each direction
n = self.vnC
# Compute areas of cell faces
if self.dim == 1:
areaFx = np.ones(n[0]+1)
elif self.dim == 2:
areaFx = np.outer(np.ones(n[0]+1), vh[1])
elif self.dim == 3:
areaFx = np.outer(
np.ones(n[0]+1), utils.mkvc(np.outer(vh[1], vh[2]))
)
self._areaFx = utils.mkvc(areaFx)
return self._areaFx
@property
def areaFy(self):
"""
Area of the y-faces
"""
if getattr(self, '_areaFy', None) is None:
# Ensure that we are working with column vectors
vh = self.h
# The number of cell centers in each direction
n = self.vnC
# Compute areas of cell faces
if self.dim == 1:
raise Exception('1D meshes do not have y-Faces')
elif self.dim == 2:
areaFy = np.outer(vh[0], np.ones(n[1]+1))
elif self.dim == 3:
areaFy = np.outer(
vh[0], utils.mkvc(np.outer(np.ones(n[1]+1), vh[2]))
)
self._areaFy = utils.mkvc(areaFy)
return self._areaFy
@property
def areaFz(self):
"""
Area of the z-faces
"""
if getattr(self, '_areaFz', None) is None:
# Ensure that we are working with column vectors
vh = self.h
# The number of cell centers in each direction
n = self.vnC
# Compute areas of cell faces
if self.dim == 1 or self.dim == 2:
raise Exception(
'{}D meshes do not have z-Faces'.format(self.dim)
)
elif self.dim == 3:
areaFz = np.outer(
vh[0], utils.mkvc(np.outer(vh[1], np.ones(n[2]+1)))
)
self._areaFz = utils.mkvc(areaFz)
return self._areaFz
@property
def area(self):
"""Construct face areas of the 3D model as 1d array."""
if self.dim == 1:
return self.areaFx
elif self.dim == 2:
return np.r_[self.areaFx, self.areaFy]
elif self.dim == 3:
return np.r_[self.areaFx, self.areaFy, self.areaFz]
@property
def edgeEx(self):
"""x-edge lengths"""
if getattr(self, '_edgeEx', None) is None:
# Ensure that we are working with column vectors
vh = self.h
# The number of cell centers in each direction
n = self.vnC
# Compute edge lengths
if self.dim == 1:
edgeEx = vh[0]
elif self.dim == 2:
edgeEx = np.outer(vh[0], np.ones(n[1]+1))
elif self.dim == 3:
edgeEx = np.outer(
vh[0],
utils.mkvc(np.outer(np.ones(n[1]+1), np.ones(n[2]+1)))
)
self._edgeEx = utils.mkvc(edgeEx)
return self._edgeEx
@property
def edgeEy(self):
"""y-edge lengths"""
if getattr(self, '_edgeEy', None) is None:
# Ensure that we are working with column vectors
vh = self.h
# The number of cell centers in each direction
n = self.vnC
# Compute edge lengths
if self.dim == 1:
raise Exception('1D meshes do not have y-edges')
elif self.dim == 2:
edgeEy = np.outer(np.ones(n[0]+1), vh[1])
elif self.dim == 3:
edgeEy = np.outer(
np.ones(n[0]+1),
utils.mkvc(np.outer(vh[1], np.ones(n[2]+1)))
)
self._edgeEy = utils.mkvc(edgeEy)
return self._edgeEy
@property
def edgeEz(self):
"""z-edge lengths"""
if getattr(self, '_edgeEz', None) is None:
# Ensure that we are working with column vectors
vh = self.h
# The number of cell centers in each direction
n = self.vnC
# Compute edge lengths
if self.dim == 1 or self.dim == 2:
raise Exception(
'{}D meshes do not have y-edges'.format(self.dim)
)
elif self.dim == 3:
edgeEz = np.outer(
np.ones(n[0]+1),
utils.mkvc(np.outer(np.ones(n[1]+1), vh[2]))
)
self._edgeEz = utils.mkvc(edgeEz)
return self._edgeEz
@property
def edge(self):
"""Construct edge legnths of the 3D model as 1d array."""
if self.dim == 1:
return self.edgeEx
elif self.dim == 2:
return np.r_[self.edgeEx, self.edgeEy]
elif(self.dim == 3):
return np.r_[self.edgeEx, self.edgeEy, self.edgeEz]
return self._edge
@property
def faceBoundaryInd(self):
"""
Find indices of boundary faces in each direction
"""
if self.dim == 1:
indxd = (self.gridFx == min(self.gridFx))
indxu = (self.gridFx == max(self.gridFx))
return indxd, indxu
elif self.dim == 2:
indxd = (self.gridFx[:, 0] == min(self.gridFx[:, 0]))
indxu = (self.gridFx[:, 0] == max(self.gridFx[:, 0]))
indyd = (self.gridFy[:, 1] == min(self.gridFy[:, 1]))
indyu = (self.gridFy[:, 1] == max(self.gridFy[:, 1]))
return indxd, indxu, indyd, indyu
elif self.dim == 3:
indxd = (self.gridFx[:, 0] == min(self.gridFx[:, 0]))
indxu = (self.gridFx[:, 0] == max(self.gridFx[:, 0]))
indyd = (self.gridFy[:, 1] == min(self.gridFy[:, 1]))
indyu = (self.gridFy[:, 1] == max(self.gridFy[:, 1]))
indzd = (self.gridFz[:, 2] == min(self.gridFz[:, 2]))
indzu = (self.gridFz[:, 2] == max(self.gridFz[:, 2]))
return indxd, indxu, indyd, indyu, indzd, indzu
@property
def cellBoundaryInd(self):
"""
Find indices of boundary faces in each direction
"""
if self.dim == 1:
indxd = (self.gridCC == min(self.gridCC))
indxu = (self.gridCC == max(self.gridCC))
return indxd, indxu
elif self.dim == 2:
indxd = (self.gridCC[:, 0] == min(self.gridCC[:, 0]))
indxu = (self.gridCC[:, 0] == max(self.gridCC[:, 0]))
indyd = (self.gridCC[:, 1] == min(self.gridCC[:, 1]))
indyu = (self.gridCC[:, 1] == max(self.gridCC[:, 1]))
return indxd, indxu, indyd, indyu
elif self.dim == 3:
indxd = (self.gridCC[:, 0] == min(self.gridCC[:, 0]))
indxu = (self.gridCC[:, 0] == max(self.gridCC[:, 0]))
indyd = (self.gridCC[:, 1] == min(self.gridCC[:, 1]))
indyu = (self.gridCC[:, 1] == max(self.gridCC[:, 1]))
indzd = (self.gridCC[:, 2] == min(self.gridCC[:, 2]))
indzu = (self.gridCC[:, 2] == max(self.gridCC[:, 2]))
return indxd, indxu, indyd, indyu, indzd, indzu
def _repr_attributes(self):
"""Attributes for the representation of the mesh."""
attrs = {}
attrs['names'] = ['x', 'y', 'z'][:self.dim]
# Loop over dimensions.
for i in range(self.dim):
name = attrs['names'][i] # Name of this dimension
attrs[name] = {}
# Get min/max node.
n_vector = getattr(self, 'vectorN'+name)
attrs[name]['min'] = np.nanmin(n_vector)
attrs[name]['max'] = np.nanmax(n_vector)
# Get min/max cell width.
h_vector = getattr(self, 'h'+name)
attrs[name]['h_min'] = np.nanmin(h_vector)
attrs[name]['h_max'] = np.nanmax(h_vector)
# Get max stretching factor.
if len(h_vector) < 2:
attrs[name]['max_fact'] = 1.0
else:
attrs[name]['max_fact'] = np.nanmax(
np.r_[h_vector[:-1]/h_vector[1:],
h_vector[1:]/h_vector[:-1]]
)
# Add number of cells.
attrs[name]['nC'] = getattr(self, 'nC'+name)
return attrs
|
{"hexsha": "5407f1cde1052acaf3bebbb15ef60aa5d3b3bf79", "size": 13464, "ext": "py", "lang": "Python", "max_stars_repo_path": "discretize/TensorMesh.py", "max_stars_repo_name": "bluetyson/discretize", "max_stars_repo_head_hexsha": "a4ead91d6a1f84658ab20946da5fa86dc9ccc831", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "discretize/TensorMesh.py", "max_issues_repo_name": "bluetyson/discretize", "max_issues_repo_head_hexsha": "a4ead91d6a1f84658ab20946da5fa86dc9ccc831", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "discretize/TensorMesh.py", "max_forks_repo_name": "bluetyson/discretize", "max_forks_repo_head_hexsha": "a4ead91d6a1f84658ab20946da5fa86dc9ccc831", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1540469974, "max_line_length": 79, "alphanum_fraction": 0.4788324421, "include": true, "reason": "import numpy", "num_tokens": 3627}
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 2020
@name: Utility Objects
@author: Jack Kirby Cook
"""
import numpy as np
import warnings
from abc import ABC, abstractmethod
__version__ = "1.0.0"
__author__ = "Jack Kirby Cook"
__all__ = ["UtilityIndex", "UtilityFunction"]
__copyright__ = "Copyright 2020, Jack Kirby Cook"
__license__ = ""
_aslist = lambda x: [x] if not isinstance(x, (list, tuple)) else list(x)
_normalize = lambda x: np.array(x) / np.sum(np.array(x))
UTILITY_FUNCTIONS = {
"cobbdouglas": lambda x, w, a, d, *args: (np.prod(np.power(x, w)) ** d) * a,
"ces": lambda x, w, a, d, p, *args: (np.sum(np.multiply(np.power(x, p), w)) ** (d/p)) * a,
"linear": lambda x, w, a, *args: np.sum(np.multiply(x, w)) ** a,
"expcobbdouglas": lambda x, w, a, d, *args: (np.prod(np.power(np.exp(x), w)) ** d) * a}
UTILITY_DERIVATIVES = {
"cobbdouglas": lambda i, x, w, a, d, *args: a * w[i] * d * (1/x[i]) * (np.prod(np.power(x, w)) ** d),
"ces": lambda i, x, w, a, d, p, *args: a * w[i] * d * (x[i]**(p-1)) * (np.sum(np.multiply(x, w) ** p) ** ((d/p)-1)),
"linear": lambda i, x, w, a, d, *args: a * w[i],
"expcobbdouglas": lambda i, x, w, a, d, *args: a * w[i] * d * (np.prod(np.power(np.exp(x), w)) ** d)}
INDEX_FUNCTIONS = {
"additive": lambda x, w, t, a: np.sum(np.multiply(np.divide(w, t), x)) * a,
"inverted": lambda x, w, t, a: np.sum(np.divide(np.divide(w, t), x)) * a,
"tangent": lambda x, w, t, a: np.sum(np.multiply(np.divide(w, t), np.tan(x * np.pi/2))) * a,
"rtangent": lambda x, w, t, a: np.sum(np.multiply(np.divide(w, t), np.tan((1 - x) * np.pi/2))) * a,
"logarithm": lambda x, w, t, a: np.sum(np.multiply(np.divide(w, t), np.log(x + 1))) * a}
class NumericalError(Exception):
pass
class UtilityIndex(ABC):
def __init_subclass__(cls, *args, name, form, parameters=[], coefficients=[], **kwargs):
assert isinstance(name, str) and isinstance(type=str)
assert isinstance(type, (tuple, list)) and isinstance(coefficients, (tuple, list))
assert type in INDEX_FUNCTIONS.keys()
setattr(cls, "name", name)
setattr(cls, "form", form)
setattr(cls, "parameters", tuple(sorted(parameters)))
setattr(cls, "coefficients", tuple(coefficients))
@classmethod
@abstractmethod
def create(cls, *args, **kwargs): pass
@abstractmethod
def execute(self, *args, **kwargs): pass
@property
def key(self):
items = [(parameter, self.tolerances[parameter], self.weight[parameter]) for parameter in self.parameters]
return hash((self.name, self.form, self.amplitude, tuple(items),))
def __len__(self): return len(self.parameters)
def __init__(self, *args, amplitude=1, tolerances={}, weights={}, **kwargs):
assert isinstance(tolerances, dict) and isinstance(weights, dict)
assert all([hasattr(self, attr) for attr in ("name", "form", "function", "parameters")])
self.amplitude = amplitude
self.tolerances = {parameter: tolerances.get(parameter, 1) for parameter in self.parameters}
self.weights = {parameter: weights.get(parameter, 0) for parameter in self.parameters}
def __call__(self, *args, **kwargs):
v = self.execute(*args, **kwargs)
assert isinstance(v, dict)
assert all([parameter in v.keys() for parameter in self.parameters])
t = np.array([self.tolerances[parameter] for parameter in self.parameters])
w = np.array([self.weights[parameter] for parameter in self.parameters])
w = _normalize(w) if sum(w) > 0 else np.ones(w.shape) * (1/len(w))
x = np.array([v[parameter] for parameter in self.parameters])
return INDEX_FUNCTIONS[self.functiontype](x, w, t, self.amplitude)
class UtilityFunction(ABC):
def __init_subclass__(cls, name, form, *args, parameters=[], coefficients=[], **kwargs):
assert isinstance(name, str) and isinstance(form=str)
assert isinstance(parameters, (tuple, list)) and isinstance(coefficients, (tuple, list))
assert form in UTILITY_FUNCTIONS.keys()
setattr(cls, "name", name)
setattr(cls, "form", form)
setattr(cls, "parameter", tuple(sorted(parameters)))
setattr(cls, "coefficients", tuple(coefficients))
@classmethod
@abstractmethod
def create(self, *args, **kwargs): pass
def execute(self, *args, **kwargs): return {}
@property
def key(self):
types = (self.name, self.functiontype)
coefficients = [(key, value) for key, value in self.__coefficients.items()]
items = [(parm, self.__subsistences[parm], self.__weights[parm]) for parm in self.parameters]
functions = [(parm, self.__functions[parm].key if parm in self.__functions.keys() else None) for parm in self.parameters]
return hash((tuple(types), tuple(coefficients), tuple(items), tuple(functions)))
def __len__(self): return len(self.parameters)
def __init__(self, *args, subsistences={}, weights={}, functions={}, coefficients={}, **kwargs):
assert isinstance(subsistences, dict) and isinstance(weights, dict)
assert all([hasattr(self, attr) for attr in ("name", "form",)])
self.__subsistences = {parm: subsistences.get(parm, 0) for parm in self.parameters}
self.__weights = {parm: weights.get(parm, 0) for parm in self.parameters}
self.__functions = {parm: functions[parm] for parm in self.parameters if parm in functions}
self.__coefficients = {coefficient: coefficients[coefficient] for coefficient in self.coefficients}
def __call__(self, *args, **kwargs):
nested_kwargs = {parameter: function(*args, **kwargs) for parameter, function in self.__functions.items()}
x = self.execute(*args, **nested_kwargs, **kwargs)
x = np.array([x[parameter] for parameter in self.parameters])
c = [self.__coefficients[coefficient] for coefficient in self.coefficients]
s = np.array([self.__subsistences[parameter] for parameter in self.parameters])
w = np.array([self.__weights[parameter] for parameter in self.parameters])
w = _normalize(w) if sum(w) > 0 else np.ones(w.shape) * (1/len(w))
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
u = UTILITY_FUNCTIONS[self.form](np.subtract(x, s), w, *c)
except Warning:
raise NumericalError(np.subtract(x, s))
return u
def derivative(self, filtration, *args, **kwargs):
filtration = _aslist(filtration)
nested_kwargs = {parm: func(*args, **kwargs) for parm, func in self.__functions.items()}
i = self.parameters.index(filtration[0])
x = self.execute(*args, **nested_kwargs, **kwargs)
x = np.array([x[parameter] for parameter in self.parameters])
c = [self.__coefficients[coefficient] for coefficient in self.coefficients]
s = np.array([self.__subsistences[parameter] for parameter in self.parameters])
w = np.array([self.__weights[parameter] for parameter in self.parameters])
w = _normalize(w) if sum(w) > 0 else np.ones(w.shape) * (1/len(w))
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
du = UTILITY_DERIVATIVES[self.functiontype](i, np.subtract(x, s), w, *c)
except Warning:
raise NumericalError(np.subtract(x, s))
dx = self.__functions[filtration[0]].derivative(filtration[1:], *args, **kwargs) if len(filtration) > 1 else 1
return du * dx
|
{"hexsha": "9a0defe8419916e587d3fa4883306f3b5bfccd2e", "size": 7639, "ext": "py", "lang": "Python", "max_stars_repo_path": "utility.py", "max_stars_repo_name": "JackKirbyCook82/utilities", "max_stars_repo_head_hexsha": "ce9bac26785652fe90a4a89b6fbcb2a7d2c8078f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utility.py", "max_issues_repo_name": "JackKirbyCook82/utilities", "max_issues_repo_head_hexsha": "ce9bac26785652fe90a4a89b6fbcb2a7d2c8078f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utility.py", "max_forks_repo_name": "JackKirbyCook82/utilities", "max_forks_repo_head_hexsha": "ce9bac26785652fe90a4a89b6fbcb2a7d2c8078f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9679487179, "max_line_length": 129, "alphanum_fraction": 0.6326744338, "include": true, "reason": "import numpy", "num_tokens": 2026}
|
from styx_msgs.msg import TrafficLight
import numpy as np
import cv2
import tensorflow as tf
import rospy
import traceback
import json
import time
# Frozen inference graph files. NOTE: change the path to where you saved the models.
#------------------------------------------------------------------------------------
#SSD MOBILENET V1 on COCO ---> Good performance using CPU, not best results but enough for simulator
GRAPH_FILE = '/home/student/catkin_ws/CarND-Capstone/data/ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb'
#FASTER RCNN RESNET101 on COCO ---> VERY Poor performance on CPU, but QUITE GOOD resutls in classification, modify score to 0.75 or more
#GRAPH_FILE = '/home/student/catkin_ws/CarND-Capstone/data/faster_rcnn_resnet101_coco_11_06_2017/frozen_inference_graph.pb'
#SSD INCEPTION V2 on COCO ---> Poor performance sometimes, penalizes results, but QUITE GOOD classification.
#GRAPH_FILE = '/home/student/catkin_ws/CarND-Capstone/data/ssd_inception_v2_coco_2017_11_17/frozen_inference_graph.pb'
#-------------------------------------------------------------------------------------
DEBUG_MODE = 1 #debug mode activates the classifier to save processed images with boxes. Use 0 for production
BOXES_SCORE_MIN = 0.5 #minimum score to accept box detection
#Useful functions to load and record graph
with open('logfile.txt','wb') as f:
#creates logfile from scratch
f.write('new log file \n')
def log(arg):
#writes log information to debug file
with open('logfile.txt','a') as f:
f.write(arg+'\n')
def load_graph(graph_file):
"""Loads a frozen inference graph"""
graph = tf.Graph()
with graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(graph_file, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return graph
log('log file initialized')
log('tf version: {}'.format(tf.__version__))
detection_graph = load_graph(GRAPH_FILE)
#log('loaded graph with following nodes:')
#for op in tf.get_default_graph().get_operations():
# log('---{}'.format(op.name))
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
log ('using pretrained model: {}'.format(GRAPH_FILE))
sess = tf.Session(graph = detection_graph)
log('tf session open')
#Useful functions for classification
def equalize_image(image):
eq_image = np.copy(image)
for c in range(0,2):
eq_image[:,:,c] = cv2.equalizeHist(image[:,:,c])
cv2.imwrite('eq_sample.png',eq_image)
return eq_image
def gaussBlur_image(image):
gb_image = cv2.GaussianBlur(image, (5,5),0)
cv2.imwrite('gb_sample.png',gb_image)
return gb_image
def draw_boxes(img, bboxes, color=(0, 0, 255), thick=3):
#draws bounding boxes
# Make a copy of the image
imcopy = np.copy(img)
# Iterate through the bounding boxes
for bbox in bboxes:
# Draw a rectangle given bbox coordinates
cv2.rectangle(imcopy, (bbox[1], bbox[0]),(bbox[3], bbox[2]), color, thick)
# Return the image copy with boxes drawn
return imcopy
def TLDetection(image, sess):
image_np = np.expand_dims(np.asarray(image, dtype = np.uint8), 0)
boxes, scores, classes = sess.run([detection_boxes, detection_scores, detection_classes], feed_dict = {image_tensor: image_np})
boxes = np.squeeze(boxes)
scores = np.squeeze(scores)
classes = np.squeeze(classes)
return boxes, scores, classes
def TLBoxes(prob, boxes, scores, classes):
#filter boxes under minimum probability 'prob'
#COCO class index for TrafficLight is '10'
n = len(boxes)
idxs = []
for i in range(n):
if scores[i] >= prob and classes[i] == 10:
idxs.append(i)
filtered_boxes = boxes[idxs, ...]
filtered_scores = scores[idxs, ...]
filtered_classes = classes[idxs, ...]
return filtered_boxes, filtered_scores, filtered_classes
def TLResizeBoxes(boxes, image_height, image_width):
#Resize boxes from original values (0:1) to image size
box_coords = np.zeros_like(boxes)
box_coords[:,0] = boxes[:,0] * image_height
box_coords[:,1] = boxes[:,1] * image_width
box_coords[:,2] = boxes[:,2] * image_height
box_coords[:,3] = boxes[:,3] * image_width
return box_coords
def TLTrim(image, box_coordinates):
#return trimmed images containing all traffic light signals ahead: from
#zero (no traffic lights) to whatever
images = []
for box in box_coordinates:
x = int(np.round(box[1]))
y = int(np.round(box[0]))
w = int(np.round(box[3] - box[1]))
h = int(np.round(box[2] - box[0]))
images.append(image[ y:y+h , x:x+w ])
return images
def TLGetColor(image):
#check a trimmed image containing only one traffic light (red+yellow+green bulbs)
#and returns the color that is ON
states = [TrafficLight.GREEN, TrafficLight.YELLOW, TrafficLight.RED]
best_state = TrafficLight.UNKNOWN
for state in states:
_image = image.copy()
#let's pick some 6x6 pixels in the middle of each light bulb:
#
# x coord, we cut in the middle *0.5
# |
# -------
# | |
# | |- y coord, first third of light, we cut at 0.2
# |-----|
# | |_ y coord, second third of light, we cut at 0.55
# | |
# |-----|
# | |_ y coord, third part of light, we cut at 0.85
# | |
# -------
if state == TrafficLight.RED:
_image = _image[int(image.shape[0] * 0.2) - 3: int(image.shape[0] * 0.2) + 3,
int(image.shape[1] * 0.5) - 3: int(image.shape[1] * 0.5) + 3]
if state == TrafficLight.YELLOW:
_image = _image[int(image.shape[0] * 0.55) - 3: int(image.shape[0] * 0.55) + 3,
int(image.shape[1] * 0.5) - 3: int(image.shape[1] * 0.5) + 3]
if state == TrafficLight.GREEN:
_image = _image[int(image.shape[0] * 0.85) - 3: int(image.shape[0] * 0.85) + 3,
int(image.shape[1] * 0.5) - 3: int(image.shape[1] * 0.5) + 3]
# So we pick the bulb that is on...
if _image[np.where(np.squeeze(_image) > 250)].shape[0] > 15:
best_state = state
return best_state
class TLClassifier(object):
def __init__(self):
log('Classifier: initialized')
def get_classification(self, image):
"""Determines the color of the traffic light in the image
Args:
image (cv::Mat): image containing the traffic light
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
#TODO implement light color prediction
#preprocess camera image, Blur the image so it seems more realistic and the classificator performs better
#image = equalize_image(image)
gbeq_image = gaussBlur_image(image)
boxes, scores, classes = TLDetection(gbeq_image, sess)
log('CAMERA IMAGE PROCESSED, {} boxes detected'.format(len(boxes)))
boxes, scores, classes = TLBoxes(BOXES_SCORE_MIN, boxes, scores, classes)
image_height = image.shape[0]
image_width = image.shape[1]
box_coordinates = TLResizeBoxes(boxes, image_height, image_width)
trimmed_lights = TLTrim(image, box_coordinates)
#if debud mode is active, then saves processed images with boxes
if DEBUG_MODE == 1:
processed_image = draw_boxes(image, box_coordinates, color=(0, 0, 255), thick=3)
cv2.imwrite('img_processed/file_{}.png'.format(time.time()),processed_image)
#log('processed camera image saved {}'.format(time.time()))
lights = []
for light_bulbs in trimmed_lights:
color = TLGetColor(light_bulbs)
lights.append(color)
log('lights detected: {}'.format(lights))
for light_bulb in lights:
if light_bulb in [TrafficLight.RED]: # check if RED is detected in any light
return TrafficLight.RED
else:
return TrafficLight.UNKNOWN
|
{"hexsha": "0b9cb29272369da79ea0c2acab3aa068cc86293f", "size": 8523, "ext": "py", "lang": "Python", "max_stars_repo_path": "ros/src/tl_detector/light_classification/tl_classifier.py", "max_stars_repo_name": "frankynavar/ANewTeam_CarND_Integration", "max_stars_repo_head_hexsha": "54f2564ed92be882e3fe1a284210946abce64a9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ros/src/tl_detector/light_classification/tl_classifier.py", "max_issues_repo_name": "frankynavar/ANewTeam_CarND_Integration", "max_issues_repo_head_hexsha": "54f2564ed92be882e3fe1a284210946abce64a9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-04-17T15:25:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-27T08:15:05.000Z", "max_forks_repo_path": "ros/src/tl_detector/light_classification/tl_classifier.py", "max_forks_repo_name": "frankynavar/ANewTeam_CarND_Integration", "max_forks_repo_head_hexsha": "54f2564ed92be882e3fe1a284210946abce64a9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-04-17T14:58:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-03T17:51:57.000Z", "avg_line_length": 36.8961038961, "max_line_length": 136, "alphanum_fraction": 0.6329930776, "include": true, "reason": "import numpy", "num_tokens": 2147}
|
/*
* MIT License
*
* Copyright (c) 2020 Robert Grupp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "xregRayCastSurRenderOCL.h"
#include <boost/compute/utility/source.hpp>
#include <boost/compute/types/struct.hpp>
#include "xregAssert.h"
//////////////////////////////////////////////////////////////////////
BOOST_COMPUTE_ADAPT_STRUCT(xreg::RayCasterSurRenderOCL::RayCastSurRenderArgs, RayCastSurRenderArgs,
(thresh,
pad1,
num_backtracking_steps,
ambient_reflection_ratio,
diffuse_reflection_ratio,
specular_reflection_ratio,
alpha_shininess))
//////////////////////////////////////////////////////////////////////
namespace // un-named
{
const char* kRAY_CASTING_SUR_RENDER_OPENCL_SRC = BOOST_COMPUTE_STRINGIZE_SOURCE(
__kernel void xregSurRenderKernel1(const RayCastArgs args,
const RayCastSurRenderArgs sur_render_args,
__global const float4* det_pts,
image3d_t vol_tex,
__global const float16* cam_to_itk_phys_xforms,
__global float8* dst_step_vecs_and_intersect_pts_wrt_itk_idx,
__global const ulong* cam_model_for_proj,
__global const float4* cam_focal_pts)
{
const ulong idx = get_global_id(0);
const ulong num_rays = args.num_projs * args.num_det_pts;
if (idx < num_rays)
{
const ulong proj_idx = idx / args.num_det_pts;
const ulong det_pt_idx = idx - (proj_idx * args.num_det_pts);
const ulong cam_idx = cam_model_for_proj[proj_idx];
const float4 focal_pt_wrt_cam = cam_focal_pts[cam_idx];
const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_LINEAR;
const float4 tex_coords_off = (float4) (0.5f, 0.5f, 0.5f, 0);
const float16 xform_cam_to_itk_idx = xregFrm4x4Composition(args.itk_phys_pt_to_itk_idx_xform,
cam_to_itk_phys_xforms[proj_idx]);
const float4 pinhole_wrt_itk_idx = xregFrm4x4XformFloat4Pt(xform_cam_to_itk_idx, focal_pt_wrt_cam);
const float4 cur_det_pt_wrt_cam = det_pts[(cam_idx * args.num_det_pts) + det_pt_idx];
const float4 pinhole_to_det_wrt_itk_idx = xregFrm4x4XformFloat4Pt(xform_cam_to_itk_idx, cur_det_pt_wrt_cam)
- pinhole_wrt_itk_idx;
// check intersection with the image/volume boundary
// these pointer were passed as float4's since boost::compute does not have a float3
float2 t = xregRayRectIntersect(xregFloat4HmgToFloat3(args.img_aabb_min),
xregFloat4HmgToFloat3(args.img_aabb_max),
xregFloat4HmgToFloat3(pinhole_wrt_itk_idx),
xregFloat4HmgToFloat3(pinhole_to_det_wrt_itk_idx));
// t.x indicates the first intersection with the volume along the source to detector ray,
// t.y indicates the exit of the volume along the source to detector ray
// t.x, t.y are in [0,inf)
const float4 start_pt_wrt_itk_idx = pinhole_wrt_itk_idx + (t.x * pinhole_to_det_wrt_itk_idx);
const float pinhole_to_det_len_wrt_itk_idx = xregFloat4HmgNorm(pinhole_to_det_wrt_itk_idx);
const float intersect_len_wrt_itk_idx = (t.y - t.x) * pinhole_to_det_len_wrt_itk_idx;
const float4 focal_pt_to_det_wrt_cam = cur_det_pt_wrt_cam - focal_pt_wrt_cam;
// NOTE: since we are transforming a vector with a scaling transform (points to indices),
// the output vector may not have the same norm, thus we take the norm
const float step_len_wrt_itk_idx = xregFloat4HmgNorm(
xregFrm4x4XformFloat4Vec(xform_cam_to_itk_idx,
(focal_pt_to_det_wrt_cam / xregFloat4HmgNorm(focal_pt_to_det_wrt_cam)) * args.step_size));
const ulong num_steps = (ulong)(intersect_len_wrt_itk_idx / step_len_wrt_itk_idx);
float4 cur_cont_vol_idx = (float4) (start_pt_wrt_itk_idx.x, start_pt_wrt_itk_idx.y, start_pt_wrt_itk_idx.z, 0);
// "/ pinhole_to_det_len_wrt_itk_idx" makes pinhole_to_det_wrt_itk_idx a unit vector
const float scale_to_step = step_len_wrt_itk_idx / pinhole_to_det_len_wrt_itk_idx;
const float4 step_vec_wrt_itk_idx = (float4) (pinhole_to_det_wrt_itk_idx.x * scale_to_step, pinhole_to_det_wrt_itk_idx.y * scale_to_step, pinhole_to_det_wrt_itk_idx.z * scale_to_step, 0);
// The first three elements will store the step direction in ITK index space
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s0 = step_vec_wrt_itk_idx.x;
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s1 = step_vec_wrt_itk_idx.y;
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s2 = step_vec_wrt_itk_idx.z;
// The fourth element will indicate whether this ray intersected the surface.
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s3 = 0; // 0 -> no intersection found
for (ulong step_idx = 0; step_idx <= num_steps; ++step_idx, cur_cont_vol_idx += step_vec_wrt_itk_idx)
{
if (read_imagef(vol_tex, sampler, cur_cont_vol_idx + tex_coords_off).x >= sur_render_args.thresh)
{
// The 5th, 6th, and 7th elements will store the initial point of intersection, before any backtracking
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s4 = cur_cont_vol_idx.x;
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s5 = cur_cont_vol_idx.y;
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s6 = cur_cont_vol_idx.z;
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s7 = 0;
dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s3 = 1; // 1 -> intersection found
break;
}
}
}
}
__kernel void xregSurRenderKernel2(const RayCastArgs args,
const RayCastSurRenderArgs sur_render_args,
image3d_t vol_tex,
__global const float8* dst_step_vecs_and_intersect_pts_wrt_itk_idx,
__global float* dst_intensities)
{
const ulong idx = get_global_id(0);
const ulong num_rays = args.num_projs * args.num_det_pts;
if (idx < num_rays)
{
if (dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s3 > 1.0e-6)
{
const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_LINEAR;
const float4 tex_coords_off = (float4) (0.5f, 0.5f, 0.5f, 0);
float3 light_src_vec = (float3) (dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s0, dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s1, dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s2);
// right now, this light source vector points from the light source, it needs to be negated, and it is when normalizing a few lines below
// This vector will always point towards the pinhole.
float4 step_vec_wrt_itk_idx = (float4) (light_src_vec.x, light_src_vec.y, light_src_vec.z, 0);
step_vec_wrt_itk_idx *= 0.5f;
// normalize the direction vector to the light source, and negate to get the right orientation
light_src_vec /= -xregFloat3Norm(light_src_vec);
float4 cur_cont_vol_idx = (float4) (dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s4, dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s5, dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s6, 0);
cur_cont_vol_idx += tex_coords_off;
// we know that we should start out backtracking.
cur_cont_vol_idx -= step_vec_wrt_itk_idx;
for (ulong backtrack_idx = 0; backtrack_idx < sur_render_args.num_backtracking_steps; ++backtrack_idx)
{
step_vec_wrt_itk_idx *= 0.5f;
cur_cont_vol_idx += (read_imagef(vol_tex, sampler, cur_cont_vol_idx).x >= sur_render_args.thresh) ?
step_vec_wrt_itk_idx : -step_vec_wrt_itk_idx;
}
// compute lighting/shading according to the phong model
// approximate the derivative at this point with finite differencing adjacent indices
// NOTE: these are wrt image (index) axes.
float3 tmp_vec;
// Gradient in X Direction:
tmp_vec.x = read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x + 1, cur_cont_vol_idx.y, cur_cont_vol_idx.z, cur_cont_vol_idx.w)).x -
read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x - 1, cur_cont_vol_idx.y, cur_cont_vol_idx.z, cur_cont_vol_idx.w)).x;
// Gradient in Y Direction:
tmp_vec.y = read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x, cur_cont_vol_idx.y + 1, cur_cont_vol_idx.z, cur_cont_vol_idx.w)).x -
read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x, cur_cont_vol_idx.y - 1, cur_cont_vol_idx.z, cur_cont_vol_idx.w)).x;
// Gradient in Z Direction:
tmp_vec.z = read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x, cur_cont_vol_idx.y, cur_cont_vol_idx.z + 1, cur_cont_vol_idx.w)).x -
read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x, cur_cont_vol_idx.y, cur_cont_vol_idx.z - 1, cur_cont_vol_idx.w)).x;
tmp_vec /= (-0.5f * xregFloat3Norm(tmp_vec));
float val = sur_render_args.ambient_reflection_ratio;
// Treating the pinhole as the light source
float tmp_dot = xregFloat3Inner(light_src_vec, tmp_vec);
const int diffuse_valid = tmp_dot > 1.0e-6;
val += diffuse_valid ? (sur_render_args.diffuse_reflection_ratio * tmp_dot) : 0;
tmp_vec *= 2 * tmp_dot;
tmp_vec -= light_src_vec;
tmp_dot = xregFloat3Inner(light_src_vec, tmp_vec);
val += (tmp_dot > 1.0e-6) ?
(sur_render_args.specular_reflection_ratio * pow(tmp_dot, sur_render_args.alpha_shininess)) : 0;
dst_intensities[idx] += val;
}
}
}
);
//////////////////////////////////////////////////////////////////////
} // un-named
xreg::RayCasterSurRenderOCL::RayCasterSurRenderOCL()
: RayCasterOCL(), step_vecs_and_intersect_pts_wrt_itk_idx_dev_(ctx_)
{ }
xreg::RayCasterSurRenderOCL::RayCasterSurRenderOCL(const boost::compute::device& dev)
: RayCasterOCL(dev), step_vecs_and_intersect_pts_wrt_itk_idx_dev_(ctx_)
{ }
xreg::RayCasterSurRenderOCL::RayCasterSurRenderOCL(const boost::compute::context& ctx,
const boost::compute::command_queue& queue)
: RayCasterOCL(ctx, queue), step_vecs_and_intersect_pts_wrt_itk_idx_dev_(ctx_)
{ }
void xreg::RayCasterSurRenderOCL::allocate_resources()
{
namespace bc = boost::compute;
RayCasterOCL::allocate_resources();
// Build the surface rendering ray casting program
std::stringstream ss;
ss << RayCastBaseOCLStr()
<< boost::compute::type_definition<RayCasterSurRenderOCL::RayCastSurRenderArgs>()
<< kRAY_CASTING_SUR_RENDER_OPENCL_SRC;
bc::program prog = bc::program::create_with_source(ss.str(), ctx_);
prog.build();
dev_kernel1_ = prog.create_kernel("xregSurRenderKernel1");
dev_kernel2_ = prog.create_kernel("xregSurRenderKernel2");
step_vecs_and_intersect_pts_wrt_itk_idx_dev_.resize(this->camera_models_[0].num_det_rows *
this->camera_models_[0].num_det_cols *
this->num_projs_,
cmd_queue_);
}
void xreg::RayCasterSurRenderOCL::compute(const size_type vol_idx)
{
xregASSERT(this->resources_allocated_);
compute_helper_pre_kernels(vol_idx);
RayCastSurRenderArgs sur_args;
sur_args.thresh = render_thresh();
sur_args.num_backtracking_steps = num_backtracking_steps();
sur_args.ambient_reflection_ratio =
surface_render_params().ambient_reflection_ratio;
sur_args.diffuse_reflection_ratio =
surface_render_params().diffuse_reflection_ratio;
sur_args.specular_reflection_ratio =
surface_render_params().specular_reflection_ratio;
sur_args.alpha_shininess = surface_render_params().alpha_shininess;
// setup kernel arguments and launch
dev_kernel1_.set_arg(0, sizeof(ray_cast_kernel_args_), &ray_cast_kernel_args_);
dev_kernel1_.set_arg(1, sizeof(sur_args), &sur_args);
dev_kernel1_.set_arg(2, det_pts_dev_);
dev_kernel1_.set_arg(3, vol_texs_dev_[vol_idx]);
dev_kernel1_.set_arg(4, cam_to_itk_phys_xforms_dev_);
dev_kernel1_.set_arg(5, step_vecs_and_intersect_pts_wrt_itk_idx_dev_);
dev_kernel1_.set_arg(6, cam_model_for_proj_dev_);
dev_kernel1_.set_arg(7, focal_pts_dev_);
std::size_t global_work_size = ray_cast_kernel_args_.num_det_pts * this->num_projs_;
//std::size_t local_work_size = 512; passing null lets open CL pick a local size
cmd_queue_.enqueue_nd_range_kernel(dev_kernel1_,
1, // dim
0, // null offset -> start at 0
&global_work_size,
0 // passing null lets open CL pick a local size
).wait();
dev_kernel2_.set_arg(0, sizeof(ray_cast_kernel_args_), &ray_cast_kernel_args_);
dev_kernel2_.set_arg(1, sizeof(sur_args), &sur_args);
dev_kernel2_.set_arg(2, vol_texs_dev_[vol_idx]);
dev_kernel2_.set_arg(3, step_vecs_and_intersect_pts_wrt_itk_idx_dev_);
dev_kernel2_.set_arg(4, *proj_pixels_dev_to_use_);
cmd_queue_.enqueue_nd_range_kernel(dev_kernel2_,
1, // dim
0, // null offset -> start at 0
&global_work_size,
0 // passing null lets open CL pick a local size
).wait();
compute_helper_post_kernels(vol_idx);
}
|
{"hexsha": "1045ea08c3a14f05f0fff883eb579db4ffc21509", "size": 15051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/ray_cast/xregRayCastSurRenderOCL.cpp", "max_stars_repo_name": "rg2/xreg", "max_stars_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T18:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:25:13.000Z", "max_issues_repo_path": "lib/ray_cast/xregRayCastSurRenderOCL.cpp", "max_issues_repo_name": "rg2/xreg", "max_issues_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-09T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T15:39:44.000Z", "max_forks_repo_path": "lib/ray_cast/xregRayCastSurRenderOCL.cpp", "max_forks_repo_name": "rg2/xreg", "max_forks_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T05:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T12:29:50.000Z", "avg_line_length": 43.8804664723, "max_line_length": 204, "alphanum_fraction": 0.676034815, "num_tokens": 3805}
|
module TestDoctest
using StaticStorages
using Documenter: doctest
using Test
test_doctest() = doctest(StaticStorages, manual = false)
end # module
|
{"hexsha": "d9309358167f9e53287a181ebdd4f1cc3b36958d", "size": 151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/StaticStoragesTests/src/test_doctest.jl", "max_stars_repo_name": "tkf/StaticStorages.jl", "max_stars_repo_head_hexsha": "9756903be2b3f317f8168463cf55f9513d42dd16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/StaticStoragesTests/src/test_doctest.jl", "max_issues_repo_name": "tkf/StaticStorages.jl", "max_issues_repo_head_hexsha": "9756903be2b3f317f8168463cf55f9513d42dd16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-19T18:51:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:51:35.000Z", "max_forks_repo_path": "test/StaticStoragesTests/src/test_doctest.jl", "max_forks_repo_name": "tkf/StaticStorages.jl", "max_forks_repo_head_hexsha": "9756903be2b3f317f8168463cf55f9513d42dd16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1, "max_line_length": 56, "alphanum_fraction": 0.7947019868, "num_tokens": 43}
|
""" Functionality to analyse random telegraph signals
Created on Wed Feb 28 10:20:46 2018
@author: riggelenfv /eendebakpt
"""
import operator
import warnings
from typing import Optional, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import qcodes
from qtt.algorithms.fitting import fit_double_gaussian, refit_double_gaussian
from qtt.algorithms.functions import double_gaussian, exp_function, fit_exp_decay, gaussian
from qtt.algorithms.markov_chain import ContinuousTimeMarkovModel
from qtt.utilities.tools import addPPTslide
from qtt.utilities.visualization import get_axis, plot_double_gaussian_fit, plot_vertical_line
def rts2tunnel_ratio(binary_signal: np.ndarray) -> float:
""" Calculate ratio between tunnelrate down and up
From the mean and standard deviation of the RTS data we can determine the ratio between
the two tunnel rates. See equations on https://en.wikipedia.org/wiki/Telegraph_process
Args:
binary_signal: RTS signal with two levels 0 and 1
Returns:
Ratio of tunnelrate up to down (l2) and down to up (l1)
"""
binary_signal = np.asarray(binary_signal)
c1 = binary_signal.min()
c2 = binary_signal.max()
number_of_transitions = np.abs(np.diff(binary_signal)).sum()
if number_of_transitions < 40:
warnings.warn(f'number of transitions {number_of_transitions} is low, estimate can be inaccurate')
if c1 == c2:
raise ValueError(f'binary signal contains only a single value {c1}')
if c1 != 0 or c2 != 1:
raise ValueError('signal must only contain 0 and 1')
m = binary_signal.mean()
var = binary_signal.var()
ratio_l2_over_l1 = var/m**2
return ratio_l2_over_l1
def transitions_durations(data: np.ndarray, split: float, add_start: bool = False,
add_end: bool = False) -> Tuple[np.ndarray, np.ndarray]:
""" For data of a two level system (up and down) determine durations of segments
This function determines which datapoints belong to which
level and finds the transitions, in order to determines
how long the system stays in these levels.
Args:
data : data from the two level system
split: value that separates the up and down level
add_start: If True, then include the segments at the start of the data
add_end:: If True, then include the segments at the end of the data
Returns:
duration_dn: array of the durations (unit: data points) in the down level
duration_up: array of durations (unit: data points) in the up level
"""
size = len(data)
if size == 0:
return np.array([], dtype=int), np.array([], dtype=int)
# split the data and find the index of the transitions, transitions from
# up to down are marked with -1 and from down to up with 1
b = np.asarray(data) > split
d = np.diff(b.astype(int))
transitions_down_to_up = (d == 1).nonzero()[0]
transitions_up_to_down = (d == -1).nonzero()[0]
# durations are calculated by taking the difference in data points between
# the transitions
endpoints_dn = []
endpoints_up = []
if data[0] <= split and data[-1] <= split:
duration_up = transitions_up_to_down - transitions_down_to_up
duration_dn = transitions_down_to_up[1:] - transitions_up_to_down[:-1]
if len(transitions_up_to_down) == 0:
if add_start or add_end:
endpoints_dn.append(size)
else:
if add_start:
endpoints_dn.append(transitions_down_to_up[0]+1)
if add_end:
endpoints_dn.append(size - transitions_up_to_down[-1]-1)
elif data[0] <= split < data[-1]:
duration_up = transitions_up_to_down - transitions_down_to_up[:-1]
duration_dn = transitions_down_to_up[1:]-transitions_up_to_down
if add_start:
endpoints_dn.append(transitions_down_to_up[0]+1)
if add_end:
endpoints_up.append(size-transitions_down_to_up[-1]-1)
elif data[0] > split >= data[-1]:
duration_up = transitions_up_to_down[1:] - transitions_down_to_up
duration_dn = transitions_down_to_up - transitions_up_to_down[:-1]
if add_start:
endpoints_up.append(transitions_up_to_down[0]+1)
if add_end:
endpoints_dn.append(size-transitions_up_to_down[-1]-1)
else: # case: data[0] > split and data[-1] > split:
duration_up = transitions_up_to_down[1:] - transitions_down_to_up[:-1]
duration_dn = transitions_down_to_up - transitions_up_to_down
if len(transitions_up_to_down) == 0:
if add_start or add_end:
endpoints_up.append(size)
else:
if add_start:
endpoints_up.append(transitions_up_to_down[0]+1)
if add_end:
endpoints_up.append(size-transitions_down_to_up[-1]-1)
duration_dn = np.concatenate((duration_dn, np.asarray(endpoints_dn, dtype=int)), dtype=int)
duration_up = np.concatenate((duration_up, np.asarray(endpoints_up, dtype=int)), dtype=int)
return duration_dn, duration_up
class FittingException(Exception):
""" Fitting exception in RTS code """
pass
def _plot_rts_histogram(data, num_bins, double_gaussian_fit, split, figure_title):
_, bins, _ = plt.hist(data, bins=num_bins)
bincentres = np.array([(bins[i] + bins[i + 1]) / 2 for i in range(0, len(bins) - 1)])
get_left_mean_std_amplitude = operator.itemgetter(4, 2, 0)
get_right_mean_std_amplitude = operator.itemgetter(5, 3, 1)
left_gaussian = list(get_left_mean_std_amplitude(double_gaussian_fit))
right_gaussian = list(get_right_mean_std_amplitude(double_gaussian_fit))
plt.plot(bincentres, double_gaussian(bincentres, double_gaussian_fit), '-m', label='Fitted double gaussian')
plt.plot(bincentres, gaussian(bincentres, *left_gaussian), 'g', label='Left Gaussian', alpha=.85, linewidth=.75)
plt.plot(bincentres, gaussian(bincentres, *right_gaussian), 'r', label='Right Gaussian', alpha=.85, linewidth=.75)
plt.plot(split, double_gaussian(split, double_gaussian_fit), 'ro', markersize=8, label='split: %.3f' % split)
plt.xlabel('Measured value (a.u.)')
plt.ylabel('Data points per bin')
plt.legend()
plt.title(figure_title)
def two_level_threshold(data: np.ndarray, number_of_bins: int = 40) -> dict:
""" Determine threshold for separation of two-level signal
Typical examples of such a signal are an RTS signal or Elzerman readout.
Args:
data: Two dimensional array with single traces
number_of_bins: Number of bins to use for calculation of double histogram
Returns:
Dictionary with results. The key readout_threshold contains the calculated threshold
"""
counts, bins = np.histogram(data, bins=number_of_bins)
bin_centres = np.array([(bins[i] + bins[i + 1]) / 2 for i in range(0, len(bins) - 1)])
_, result_dict = fit_double_gaussian(bin_centres, counts)
result_dict = refit_double_gaussian(result_dict, bin_centres, counts)
result = {'signal_threshold': result_dict['split'], 'double_gaussian_fit': result_dict,
'separation': result_dict['separation'],
'histogram': {'counts': counts, 'bins': bins, 'bin_centres': bin_centres}}
return result
def plot_two_level_threshold(results: dict, fig: int = 100, plot_initial_estimate: bool = False):
separation = results['separation']
threshold = results['signal_threshold']
ax = get_axis(fig)
bin_centres = results['histogram']['bin_centres']
counts = results['histogram']['counts']
ax.bar(bin_centres, counts, width=bin_centres[1] - bin_centres[0], label='histogram')
ax.set_ylabel('Counts')
ax.set_xlabel('Signal [a.u.]')
plot_vertical_line(threshold, label='threshold')
plot_double_gaussian_fit(results['double_gaussian_fit'], bin_centres)
ax.set_title(f'Two-level signal: separation {separation:.3f}, threshold {threshold:.3g}')
if plot_initial_estimate:
xdata = np.linspace(bin_centres[0], bin_centres[-1], 300)
initial_estimate = results['double_gaussian_fit']['parameters initial guess']
left0 = initial_estimate[::2][::-1]
right0 = initial_estimate[1::2][::-1]
ax.plot(xdata, gaussian(xdata, *left0), ':g', label='initial estimate left')
ax.plot(xdata, gaussian(xdata, *right0), ':r', label='initial estimate right')
def _create_integer_histogram(durations):
""" Calculate number of bins, bin edges and histogram for durations
This method works if the data is sampled at integer durations.
"""
numbins = int(np.sqrt(len(durations)))
if numbins == 0:
raise Exception('cannot create histogram with zero bins')
bin_size = int(np.ceil((durations.max() - (durations.min() - .5)) / numbins))
# choose bins carefully, since our data is sampled only at discrete times
bins = np.arange(durations.min() - .5, durations.max() + bin_size, bin_size)
counts, bin_edges = np.histogram(durations, bins=bins)
return counts, bin_edges, bin_size
def tunnelrates_RTS(data: Union[np.ndarray, qcodes.data.data_set.DataSet], samplerate: Optional[float] = None,
min_sep: float = 2.0, max_sep: float = 7.0, min_duration: int = 5,
num_bins: Optional[int] = None, fig: Optional[int] = None, ppt=None,
verbose: int = 0,
offset_parameter: Optional[float] = None) -> Tuple[Optional[float], Optional[float], dict]:
"""
This function takes an RTS dataset, fits a double gaussian, finds the split between the two levels,
determines the durations in these two levels, fits a decaying exponential on two arrays of durations,
which gives the tunneling frequency for both the levels. If the number of datapoints is too low to get enough
points per bin for the exponential fit (for either the up or the down level), this analysis step is passed over.
tunnelrate_dn and tunnelrate_up are returned as None, but similar information can be substracted from
parameters['down_segments'] and parameters['up_segments'].
Args:
data: qcodes DataSet (or 1d data array) with the RTS data
samplerate: sampling rate of the acquisition device, optional if given in the metadata
of the measured data
min_sep: if the separation found for the fit of the double gaussian is less then this value, the
fit probably failed and a FittingException is raised
max_sep: if the separation found for the fit of the double gaussian is more then this value, the
fit probably failed and a FittingException is raised
min_duration: minimal number of datapoints a duration should last to be taking into account for the
analysis
num_bins: number of bins for the histogram of signal values. If None, then determine based
on the size of the data
fig: shows figures and sends them to the ppt when is not None
ppt: determines if the figures are send to a powerpoint presentation
verbose: prints info to the console when > 0
offset_parameter: Offset parameter for fitting of exponential decay
Returns:
tunnelrate_dn: tunneling rate of the down level to the up level (kHz) or None in case of
not enough datapoints
tunnelrate_up: tunneling rate of the up level to the down level (kHz) or None in case of
not enough datapoints
parameters: dictionary with relevent (fit) parameters. this includes:
tunnelrate_down (float): tunnel rate in Hz
tunnelrate_up (float): tunnel rate up in Hz
"""
if isinstance(data, qcodes.data.data_set.DataSet):
if samplerate is None:
samplerate = data.metadata.get('samplerate', None)
data = np.array(data.default_parameter_array())
if samplerate is None:
raise ValueError('samplerate should be set to the data samplerate in Hz')
# plotting a 2d histogram of the RTS
if fig is not None:
max_num_bins_time_domain = 1200
max_num_bins_signal_domain = 800
xdata = np.arange(len(data)) / (samplerate / 1_000)
ny = min(int(np.sqrt(len(data))/2), max_num_bins_signal_domain)
nx = min(int(np.sqrt(len(xdata))/2), max_num_bins_time_domain)
Z, xedges, yedges = np.histogram2d(xdata, data, bins=[nx, ny])
title = '2d histogram RTS'
Fig = plt.figure(fig)
plt.clf()
plt.pcolormesh(xedges, yedges, Z.T)
cb = plt.colorbar()
cb.set_label('Data points per bin')
plt.xlabel('Time (ms)')
plt.ylabel('Signal sensing dot (a.u.)')
plt.title(title)
if ppt:
addPPTslide(title=title, fig=Fig)
# binning the data and determining the bincentres
if num_bins is None:
max_num_bins_fitting = 1200
num_bins = min(int(np.sqrt(len(data))), max_num_bins_fitting)
fit_results = two_level_threshold(data, number_of_bins=num_bins)
separation = fit_results['separation']
split = fit_results['signal_threshold']
double_gaussian_fit_parameters = fit_results['double_gaussian_fit']['parameters']
if verbose:
print('Fit parameters double gaussian:\n mean down: %.3f counts' %
double_gaussian_fit_parameters[4] + ', mean up: %.3f counts' % double_gaussian_fit_parameters[
5] + ', std down: %.3f counts' % double_gaussian_fit_parameters[2] + ', std up:%.3f counts' %
double_gaussian_fit_parameters[3])
print('Separation between peaks gaussians: %.3f std' % separation)
print('Split between two levels: %.3f' % split)
# plotting the data in a histogram, the fitted two gaussian model and the split
if fig:
figure_title = 'Histogram of two level signal' + f'\nseparation: {separation:.1f} [std]'
Fig = plt.figure(fig + 1)
plt.clf()
_plot_rts_histogram(data, num_bins, double_gaussian_fit_parameters, split, figure_title)
if ppt:
addPPTslide(title=title, fig=Fig, notes='Fit parameters double gaussian:\n mean down: %.3f counts' %
double_gaussian_fit_parameters[4] + ', mean up:%.3f counts' %
double_gaussian_fit_parameters[5] + ', std down: %.3f counts' %
double_gaussian_fit_parameters[2] + ', std up:%.3f counts' %
double_gaussian_fit_parameters[
3] + '.Separation between peaks gaussians: %.3f std' % separation + '. Split between two levels: %.3f' % split)
if separation < min_sep:
raise FittingException(
'Separation between the peaks of the gaussian %.1f is less then %.1f std, indicating that the fit was not succesfull.' % (
separation, min_sep))
if separation > max_sep:
raise FittingException(
'Separation between the peaks of the gaussian %.1f is more then %.1f std, indicating that the fit was not succesfull.' % (
separation, max_sep))
thresholded_data = data > split
fraction_up = np.sum(thresholded_data) / data.size
fraction_down = 1 - fraction_up
# count the number of transitions and their duration
durations_dn_idx, durations_up_idx = transitions_durations(data, split)
# throwing away the durations with less data points then min_duration
durations_up_min_duration = durations_up_idx >= min_duration
durations_up = durations_up_idx[durations_up_min_duration]
durations_dn_min_duration = durations_dn_idx >= min_duration
durations_dn = durations_dn_idx[durations_dn_min_duration]
if len(durations_up) < 1:
raise FittingException('All durations_up are shorter than the minimal duration.')
if len(durations_dn) < 1:
raise FittingException('All durations_dn are shorter than the minimal duration.')
# calculating the number of bins and counts for down level
counts_dn, bins_dn, _ = _create_integer_histogram(durations_dn)
# calculating the number of bins and counts for up level
counts_up, bins_up, _ = _create_integer_histogram(durations_up)
if verbose >= 2:
print(f' _create_integer_histogram: up/down: number of bins {len(bins_up)}/{len(bins_dn)}')
bins_dn = bins_dn / samplerate
bins_up = bins_up / samplerate
if verbose >= 2:
print('counts_dn %d, counts_up %d' % (counts_dn[0], counts_up[0]))
tunnelrate_dn = None
tunnelrate_up = None
minimal_count_number = 50
if counts_dn[0] < minimal_count_number:
warnings.warn(
f'Number of down datapoints {counts_dn[0]} is not enough (minimal_count_number {minimal_count_number})'
f' to make an accurate fit of the exponential decay for level down. ' +
'Look therefore at the mean value of the measurement segments')
if counts_up[0] < minimal_count_number:
warnings.warn(
f'Number of up datapoints {counts_up[0]} is not enough (minimal_count_number {minimal_count_number}) to make an acurate fit of the exponential decay for level up. '
+ 'Look therefore at the mean value of the measurement segments')
parameters = {'sampling rate': samplerate,
'fit parameters double gaussian': double_gaussian_fit_parameters,
'separations between peaks gaussians': separation,
'split between the two levels': split}
parameters['down_segments'] = {'number': len(durations_dn_idx), 'mean': np.mean(durations_dn_idx) / samplerate, 'p50': np.percentile(
durations_dn_idx, 50) / samplerate, 'number_filtered': len(durations_dn), 'mean_filtered': np.mean(durations_dn)}
parameters['up_segments'] = {'number': len(durations_up_idx), 'mean': np.mean(durations_up_idx) / samplerate, 'p50': np.percentile(
durations_up_idx, 50) / samplerate, 'number_filtered': len(durations_up), 'mean_filtered': np.mean(durations_up)}
parameters['tunnelrate_down_to_up'] = 1. / parameters['down_segments']['mean']
parameters['tunnelrate_up_to_down'] = 1. / parameters['up_segments']['mean']
parameters['fraction_down'] = fraction_down
parameters['fraction_up'] = fraction_up
parameters['bins_dn'] = {'number': len(bins_dn), 'size': np.diff(bins_dn).mean(), 'start': bins_dn[0]}
parameters['bins_up'] = {'number': len(bins_up), 'size': np.diff(bins_up).mean(), 'start': bins_up[0]}
parameters['tunnelrate_ratio'] = rts2tunnel_ratio(thresholded_data)
if (counts_dn[0] > minimal_count_number) and (counts_up[0] > minimal_count_number):
def _fit_and_plot_decay(bincentres, counts, label, fig_label):
""" Fitting and plotting of exponential decay for level """
A_fit, B_fit, gamma_fit = fit_exp_decay(bincentres, counts, offset_parameter=offset_parameter)
tunnelrate = gamma_fit / 1000
other_label = 'up' if label == 'down' else 'down'
if verbose:
print(f'Tunnel rate {label} to {other_label}: %.1f kHz' % tunnelrate)
time_scaling = 1e3
if fig_label:
title = f'Fitted exponential decay, level {label}'
Fig = plt.figure(fig_label)
plt.clf()
plt.plot(time_scaling * bincentres, counts, 'o', label=f'Counts {label}')
plt.plot(time_scaling * bincentres, exp_function(bincentres, A_fit, B_fit, gamma_fit),
'r', label=r'Fitted exponential decay $\Gamma_{\mathrm{%s\ to\ %s}}$: %.1f kHz' % (label, other_label, tunnelrate))
plt.xlabel('Lifetime (ms)')
plt.ylabel('Counts per bin')
plt.legend()
plt.title(title)
if ppt:
addPPTslide(title=title, fig=Fig)
fit_parameters = [A_fit, B_fit, gamma_fit]
return tunnelrate, fit_parameters
bincentres_dn = (bins_dn[:-1]+bins_dn[1:])/2
fig_label = None if fig is None else fig + 2
tunnelrate_dn, fit_parameters_down = _fit_and_plot_decay(
bincentres_dn, counts_dn, label='down', fig_label=fig_label)
bincentres_up = (bins_up[:-1]+bins_up[1:])/2
fig_label = None if fig is None else fig + 3
tunnelrate_up, fit_parameters_up = _fit_and_plot_decay(
bincentres_up, counts_up, label='up', fig_label=fig_label)
parameters['fit parameters exp. decay down'] = fit_parameters_down
parameters['fit parameters exp. decay up'] = fit_parameters_up
parameters['tunnelrate_down_exponential_fit'] = tunnelrate_dn
parameters['tunnelrate_up_exponential_fit'] = tunnelrate_up
else:
parameters['tunnelrate_down_exponential_fit'] = None
parameters['tunnelrate_up_exponential_fit'] = None
return tunnelrate_dn, tunnelrate_up, parameters
def generate_RTS_signal(number_of_samples: int = 100000, std_gaussian_noise: float = 0.1,
uniform_noise: float = 0.05, rate_up: float = 10e3, rate_down: float = 15e3, samplerate: float = 1e6) -> np.ndarray:
""" Generate a RTS signal
Args:
number_of_samples: Length the the trace to be generated
std_normal_noise: std of Gaussian noise added to the signal
uniform_noise: uniform noise in the range +- uniform_noise/2 is added to the signal
rate_up: rate from down to up
rate_down: rate from up to down
samplerate: The samplerate of the signal to be generated
Returns:
Array with generated signal (0 is down, 1 is up)
"""
rts_model = ContinuousTimeMarkovModel(['down', 'up'], [rate_up / samplerate,
rate_down / samplerate], np.array([[0., 1], [1, 0]]))
data = rts_model.generate_sequence(number_of_samples, delta_time=1)
if uniform_noise != 0:
data = data + uniform_noise * (np.random.rand(data.size, ) - .5)
if std_gaussian_noise != 0:
data = data + np.random.normal(0, std_gaussian_noise, data.size)
return data
|
{"hexsha": "b44a9c235707a304ebeba76df3324135df799ee6", "size": 22503, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/qtt/algorithms/random_telegraph_signal.py", "max_stars_repo_name": "VandersypenQutech/qtt", "max_stars_repo_head_hexsha": "94366c5a4a8fe1c14fc89a8129fca49ea36d16a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qtt/algorithms/random_telegraph_signal.py", "max_issues_repo_name": "VandersypenQutech/qtt", "max_issues_repo_head_hexsha": "94366c5a4a8fe1c14fc89a8129fca49ea36d16a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qtt/algorithms/random_telegraph_signal.py", "max_forks_repo_name": "VandersypenQutech/qtt", "max_forks_repo_head_hexsha": "94366c5a4a8fe1c14fc89a8129fca49ea36d16a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9244897959, "max_line_length": 176, "alphanum_fraction": 0.6641336711, "include": true, "reason": "import numpy", "num_tokens": 5329}
|
\section{\module{ossaudiodev} ---
Access to OSS-compatible audio devices}
\declaremodule{builtin}{ossaudiodev}
\platform{Linux, FreeBSD}
\modulesynopsis{Access to OSS-compatible audio devices.}
\versionadded{2.3}
This module allows you to access the OSS (Open Sound System) audio
interface. OSS is available for a wide range of open-source and
commercial Unices, and is the standard audio interface for Linux and
recent versions of FreeBSD.
% Things will get more complicated for future Linux versions, since
% ALSA is in the standard kernel as of 2.5.x. Presumably if you
% use ALSA, you'll have to make sure its OSS compatibility layer
% is active to use ossaudiodev, but you're gonna need it for the vast
% majority of Linux audio apps anyways.
%
% Sounds like things are also complicated for other BSDs. In response
% to my python-dev query, Thomas Wouters said:
%
% > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial
% > OSS installation manual tells you to remove references to OSS/Free from the
% > kernel :)
%
% but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes
% from its <soundcard.h>:
% > * WARNING! WARNING!
% > * This is an OSS (Linux) audio emulator.
% > * Use the Native NetBSD API for developing new code, and this
% > * only for compiling Linux programs.
%
% There's also an ossaudio manpage on OpenBSD that explains things
% further. Presumably NetBSD and OpenBSD have a different standard
% audio interface. That's the great thing about standards, there are so
% many to choose from ... ;-)
%
% This probably all warrants a footnote or two, but I don't understand
% things well enough right now to write it! --GPW
\begin{seealso}
\seetitle[http://www.opensound.com/pguide/oss.pdf]
{Open Sound System Programmer's Guide} {the official
documentation for the OSS C API}
\seetext{The module defines a large number of constants supplied by
the OSS device driver; see \code{<sys/soundcard.h>} on either
Linux or FreeBSD for a listing .}
\end{seealso}
\module{ossaudiodev} defines the following variables and functions:
\begin{excdesc}{OSSAudioError}
This exception is raised on certain errors. The argument is a string
describing what went wrong.
(If \module{ossaudiodev} receives an error from a system call such as
\cfunction{open()}, \cfunction{write()}, or \cfunction{ioctl()}, it
raises \exception{IOError}. Errors detected directly by
\module{ossaudiodev} result in \exception{OSSAudioError}.)
(For backwards compatibility, the exception class is also available as
\code{ossaudiodev.error}.)
\end{excdesc}
\begin{funcdesc}{open}{\optional{device, }mode}
Open an audio device and return an OSS audio device object. This
object supports many file-like methods, such as \method{read()},
\method{write()}, and \method{fileno()} (although there are subtle
differences between conventional Unix read/write semantics and those of
OSS audio devices). It also supports a number of audio-specific
methods; see below for the complete list of methods.
\var{device} is the audio device filename to use. If it is not
specified, this module first looks in the environment variable
\envvar{AUDIODEV} for a device to use. If not found, it falls back to
\file{/dev/dsp}.
\var{mode} is one of \code{'r'} for read-only (record) access,
\code{'w'} for write-only (playback) access and \code{'rw'} for both.
Since many sound cards only allow one process to have the recorder or
player open at a time, it is a good idea to open the device only for the
activity needed. Further, some sound cards are half-duplex: they can be
opened for reading or writing, but not both at once.
Note the unusual calling syntax: the \emph{first} argument is optional,
and the second is required. This is a historical artifact for
compatibility with the older \module{linuxaudiodev} module which
\module{ossaudiodev} supersedes. % XXX it might also be motivated
% by my unfounded-but-still-possibly-true belief that the default
% audio device varies unpredictably across operating systems. -GW
\end{funcdesc}
\begin{funcdesc}{openmixer}{\optional{device}}
Open a mixer device and return an OSS mixer device object.
\var{device} is the mixer device filename to use. If it is
not specified, this module first looks in the environment variable
\envvar{MIXERDEV} for a device to use. If not found, it falls back to
\file{/dev/mixer}.
\end{funcdesc}
\subsection{Audio Device Objects \label{ossaudio-device-objects}}
Before you can write to or read from an audio device, you must call
three methods in the correct order:
\begin{enumerate}
\item \method{setfmt()} to set the output format
\item \method{channels()} to set the number of channels
\item \method{speed()} to set the sample rate
\end{enumerate}
Alternately, you can use the \method{setparameters()} method to set all
three audio parameters at once. This is more convenient, but may not be
as flexible in all cases.
The audio device objects returned by \function{open()} define the
following methods:
\begin{methoddesc}[audio device]{close}{}
Explicitly close the audio device. When you are done writing to or
reading from an audio device, you should explicitly close it. A closed
device cannot be used again.
\end{methoddesc}
\begin{methoddesc}[audio device]{fileno}{}
Return the file descriptor associated with the device.
\end{methoddesc}
\begin{methoddesc}[audio device]{read}{size}
Read \var{size} bytes from the audio input and return them as a Python
string. Unlike most \UNIX{} device drivers, OSS audio devices in
blocking mode (the default) will block \function{read()} until the
entire requested amount of data is available.
\end{methoddesc}
\begin{methoddesc}[audio device]{write}{data}
Write the Python string \var{data} to the audio device and return the
number of bytes written. If the audio device is in blocking mode (the
default), the entire string is always written (again, this is different
from usual \UNIX{} device semantics). If the device is in non-blocking
mode, some data may not be written---see \method{writeall()}.
\end{methoddesc}
\begin{methoddesc}[audio device]{writeall}{data}
Write the entire Python string \var{data} to the audio device: waits
until the audio device is able to accept data, writes as much data as it
will accept, and repeats until \var{data} has been completely written.
If the device is in blocking mode (the default), this has the same
effect as \method{write()}; \method{writeall()} is only useful in
non-blocking mode. Has no return value, since the amount of data
written is always equal to the amount of data supplied.
\end{methoddesc}
The following methods each map to exactly one
\function{ioctl()} system call. The correspondence is obvious: for
example, \method{setfmt()} corresponds to the \code{SNDCTL_DSP_SETFMT}
ioctl, and \method{sync()} to \code{SNDCTL_DSP_SYNC} (this can be useful
when consulting the OSS documentation). If the underlying
\function{ioctl()} fails, they all raise \exception{IOError}.
\begin{methoddesc}[audio device]{nonblock}{}
Put the device into non-blocking mode. Once in non-blocking mode, there
is no way to return it to blocking mode.
\end{methoddesc}
\begin{methoddesc}[audio device]{getfmts}{}
Return a bitmask of the audio output formats supported by the
soundcard. Some of the formats supported by OSS are:
\begin{tableii}{l|l}{constant}{Format}{Description}
\lineii{AFMT_MU_LAW}
{a logarithmic encoding (used by Sun \code{.au} files and
\filenq{/dev/audio})}
\lineii{AFMT_A_LAW}
{a logarithmic encoding}
\lineii{AFMT_IMA_ADPCM}
{a 4:1 compressed format defined by the Interactive Multimedia
Association}
\lineii{AFMT_U8}
{Unsigned, 8-bit audio}
\lineii{AFMT_S16_LE}
{Signed, 16-bit audio, little-endian byte order (as used by
Intel processors)}
\lineii{AFMT_S16_BE}
{Signed, 16-bit audio, big-endian byte order (as used by 68k,
PowerPC, Sparc)}
\lineii{AFMT_S8}
{Signed, 8 bit audio}
\lineii{AFMT_U16_LE}
{Unsigned, 16-bit little-endian audio}
\lineii{AFMT_U16_BE}
{Unsigned, 16-bit big-endian audio}
\end{tableii}
Consult the OSS documentation for a full list of audio formats, and note
that most devices support only a subset of these formats. Some older
devices only support \constant{AFMT_U8}; the most common format used
today is \constant{AFMT_S16_LE}.
\end{methoddesc}
\begin{methoddesc}[audio device]{setfmt}{format}
Try to set the current audio format to \var{format}---see
\method{getfmts()} for a list. Returns the audio format that the device
was set to, which may not be the requested format. May also be used to
return the current audio format---do this by passing an ``audio format''
of
\constant{AFMT_QUERY}.
\end{methoddesc}
\begin{methoddesc}[audio device]{channels}{nchannels}
Set the number of output channels to \var{nchannels}. A value of 1
indicates monophonic sound, 2 stereophonic. Some devices may have more
than 2 channels, and some high-end devices may not support mono.
Returns the number of channels the device was set to.
\end{methoddesc}
\begin{methoddesc}[audio device]{speed}{samplerate}
Try to set the audio sampling rate to \var{samplerate} samples per
second. Returns the rate actually set. Most sound devices don't
support arbitrary sampling rates. Common rates are:
\begin{tableii}{l|l}{textrm}{Rate}{Description}
\lineii{8000}{default rate for \filenq{/dev/audio}}
\lineii{11025}{speech recording}
\lineii{22050}{}
\lineii{44100}{CD quality audio (at 16 bits/sample and 2 channels)}
\lineii{96000}{DVD quality audio (at 24 bits/sample)}
\end{tableii}
\end{methoddesc}
\begin{methoddesc}[audio device]{sync}{}
Wait until the sound device has played every byte in its buffer. (This
happens implicitly when the device is closed.) The OSS documentation
recommends closing and re-opening the device rather than using
\method{sync()}.
\end{methoddesc}
\begin{methoddesc}[audio device]{reset}{}
Immediately stop playing or recording and return the device to a
state where it can accept commands. The OSS documentation recommends
closing and re-opening the device after calling \method{reset()}.
\end{methoddesc}
\begin{methoddesc}[audio device]{post}{}
Tell the driver that there is likely to be a pause in the output, making
it possible for the device to handle the pause more intelligently. You
might use this after playing a spot sound effect, before waiting for
user input, or before doing disk I/O.
\end{methoddesc}
The following convenience methods combine several ioctls, or one ioctl
and some simple calculations.
\begin{methoddesc}[audio device]{setparameters}
{format, nchannels, samplerate \optional{, strict=False}}
Set the key audio sampling parameters---sample format, number of
channels, and sampling rate---in one method call. \var{format},
\var{nchannels}, and \var{samplerate} should be as specified in the
\method{setfmt()}, \method{channels()}, and \method{speed()}
methods. If \var{strict} is true, \method{setparameters()} checks to
see if each parameter was actually set to the requested value, and
raises \exception{OSSAudioError} if not. Returns a tuple (\var{format},
\var{nchannels}, \var{samplerate}) indicating the parameter values that
were actually set by the device driver (i.e., the same as the return
values of \method{setfmt()}, \method{channels()}, and \method{speed()}).
For example,
\begin{verbatim}
(fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)
\end{verbatim}
is equivalent to
\begin{verbatim}
fmt = dsp.setfmt(fmt)
channels = dsp.channels(channels)
rate = dsp.rate(channels)
\end{verbatim}
\end{methoddesc}
\begin{methoddesc}[audio device]{bufsize}{}
Returns the size of the hardware buffer, in samples.
\end{methoddesc}
\begin{methoddesc}[audio device]{obufcount}{}
Returns the number of samples that are in the hardware buffer yet to be
played.
\end{methoddesc}
\begin{methoddesc}[audio device]{obuffree}{}
Returns the number of samples that could be queued into the hardware
buffer to be played without blocking.
\end{methoddesc}
\subsection{Mixer Device Objects \label{mixer-device-objects}}
The mixer object provides two file-like methods:
\begin{methoddesc}[mixer device]{close}{}
This method closes the open mixer device file. Any further attempts to
use the mixer after this file is closed will raise an IOError.
\end{methoddesc}
\begin{methoddesc}[mixer device]{fileno}{}
Returns the file handle number of the open mixer device file.
\end{methoddesc}
The remaining methods are specific to audio mixing:
\begin{methoddesc}[mixer device]{controls}{}
This method returns a bitmask specifying the available mixer controls
(``Control'' being a specific mixable ``channel'', such as
\constant{SOUND_MIXER_PCM} or \constant{SOUND_MIXER_SYNTH}). This
bitmask indicates a subset of all available mixer controls---the
\constant{SOUND_MIXER_*} constants defined at module level. To determine if,
for example, the current mixer object supports a PCM mixer, use the
following Python code:
\begin{verbatim}
mixer=ossaudiodev.openmixer()
if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
# PCM is supported
... code ...
\end{verbatim}
For most purposes, the \constant{SOUND_MIXER_VOLUME} (master volume) and
\constant{SOUND_MIXER_PCM} controls should suffice---but code that uses the
mixer should be flexible when it comes to choosing mixer controls. On
the Gravis Ultrasound, for example, \constant{SOUND_MIXER_VOLUME} does not
exist.
\end{methoddesc}
\begin{methoddesc}[mixer device]{stereocontrols}{}
Returns a bitmask indicating stereo mixer controls. If a bit is set,
the corresponding control is stereo; if it is unset, the control is
either monophonic or not supported by the mixer (use in combination with
\method{controls()} to determine which).
See the code example for the \method{controls()} function for an example
of getting data from a bitmask.
\end{methoddesc}
\begin{methoddesc}[mixer device]{reccontrols}{}
Returns a bitmask specifying the mixer controls that may be used to
record. See the code example for \method{controls()} for an example of
reading from a bitmask.
\end{methoddesc}
\begin{methoddesc}[mixer device]{get}{control}
Returns the volume of a given mixer control. The returned volume is a
2-tuple \code{(left_volume,right_volume)}. Volumes are specified as
numbers from 0 (silent) to 100 (full volume). If the control is
monophonic, a 2-tuple is still returned, but both volumes are
the same.
Raises \exception{OSSAudioError} if an invalid control was is specified,
or \exception{IOError} if an unsupported control is specified.
\end{methoddesc}
\begin{methoddesc}[mixer device]{set}{control, (left, right)}
Sets the volume for a given mixer control to \code{(left,right)}.
\code{left} and \code{right} must be ints and between 0 (silent) and 100
(full volume). On success, the new volume is returned as a 2-tuple.
Note that this may not be exactly the same as the volume specified,
because of the limited resolution of some soundcard's mixers.
Raises \exception{OSSAudioError} if an invalid mixer control was
specified, or if the specified volumes were out-of-range.
\end{methoddesc}
\begin{methoddesc}[mixer device]{get_recsrc}{}
This method returns a bitmask indicating which control(s) are
currently being used as a recording source.
\end{methoddesc}
\begin{methoddesc}[mixer device]{set_recsrc}{bitmask}
Call this function to specify a recording source. Returns a bitmask
indicating the new recording source (or sources) if successful; raises
\exception{IOError} if an invalid source was specified. To set the current
recording source to the microphone input:
\begin{verbatim}
mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)
\end{verbatim}
\end{methoddesc}
|
{"hexsha": "cecf53c161a1975bd6cf1f897cd3289611db4ff5", "size": 15850, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Doc/lib/libossaudiodev.tex", "max_stars_repo_name": "deadsnakes/python2.4", "max_stars_repo_head_hexsha": "f493d5415b662e99a73d017bcafe2148c5bc8fb5", "max_stars_repo_licenses": ["PSF-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Doc/lib/libossaudiodev.tex", "max_issues_repo_name": "deadsnakes/python2.4", "max_issues_repo_head_hexsha": "f493d5415b662e99a73d017bcafe2148c5bc8fb5", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Doc/lib/libossaudiodev.tex", "max_forks_repo_name": "deadsnakes/python2.4", "max_forks_repo_head_hexsha": "f493d5415b662e99a73d017bcafe2148c5bc8fb5", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9560723514, "max_line_length": 79, "alphanum_fraction": 0.7626498423, "num_tokens": 4076}
|
# Copyright (c) 2020 Vincent Liu
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
""" Contains auxiliary helper functions. """
import functools
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import random
import torch
import torch.nn as nn
def compose(*fns):
""" Composes a list of functions. """
def compose2(f, g):
return lambda x: f(g(x))
return functools.reduce(compose2, fns, lambda x: x)
def get_preprocessing_fn(mu_law: bool = True):
""" Returns sequential list of functions for preprocessing audio. """
fns = []
if mu_law:
fns += [mu_transform]
# If no transforms. return identity function.
if len(fns) == 0:
return lambda x: x
return compose(*fns)
def get_postprocessing_fn(mu_law: bool = True):
""" Returns sequential list of functions for postprocessing audio. """
fns = []
if mu_law:
fns += [mu_inverse]
# If no transforms. return identity function.
if len(fns) == 0:
return lambda x: x
return compose(*fns)
def seed_everything(seed: int = 1234):
""" Sets seed for pseudo-random number generators in pytorch, numpy, python.random, os.environ["PYTHONHASHSEED"]. """
max_seed_value = np.iinfo(np.uint32).max
min_seed_value = np.iinfo(np.uint32).min
try:
seed = int(seed)
except (TypeError, ValueError):
seed = random.randint(min_seed_value, max_seed_value)
if (seed > max_seed_value) or (seed < min_seed_value):
print("{} is not in bounds, numpy accepts from {} to {}".format(seed, min_seed_value, max_seed_value))
seed = random.randint(min_seed_value, max_seed_value)
os.environ["PYTHONHASHSEED"] = str(seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
return seed
def plot_spectrogram_to_numpy(spectrogram):
""" Converts spectrogram image as numpy array. """
spectrogram = spectrogram.astype(np.float32)
fig, ax = plt.subplots(figsize=(12, 3))
im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
plt.colorbar(im, ax=ax)
plt.xlabel("Frames")
plt.ylabel("Channels")
plt.tight_layout()
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
plt.close()
return data
def sequence_mask(length, max_length=None):
""" Get masks for given lengths. """
if max_length is None:
max_length = length.max()
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
return x.unsqueeze(0) < length.unsqueeze(1)
def convert_pad_shape(pad_shape):
""" Used to get arguments for F.pad. """
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape
@torch.jit.script
def ones_mask(x):
""" Creates a mask of ones in the same batch and length size as input. """
assert len(x.size()) == 3
return torch.ones((x.size(0), 1, x.size(-1)), dtype=x.dtype, device=x.device)
@torch.jit.script
def mu_transform(x):
""" Forward operation of mu-law transform for 16-bit integers. """
assert x.min() >= -1 and x.max() <= 1
return torch.sign(x) * torch.log(1 + 32768. * torch.abs(x)) / math.log(1 + 32768.)
@torch.jit.script
def mu_inverse(y):
""" Inverse operation of mu-law transform for 16-bit integers. """
assert y.min() >= -1 and y.max() <= 1
return torch.sign(y) / 32768. * ((1 + 32768.) ** torch.abs(y) - 1)
def weights_init(m, gain=None):
""" Applies orthogonal initialization to dense weights. """
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv1d):
if gain is None:
gain = (0.5 * m.weight.size(1)) ** -0.5
nn.init.orthogonal_(m.weight, gain=gain)
def print_list_values(*args, prefix="\t"):
""" Prints list of tensors, rounded to 4 decimal points. """
args = [round(arg.cpu().item(), 4) for arg in args]
print(prefix, *args)
def print_batch_stats(batch, prefix="\t"):
""" Prints the min, max, mean, and std of a batch tensor. """
batch_min = round(batch.min().cpu().item(), 4)
batch_max = round(batch.max().cpu().item(), 4)
batch_mean = round(batch.mean().cpu().item(), 4)
batch_std = round(batch.std().cpu().item(), 4)
print(prefix, batch_min, batch_max, batch_mean, batch_std)
def print_cuda_memory(gpu: int = 0):
""" Prints current memory stats of gpu. """
t = torch.cuda.get_device_properties(gpu).total_memory
c = torch.cuda.memory_cached(gpu)
a = torch.cuda.memory_allocated(gpu)
print("GPU {}".format(gpu))
print("\tTotal memory: {}".format(t))
print("\tCached memory: {}".format(c))
print("\tAllocated memory: {}".format(a))
|
{"hexsha": "db45690289a635817f3b66717290fea184907f36", "size": 5804, "ext": "py", "lang": "Python", "max_stars_repo_path": "modules/utils.py", "max_stars_repo_name": "vliu15/tts-gan", "max_stars_repo_head_hexsha": "6246c584a83f67dedaa25155c3b1491b99658319", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-02-17T23:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T08:24:58.000Z", "max_issues_repo_path": "modules/utils.py", "max_issues_repo_name": "vliu15/tts-gan", "max_issues_repo_head_hexsha": "6246c584a83f67dedaa25155c3b1491b99658319", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/utils.py", "max_forks_repo_name": "vliu15/tts-gan", "max_forks_repo_head_hexsha": "6246c584a83f67dedaa25155c3b1491b99658319", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-27T12:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T08:31:32.000Z", "avg_line_length": 33.3563218391, "max_line_length": 121, "alphanum_fraction": 0.6729841489, "include": true, "reason": "import numpy", "num_tokens": 1453}
|
import pickle
import csv
import os
import pandas as pd
import numpy as np
from util.params import Params
def filter_glove(word_indices_path, filtered_output):
print("Read files...")
iterator = pd.read_csv('data/glove.42B.300d.txt', header=None, index_col=0,
delim_whitespace=True, quoting=csv.QUOTE_NONE, dtype="str", chunksize=100000)
with open(word_indices_path, 'rb') as f:
word_indices = pickle.load(f)
print("Done.")
df = pd.DataFrame()
words = set(word_indices.keys())
total = 0
in_glove = 0
total_ubuntu = len(words)
print("Iterating through chunks...")
done = 0
# Iterate chunk by chunk
for i in iterator:
total += i.shape[0]
unique_toks = set(i.index.values)
in_glove += len(unique_toks.intersection(words))
remain = unique_toks - words
df = df.append(i.drop(remain, axis=0))
done += 1
print("Batch {} done".format(done))
print("Done.")
# Print compression percentage
filtered = df.shape[0]
print("Kept {0:.4f}% of the rows".format((filtered/total) * 100))
print("{0:.4f}% of tokens were in glove".format(in_glove/total_ubuntu))
df.to_csv(filtered_output, sep=" ", header=False, index=True, quoting=csv.QUOTE_NONE)
def main():
params = Params()
indices_path = os.path.join(params.dump_folder, "word_indices.pkl")
output_path = os.path.join(params.data_folder, "glove_filtered.txt")
filter_glove(indices_path, output_path)
if __name__ == "__main__":
main()
|
{"hexsha": "7923efd06ef4ddd4a23c3b9e18d9223fc60cce9b", "size": 1628, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/glove_filter.py", "max_stars_repo_name": "isaacsultan/comp-550", "max_stars_repo_head_hexsha": "24e7d22a6f998a94ad6eb020f1df13970da4b150", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/glove_filter.py", "max_issues_repo_name": "isaacsultan/comp-550", "max_issues_repo_head_hexsha": "24e7d22a6f998a94ad6eb020f1df13970da4b150", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/glove_filter.py", "max_forks_repo_name": "isaacsultan/comp-550", "max_forks_repo_head_hexsha": "24e7d22a6f998a94ad6eb020f1df13970da4b150", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.593220339, "max_line_length": 106, "alphanum_fraction": 0.6253071253, "include": true, "reason": "import numpy", "num_tokens": 406}
|
#define BOOST_TEST_DYN_LINK
#include <canard/net/ofp/v13/any_oxm_match_field.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <cstdint>
#include <type_traits>
#include <utility>
#include <vector>
#include <boost/asio/ip/address_v4.hpp>
#include <boost/asio/ip/address_v6.hpp>
#include <canard/mac_address.hpp>
#include <canard/net/ofp/v13/common/oxm_match_field.hpp>
#include <canard/net/ofp/v13/io/openflow.hpp>
#include "../../test_utility.hpp"
namespace of = canard::net::ofp;
namespace v13 = of::v13;
namespace match = v13::oxm_match_fields;
namespace proto = v13::protocol;
using boost::asio::ip::address_v4;
using boost::asio::ip::address_v6;
using canard::mac_address;
namespace bdata = boost::unit_test::data;
BOOST_TEST_DONT_PRINT_LOG_VALUE(v13::any_oxm_match_field)
BOOST_TEST_DONT_PRINT_LOG_VALUE(std::vector<std::uint8_t>)
namespace {
std::vector<v13::any_oxm_match_field> fields = {
v13::any_oxm_match_field{match::in_port{0x01020304}}
, v13::any_oxm_match_field{match::in_port{0x01020304, 0x0f0f0f0f}}
, v13::any_oxm_match_field{match::eth_dst{
"\x01\x02\x03\x04\x05\x06"_mac
}}
, v13::any_oxm_match_field{match::eth_dst{
"\x01\x02\x03\x04\x05\x06"_mac, "\x0f\x0f\x0f\x0f\x0f\x0f"_mac
}}
, v13::any_oxm_match_field{match::ipv4_dst{
address_v4::from_string("192.168.10.128")
}}
, v13::any_oxm_match_field{match::ipv4_dst{
address_v4::from_string("192.168.10.128"), 25
}}
, v13::any_oxm_match_field{match::ipv6_dst{
address_v6::from_string("2001:db8::9abc:8000")
}}
, v13::any_oxm_match_field{match::ipv6_dst{
address_v6::from_string("2001:db8::9abc:8000"), 113
}}
};
std::vector<std::vector<std::uint8_t>> binary_fields = {
"\x80\x00\x00\x04\x01\x02\x03\x04"_bin
, "\x80\x00\x01\x08\x01\x02\x03\x04""\x0f\x0f\x0f\x0f"_bin
, "\x80\x00\x06\x06\x01\x02\x03\x04""\x05\x06"_bin
, "\x80\x00\x07\x0c\x01\x02\x03\x04""\x05\x06\x0f\x0f\x0f\x0f\x0f\x0f"_bin
, "\x80\x00\x18\x04\xc0\xa8\x0a\x80"_bin
, "\x80\x00\x19\x08\xc0\xa8\x0a\x80""\xff\xff\xff\x80"_bin
, "\x80\x00\x36\x10\x20\x01\x0d\xb8""\x00\x00\x00\x00\x00\x00\x00\x00"
"\x9a\xbc\x80\x00"_bin
, "\x80\x00\x37\x20\x20\x01\x0d\xb8""\x00\x00\x00\x00\x00\x00\x00\x00"
"\x9a\xbc\x80\x00\xff\xff\xff\xff""\xff\xff\xff\xff\xff\xff\xff\xff"
"\xff\xff\x80\x00"_bin
};
}
BOOST_AUTO_TEST_SUITE(common_type_test)
BOOST_AUTO_TEST_SUITE(any_oxm_match_field_test)
BOOST_AUTO_TEST_SUITE(type_definition_test)
BOOST_AUTO_TEST_CASE(min_length)
{
using sut = v13::any_oxm_match_field;
using min_length
= std::integral_constant<std::uint16_t, sut::min_length()>;
BOOST_TEST(min_length::value == 4 + 1);
}
BOOST_AUTO_TEST_CASE(min_byte_length)
{
using sut = v13::any_oxm_match_field;
using min_byte_length
= std::integral_constant<std::uint16_t, sut::min_byte_length()>;
BOOST_TEST(min_byte_length::value == 4 + 1);
}
BOOST_AUTO_TEST_SUITE_END() // type_test
BOOST_AUTO_TEST_CASE(construct_from_no_mask_field_test)
{
auto const field = match::in_port{1};
auto const sut = v13::any_oxm_match_field{field};
BOOST_TEST(sut.oxm_class() == field.oxm_class());
BOOST_TEST(sut.oxm_field() == field.oxm_field());
BOOST_TEST(sut.oxm_type() == field.oxm_type());
BOOST_TEST(sut.oxm_hasmask() == field.oxm_hasmask());
BOOST_TEST(sut.oxm_length() == field.oxm_length());
BOOST_TEST(sut.length() == field.length());
BOOST_TEST(sut.byte_length() == field.byte_length());
BOOST_TEST(sut.is_wildcard() == field.is_wildcard());
BOOST_TEST(sut.is_exact() == field.is_exact());
BOOST_TEST((v13::any_cast<match::in_port>(sut) == field));
}
BOOST_AUTO_TEST_CASE(construct_from_has_mask_field_test)
{
auto const field
= match::vlan_vid{proto::OFPVID_PRESENT, proto::OFPVID_PRESENT};
auto const sut = v13::any_oxm_match_field{field};
BOOST_TEST(sut.oxm_class() == field.oxm_class());
BOOST_TEST(sut.oxm_field() == field.oxm_field());
BOOST_TEST(sut.oxm_type() == field.oxm_type());
BOOST_TEST(sut.oxm_hasmask() == field.oxm_hasmask());
BOOST_TEST(sut.oxm_length() == field.oxm_length());
BOOST_TEST(sut.length() == field.length());
BOOST_TEST(sut.byte_length() == field.byte_length());
BOOST_TEST(sut.is_wildcard() == field.is_wildcard());
BOOST_TEST(sut.is_exact() == field.is_exact());
BOOST_TEST((v13::any_cast<match::vlan_vid>(sut) == field));
}
BOOST_AUTO_TEST_CASE(assign_from_no_mask_same_type_field_test)
{
auto const field1
= match::ipv4_src{address_v4::from_string("192.168.1.0"), 24};
auto const field2
= match::ipv4_src{address_v4::from_string("172.16.0.0")};
auto sut = v13::any_oxm_match_field{field1};
sut = field2;
BOOST_TEST(sut.oxm_class() == field2.oxm_class());
BOOST_TEST(sut.oxm_field() == field2.oxm_field());
BOOST_TEST(sut.oxm_type() == field2.oxm_type());
BOOST_TEST(sut.oxm_hasmask() == field2.oxm_hasmask());
BOOST_TEST(sut.oxm_length() == field2.oxm_length());
BOOST_TEST(sut.length() == field2.length());
BOOST_TEST(sut.byte_length() == field2.byte_length());
BOOST_TEST(sut.is_wildcard() == field2.is_wildcard());
BOOST_TEST(sut.is_exact() == field2.is_exact());
BOOST_TEST((v13::any_cast<match::ipv4_src>(sut) == field2));
}
BOOST_AUTO_TEST_CASE(assign_from_has_mask_same_type_field_test)
{
auto const field1
= match::ipv4_src{address_v4::from_string("192.168.1.0"), 24};
auto const field2
= match::ipv4_src{address_v4::from_string("172.16.0.0"), 16};
auto sut = v13::any_oxm_match_field{field1};
sut = field2;
BOOST_TEST(sut.oxm_class() == field2.oxm_class());
BOOST_TEST(sut.oxm_field() == field2.oxm_field());
BOOST_TEST(sut.oxm_type() == field2.oxm_type());
BOOST_TEST(sut.oxm_hasmask() == field2.oxm_hasmask());
BOOST_TEST(sut.oxm_length() == field2.oxm_length());
BOOST_TEST(sut.length() == field2.length());
BOOST_TEST(sut.byte_length() == field2.byte_length());
BOOST_TEST(sut.is_wildcard() == field2.is_wildcard());
BOOST_TEST(sut.is_exact() == field2.is_exact());
BOOST_TEST((v13::any_cast<match::ipv4_src>(sut) == field2));
}
BOOST_AUTO_TEST_CASE(assign_from_no_mask_diff_type_field_test)
{
auto const field1
= match::ipv4_src{address_v4::from_string("192.168.1.0"), 24};
auto const field2
= match::ipv6_src{address_v6::from_string("::1")};
auto sut = v13::any_oxm_match_field{field1};
sut = field2;
BOOST_TEST(sut.oxm_class() == field2.oxm_class());
BOOST_TEST(sut.oxm_field() == field2.oxm_field());
BOOST_TEST(sut.oxm_type() == field2.oxm_type());
BOOST_TEST(sut.oxm_hasmask() == field2.oxm_hasmask());
BOOST_TEST(sut.oxm_length() == field2.oxm_length());
BOOST_TEST(sut.length() == field2.length());
BOOST_TEST(sut.byte_length() == field2.byte_length());
BOOST_TEST(sut.is_wildcard() == field2.is_wildcard());
BOOST_TEST(sut.is_exact() == field2.is_exact());
BOOST_TEST((v13::any_cast<match::ipv6_src>(sut) == field2));
}
BOOST_AUTO_TEST_CASE(assign_from_has_mask_diff_type_field_test)
{
auto const field1
= match::ipv4_src{address_v4::from_string("192.168.1.0"), 24};
auto const field2
= match::ipv6_src{address_v6::from_string("::1"), 64};
auto sut = v13::any_oxm_match_field{field1};
sut = field2;
BOOST_TEST(sut.oxm_class() == field2.oxm_class());
BOOST_TEST(sut.oxm_field() == field2.oxm_field());
BOOST_TEST(sut.oxm_type() == field2.oxm_type());
BOOST_TEST(sut.oxm_hasmask() == field2.oxm_hasmask());
BOOST_TEST(sut.oxm_length() == field2.oxm_length());
BOOST_TEST(sut.length() == field2.length());
BOOST_TEST(sut.byte_length() == field2.byte_length());
BOOST_TEST(sut.is_wildcard() == field2.is_wildcard());
BOOST_TEST(sut.is_exact() == field2.is_exact());
BOOST_TEST((v13::any_cast<match::ipv6_src>(sut) == field2));
}
BOOST_AUTO_TEST_SUITE(equality)
BOOST_AUTO_TEST_CASE(true_if_same_object)
{
auto const sut = v13::any_oxm_match_field{match::tcp_src{1}};
BOOST_TEST((sut == sut));
}
BOOST_AUTO_TEST_CASE(true_if_oxm_match_field_is_equal)
{
BOOST_TEST(
(v13::any_oxm_match_field{match::tcp_src{1}}
== v13::any_oxm_match_field{match::tcp_src{1}}));
}
BOOST_AUTO_TEST_CASE(false_if_oxm_match_field_is_not_equal)
{
BOOST_TEST(
(v13::any_oxm_match_field{match::tcp_src{1}}
!= v13::any_oxm_match_field{match::tcp_src{1, 1}}));
}
BOOST_AUTO_TEST_CASE(false_if_oxm_match_field_is_not_equal_but_equivalent)
{
BOOST_TEST(
(v13::any_oxm_match_field{match::tcp_src{1}}
!= v13::any_oxm_match_field{match::tcp_src{1, 0xffff}}));
}
BOOST_AUTO_TEST_CASE(false_if_oxm_type_is_not_equal)
{
BOOST_TEST(
(v13::any_oxm_match_field{match::tcp_src{1}}
!= v13::any_oxm_match_field{match::udp_src{1}}));
}
BOOST_AUTO_TEST_SUITE_END() // equality
BOOST_AUTO_TEST_SUITE(function_equivalent)
BOOST_AUTO_TEST_CASE(true_if_same_object)
{
auto const sut = v13::any_oxm_match_field{match::tcp_src{1}};
BOOST_TEST(equivalent(sut, sut));
}
BOOST_AUTO_TEST_CASE(true_if_oxm_match_field_is_equal)
{
BOOST_TEST(
equivalent(
v13::any_oxm_match_field{match::tcp_src{1}}
, v13::any_oxm_match_field{match::tcp_src{1}}));
}
BOOST_AUTO_TEST_CASE(false_if_oxm_match_field_is_not_equal)
{
BOOST_TEST(
!equivalent(
v13::any_oxm_match_field{match::tcp_src{1}}
, v13::any_oxm_match_field{match::tcp_src{1, 1}}));
}
BOOST_AUTO_TEST_CASE(true_if_oxm_match_field_is_not_equal_but_equivalent)
{
BOOST_TEST(
equivalent(
v13::any_oxm_match_field{match::tcp_src{1}}
, v13::any_oxm_match_field{match::tcp_src{1, 0xffff}}));
}
BOOST_AUTO_TEST_CASE(false_if_oxm_type_is_not_equal)
{
BOOST_TEST(
!equivalent(
v13::any_oxm_match_field{match::tcp_src{1}}
, v13::any_oxm_match_field{match::udp_src{1}}));
}
BOOST_AUTO_TEST_SUITE_END() // function_equivalent
BOOST_DATA_TEST_CASE(
encode_test
, bdata::make(fields) ^ bdata::make(binary_fields)
, sut, binary)
{
auto buffer = std::vector<std::uint8_t>{};
sut.encode(buffer);
BOOST_TEST(buffer.size() == sut.byte_length());
BOOST_TEST(buffer == binary, boost::test_tools::per_element{});
}
BOOST_DATA_TEST_CASE(
decode_test
, bdata::make(fields) ^ bdata::make(binary_fields)
, sut, binary)
{
auto it = binary.begin();
auto const it_end = binary.end();
auto const field = v13::any_oxm_match_field::decode(it, it_end);
BOOST_TEST((it == it_end));
BOOST_TEST((field == sut));
}
BOOST_AUTO_TEST_SUITE_END() // any_oxm_match_field_test
BOOST_AUTO_TEST_SUITE_END() // common_type_test
|
{"hexsha": "639dd5bad77b9ef869a733a6ac0491658d377abb", "size": 12048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/v13/utility/any_oxm_match_field_test.cpp", "max_stars_repo_name": "amedama41/bulb", "max_stars_repo_head_hexsha": "2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/v13/utility/any_oxm_match_field_test.cpp", "max_issues_repo_name": "amedama41/bulb", "max_issues_repo_head_hexsha": "2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2016-07-21T11:29:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:16:42.000Z", "max_forks_repo_path": "test/v13/utility/any_oxm_match_field_test.cpp", "max_forks_repo_name": "amedama41/bulb", "max_forks_repo_head_hexsha": "2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3003095975, "max_line_length": 82, "alphanum_fraction": 0.6313081009, "num_tokens": 3480}
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
""" Helper functions and class to calculate Average Precisions for 3D object detection.
"""
import os
import sys
import numpy as np
import torch
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, "utils"))
from eval_det import eval_det_cls, eval_det_multiprocessing, eval_det, eval_det_iou
from eval_det import get_iou_obb
from nms import nms_2d_faster, nms_3d_faster, nms_3d_faster_samecls
from box_util import get_3d_box
from nn_distance import nn_distance, huber_loss
from uncertainty_utils import accumulate_mc_samples, accumulate_scores
import pc_util
sys.path.append(os.path.join(ROOT_DIR, "sunrgbd"))
from sunrgbd_utils import extract_pc_in_box3d
from box_util import box3d_iou
from nn_distance import nn_distance_iou
def flip_axis_to_camera(pc):
"""Flip X-right,Y-forward,Z-up to X-right,Y-down,Z-forward
Input and output are both (N,3) array
"""
pc2 = np.copy(pc)
pc2[..., [0, 1, 2]] = pc2[..., [0, 2, 1]] # cam X,Y,Z = depth X,-Z,Y
pc2[..., 1] *= -1
return pc2
def flip_axis_to_depth(pc):
pc2 = np.copy(pc)
pc2[..., [0, 1, 2]] = pc2[..., [0, 2, 1]] # depth X,Y,Z = cam X,Z,-Y
pc2[..., 2] *= -1
return pc2
def softmax(x):
"""Numpy function for softmax"""
shape = x.shape
probs = np.exp(x - np.max(x, axis=len(shape) - 1, keepdims=True))
probs /= np.sum(probs, axis=len(shape) - 1, keepdims=True)
return probs
def end_pts_to_bb(
end_points,
config_dict,
):
pred_center = end_points["center"] # B,num_proposal,3
pred_variances = torch.exp(end_points["log_vars"]) ** 0.5
pred_heading_class = torch.argmax(
end_points["heading_scores"], -1
) # B,num_proposal
pred_heading_residual = torch.gather(
end_points["heading_residuals"], 2, pred_heading_class.unsqueeze(-1)
) # B,num_proposal,1
pred_heading_residual.squeeze_(2)
pred_size_class = torch.argmax(end_points["size_scores"], -1) # B,num_proposal
pred_size_residual = torch.gather(
end_points["size_residuals"],
2,
pred_size_class.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 1, 3),
) # B,num_proposal,1,3
pred_size_residual.squeeze_(2)
pred_sem_cls = torch.argmax(end_points["sem_cls_scores"], -1) # B,num_proposal
num_proposal = pred_center.shape[1]
# Since we operate in upright_depth coord for points, while util functions
# assume upright_camera coord.
bsize = pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_corners_3d_upright_camera[i, j] = corners_3d_upright_camera
# pred_box_sizes[i, j] = (
# np.linalg.norm(
# corners_3d_upright_camera[0] - corners_3d_upright_camera[1]
# )
# * np.linalg.norm(
# corners_3d_upright_camera[2] - corners_3d_upright_camera[1]
# )
# * np.linalg.norm(
# corners_3d_upright_camera[4] - corners_3d_upright_camera[1]
# )
# )
K = pred_center.shape[1] # K==num_proposal
nonempty_box_mask = np.ones((bsize, K))
end_points["raw_pred_boxes"] = pred_corners_3d_upright_camera
if config_dict["remove_empty_box"]:
# -------------------------------------
# Remove predicted boxes without any point within them..
batch_pc = end_points["point_clouds"].cpu().numpy()[:, :, 0:3] # B,N,3
for i in range(bsize):
pc = batch_pc[i, :, :] # (N,3)
for j in range(K):
box3d = pred_corners_3d_upright_camera[i, j, :, :] # (8,3)
if not noflip:
box3d = flip_axis_to_depth(box3d)
pc_in_box, inds = extract_pc_in_box3d(pc, box3d)
if len(pc_in_box) < 5:
nonempty_box_mask[i, j] = 0
# -------------------------------------
obj_logits = end_points["objectness_scores"].detach().cpu().numpy()
obj_prob = softmax(obj_logits)[:, :, 1] # (B,K)
if not config_dict["use_3d_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,7) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_2d_with_prob = np.zeros((K, 5))
for j in range(K):
boxes_2d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_2d_with_prob[j, 2] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_2d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_2d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_2d_with_prob[j, 4] = obj_prob[i, j]
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_2d_faster(
boxes_2d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
elif config_dict["use_3d_nms"] and (not config_dict["cls_nms"]):
# ---------- NMS input: pred_with_prob in (B,K,7) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 7))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
elif config_dict["use_3d_nms"] and config_dict["cls_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,8) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 8))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
boxes_3d_with_prob[j, 7] = pred_sem_cls[
i, j
] # only suppress if the two boxes are of the same class!!
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster_samecls(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
return pred_corners_3d_upright_camera, pred_mask, pred_center, end_points
def parse_predictions_with_log_var(end_points, config_dict):
"""Parse predictions to OBB parameters and suppress overlapping boxes
Args:
end_points: dict
{point_clouds, center, heading_scores, heading_residuals,
size_scores, size_residuals, sem_cls_scores}
config_dict: dict
{dataset_config, remove_empty_box, use_3d_nms, nms_iou,
use_old_type_nms, conf_thresh, per_class_proposal}
Returns:
batch_pred_map_cls: a list of len == batch size (BS)
[pred_list_i], i = 0, 1, ..., BS-1
where pred_list_i = [(pred_sem_cls, box_params, box_score)_j]
where j = 0, ..., num of valid detections - 1 from sample input i
"""
pred_corners_3d_upright_camera, pred_mask, pred_center, end_points = end_pts_to_bb(
end_points, config_dict
)
print(end_points["raw_pred_boxes"].shape)
pred_variances = torch.exp(end_points["log_vars"]) ** 0.5
obj_logits = end_points["objectness_scores"].detach().cpu().numpy()
obj_prob = softmax(obj_logits)[:, :, 1] #
sem_cls_probs = softmax(
end_points["sem_cls_scores"].detach().cpu().numpy()
) # B,num_proposal,10
bsize = pred_center.shape[0]
pred_sem_cls = torch.argmax(end_points["sem_cls_scores"], -1) # B,num_proposal
batch_pred_map_cls = (
[]
) # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)
# final_mask = np.zeros_like(pred_mask)
selected_raw_boxes = []
for i in range(bsize):
if config_dict["per_class_proposal"]:
cur_list = []
for ii in range(config_dict["dataset_config"].num_class):
cur_list += [
(
ii,
pred_corners_3d_upright_camera[i, j],
sem_cls_probs[i, j, ii] * obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
batch_pred_map_cls.append(cur_list)
else:
batch_pred_map_cls.append(
[
(
pred_sem_cls[i, j].item(),
pred_corners_3d_upright_camera[i, j],
obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
)
selected_raw_boxes.append(
[
(
pred_sem_cls[i, j].item(),
pred_variances[i, j],
pred_corners_3d_upright_camera[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
)
# for j in range(pred_center.shape[1]):
# if pred_mask[i,j]==1 and obj_prob[i,j]>config_dict['conf_thresh']:
# import pdb
# pdb.set_trace()
end_points["batch_pred_map_cls"] = batch_pred_map_cls
# end_points["final_masks"] = final_mask
return batch_pred_map_cls, selected_raw_boxes
def parse_predictions(end_points, config_dict, noflip=False):
"""Parse predictions to OBB parameters and suppress overlapping boxes
Args:
end_points: dict
{point_clouds, center, heading_scores, heading_residuals,
size_scores, size_residuals, sem_cls_scores}
config_dict: dict
{dataset_config, remove_empty_box, use_3d_nms, nms_iou,
use_old_type_nms, conf_thresh, per_class_proposal}
Returns:
batch_pred_map_cls: a list of len == batch size (BS)
[pred_list_i], i = 0, 1, ..., BS-1
where pred_list_i = [(pred_sem_cls, box_params, box_score)_j]
where j = 0, ..., num of valid detections - 1 from sample input i
"""
pred_center = end_points["center"] # B,num_proposal,3
pred_heading_class = torch.argmax(
end_points["heading_scores"], -1
) # B,num_proposal
pred_heading_residual = torch.gather(
end_points["heading_residuals"], 2, pred_heading_class.unsqueeze(-1)
) # B,num_proposal,1
pred_heading_residual.squeeze_(2)
pred_size_class = torch.argmax(end_points["size_scores"], -1) # B,num_proposal
pred_size_residual = torch.gather(
end_points["size_residuals"],
2,
pred_size_class.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 1, 3),
) # B,num_proposal,1,3
pred_size_residual.squeeze_(2)
pred_sem_cls = torch.argmax(end_points["sem_cls_scores"], -1) # B,num_proposal
sem_cls_probs = softmax(
end_points["sem_cls_scores"].detach().cpu().numpy()
) # B,num_proposal,10
pred_sem_cls_prob = np.max(sem_cls_probs, -1) # B,num_proposal
num_proposal = pred_center.shape[1]
# Since we operate in upright_depth coord for points, while util functions
# assume upright_camera coord.
bsize = pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
if noflip:
pred_center_upright_camera = pred_center.detach().cpu().numpy()
else:
pred_center_upright_camera = flip_axis_to_camera(
pred_center.detach().cpu().numpy()
)
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_box_sizes = np.zeros((bsize, num_proposal))
if noflip:
pred_center_upright_camera = pred_center.detach().cpu().numpy()
else:
pred_center_upright_camera = flip_axis_to_camera(
pred_center.detach().cpu().numpy()
)
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_corners_3d_upright_camera[i, j] = corners_3d_upright_camera
pred_box_sizes[i, j] = (
np.linalg.norm(
corners_3d_upright_camera[0] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[2] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[4] - corners_3d_upright_camera[1]
)
)
K = pred_center.shape[1] # K==num_proposal
nonempty_box_mask = np.ones((bsize, K))
end_points["pred_box_sizes"] = torch.Tensor(pred_box_sizes)
end_points["raw_pred_boxes"] = pred_corners_3d_upright_camera
if config_dict["remove_empty_box"]:
# -------------------------------------
# Remove predicted boxes without any point within them..
batch_pc = end_points["point_clouds"].cpu().numpy()[:, :, 0:3] # B,N,3
for i in range(bsize):
pc = batch_pc[i, :, :] # (N,3)
for j in range(K):
box3d = pred_corners_3d_upright_camera[i, j, :, :] # (8,3)
if not noflip:
box3d = flip_axis_to_depth(box3d)
pc_in_box, inds = extract_pc_in_box3d(pc, box3d)
if len(pc_in_box) < 5:
nonempty_box_mask[i, j] = 0
# -------------------------------------
obj_logits = end_points["objectness_scores"].detach().cpu().numpy()
obj_prob = softmax(obj_logits)[:, :, 1] # (B,K)
if not config_dict["use_3d_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,7) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_2d_with_prob = np.zeros((K, 5))
for j in range(K):
boxes_2d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_2d_with_prob[j, 2] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_2d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_2d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_2d_with_prob[j, 4] = obj_prob[i, j]
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_2d_faster(
boxes_2d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
elif config_dict["use_3d_nms"] and (not config_dict["cls_nms"]):
# ---------- NMS input: pred_with_prob in (B,K,7) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 7))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
elif config_dict["use_3d_nms"] and config_dict["cls_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,8) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 8))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
boxes_3d_with_prob[j, 7] = pred_sem_cls[
i, j
] # only suppress if the two boxes are of the same class!!
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster_samecls(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
batch_pred_map_cls = (
[]
) # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)
# final_mask = np.zeros_like(pred_mask)
for i in range(bsize):
if config_dict["per_class_proposal"]:
cur_list = []
for ii in range(config_dict["dataset_config"].num_class):
cur_list += [
(
ii,
pred_corners_3d_upright_camera[i, j],
sem_cls_probs[i, j, ii] * obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
batch_pred_map_cls.append(cur_list)
else:
batch_pred_map_cls.append(
[
(
pred_sem_cls[i, j].item(),
pred_corners_3d_upright_camera[i, j],
obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
)
# for j in range(pred_center.shape[1]):
# if pred_mask[i,j]==1 and obj_prob[i,j]>config_dict['conf_thresh']:
# final_mask[i,j] = 1
end_points["batch_pred_map_cls"] = batch_pred_map_cls
# end_points["final_masks"] = final_mask
return batch_pred_map_cls
def parse_predictions_with_objectness_prob(end_points, config_dict):
"""Parse predictions to OBB parameters and suppress overlapping boxes
Args:
end_points: dict
{point_clouds, center, heading_scores, heading_residuals,
size_scores, size_residuals, sem_cls_scores}
config_dict: dict
{dataset_config, remove_empty_box, use_3d_nms, nms_iou,
use_old_type_nms, conf_thresh, per_class_proposal}
Returns:
batch_pred_map_cls: a list of len == batch size (BS)
[pred_list_i], i = 0, 1, ..., BS-1
where pred_list_i = [(pred_sem_cls, box_params, box_score)_j]
where j = 0, ..., num of valid detections - 1 from sample input i
"""
pred_center = end_points["center"] # B,num_proposal,3
pred_heading_class = torch.argmax(
end_points["heading_scores"], -1
) # B,num_proposal
pred_heading_residual = torch.gather(
end_points["heading_residuals"], 2, pred_heading_class.unsqueeze(-1)
) # B,num_proposal,1
pred_heading_residual.squeeze_(2)
pred_size_class = torch.argmax(end_points["size_scores"], -1) # B,num_proposal
pred_size_residual = torch.gather(
end_points["size_residuals"],
2,
pred_size_class.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 1, 3),
) # B,num_proposal,1,3
pred_size_residual.squeeze_(2)
pred_sem_cls = torch.argmax(end_points["sem_cls_scores"], -1) # B,num_proposal
sem_cls_probs = softmax(
end_points["sem_cls_scores"].detach().cpu().numpy()
) # B,num_proposal,10
pred_sem_cls_prob = np.max(sem_cls_probs, -1) # B,num_proposal
num_proposal = pred_center.shape[1]
# Since we operate in upright_depth coord for points, while util functions
# assume upright_camera coord.
bsize = pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_box_sizes = np.zeros((bsize, num_proposal))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_corners_3d_upright_camera[i, j] = corners_3d_upright_camera
pred_box_sizes[i, j] = (
np.linalg.norm(
corners_3d_upright_camera[0] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[2] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[4] - corners_3d_upright_camera[1]
)
)
K = pred_center.shape[1] # K==num_proposal
nonempty_box_mask = np.ones((bsize, K))
end_points["pred_box_sizes"] = torch.Tensor(pred_box_sizes)
end_points["raw_pred_boxes"] = pred_corners_3d_upright_camera
if config_dict["remove_empty_box"]:
# -------------------------------------
# Remove predicted boxes without any point within them..
batch_pc = end_points["point_clouds"].cpu().numpy()[:, :, 0:3] # B,N,3
for i in range(bsize):
pc = batch_pc[i, :, :] # (N,3)
for j in range(K):
box3d = pred_corners_3d_upright_camera[i, j, :, :] # (8,3)
box3d = flip_axis_to_depth(box3d)
pc_in_box, inds = extract_pc_in_box3d(pc, box3d)
if len(pc_in_box) < 5:
nonempty_box_mask[i, j] = 0
# -------------------------------------
obj_logits = end_points["objectness_scores"].detach().cpu().numpy()
obj_prob = softmax(obj_logits)[:, :, 1] # (B,K)
# ---------- NMS output: pred_mask in (B,K) -----------
batch_pred_map_cls = (
[]
) # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)
final_mask = np.zeros_like(nonempty_box_mask)
for i in range(bsize):
for j in range(pred_center.shape[1]):
if obj_prob[i, j] > config_dict["conf_thresh"]:
final_mask[i, j] = 1
end_points["batch_pred_map_cls"] = batch_pred_map_cls
end_points["final_masks"] = final_mask
return batch_pred_map_cls
def parse_predictions_with_custom_mask(end_points, config_dict):
"""Parse predictions to OBB parameters and suppress overlapping boxes
Args:
end_points: dict
{point_clouds, center, heading_scores, heading_residuals,
size_scores, size_residuals, sem_cls_scores}
config_dict: dict
{dataset_config, remove_empty_box, use_3d_nms, nms_iou,
use_old_type_nms, conf_thresh, per_class_proposal}
Returns:
batch_pred_map_cls: a list of len == batch size (BS)
[pred_list_i], i = 0, 1, ..., BS-1
where pred_list_i = [(pred_sem_cls, box_params, box_score)_j]
where j = 0, ..., num of valid detections - 1 from sample input i
"""
pred_center = end_points["center"] # B,num_proposal,3
pred_heading_class = torch.argmax(
end_points["heading_scores"], -1
) # B,num_proposal
pred_heading_residual = torch.gather(
end_points["heading_residuals"], 2, pred_heading_class.unsqueeze(-1)
) # B,num_proposal,1
pred_heading_residual.squeeze_(2)
pred_size_class = torch.argmax(end_points["size_scores"], -1) # B,num_proposal
pred_size_residual = torch.gather(
end_points["size_residuals"],
2,
pred_size_class.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 1, 3),
) # B,num_proposal,1,3
pred_size_residual.squeeze_(2)
pred_sem_cls = torch.argmax(end_points["sem_cls_scores"], -1) # B,num_proposal
sem_cls_probs = softmax(
end_points["sem_cls_scores"].detach().cpu().numpy()
) # B,num_proposal,10
pred_sem_cls_prob = np.max(sem_cls_probs, -1) # B,num_proposal
num_proposal = pred_center.shape[1]
# Since we operate in upright_depth coord for points, while util functions
# assume upright_camera coord.
bsize = pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_box_sizes = np.zeros((bsize, num_proposal))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_corners_3d_upright_camera[i, j] = corners_3d_upright_camera
pred_box_sizes[i, j] = (
np.linalg.norm(
corners_3d_upright_camera[0] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[2] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[4] - corners_3d_upright_camera[1]
)
)
K = pred_center.shape[1] # K==num_proposal
nonempty_box_mask = np.ones((bsize, K))
end_points["pred_box_sizes"] = torch.Tensor(pred_box_sizes)
end_points["raw_pred_boxes"] = pred_corners_3d_upright_camera
# if config_dict['remove_empty_box']:
# # -------------------------------------
# # Remove predicted boxes without any point within them..
# batch_pc = end_points['point_clouds'].cpu().numpy()[:, :, 0:3] # B,N,3
# for i in range(bsize):
# pc = batch_pc[i, :, :] # (N,3)
# for j in range(K):
# box3d = pred_corners_3d_upright_camera[i, j, :, :] # (8,3)
# box3d = flip_axis_to_depth(box3d)
# pc_in_box, inds = extract_pc_in_box3d(pc, box3d)
# if len(pc_in_box) < 5:
# nonempty_box_mask[i, j] = 0
# # -------------------------------------
obj_logits = end_points["objectness_scores"].detach().cpu().numpy()
obj_prob = softmax(obj_logits)[:, :, 1] # (B,K)
custom_mask = end_points["custom_mask"]
if config_dict["use_3d_nms"] and config_dict["cls_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,8) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
nonempty_box_mask[i] = custom_mask
boxes_3d_with_prob = np.zeros((K, 8))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
boxes_3d_with_prob[j, 7] = pred_sem_cls[
i, j
] # only suppress if the two boxes are of the same class!!
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster_samecls(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# pred_mask = np.logical_and(pred_mask[0],)
batch_pred_map_cls = (
[]
) # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)
# final_mask = np.zeros_like(pred_mask)
for i in range(bsize):
batch_pred_map_cls.append(
[
(
pred_sem_cls[i, j].item(),
pred_corners_3d_upright_camera[i, j],
obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
]
)
# if pred_mask[i,j]==1 and obj_prob[i,j]>config_dict['conf_thresh']:
# final_mask[i,j] = 1
end_points["batch_pred_map_cls"] = batch_pred_map_cls
# end_points["final_masks"] = final_mask
return batch_pred_map_cls
def parse_predictions_ensemble(
mc_samples, config_dict, extension=None, expected_ent=None
):
"""Parse predictions to OBB parameters and suppress overlapping boxes
Args:
end_points: list of dicts, results of MC sampling
{point_clouds, center, heading_scores, heading_residuals,
size_scores, size_residuals, sem_cls_scores}
config_dict: dict
{dataset_config, remove_empty_box, use_3d_nms, nms_iou,
use_old_type_nms, conf_thresh, per_class_proposal}
Returns:
batch_pred_map_cls: a list of len == batch size (BS)
[pred_list_i], i = 0, 1, ..., BS-1
where pred_list_i = [(pred_sem_cls, box_params, box_score)_j]
where j = 0, ..., num of valid detections - 1 from sample input i
"""
end_points = accumulate_mc_samples(mc_samples, classification=expected_ent)
pred_center = end_points["center"] # B,num_proposal,3
pred_heading_class = torch.argmax(
end_points["heading_scores"], -1
) # B,num_proposal
pred_heading_residual = torch.gather(
end_points["heading_residuals"], 2, pred_heading_class.unsqueeze(-1)
) # B,num_proposal,1
pred_heading_residual.squeeze_(2)
pred_size_class = torch.argmax(end_points["size_scores"], -1) # B,num_proposal
pred_size_residual = torch.gather(
end_points["size_residuals"],
2,
pred_size_class.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 1, 3),
) # B,num_proposal,1,3
pred_size_residual.squeeze_(2)
pred_sem_cls = torch.argmax(end_points["sem_cls_scores"], -1) # B,num_proposal
sem_cls_probs = softmax(
end_points["sem_cls_scores"].detach().cpu().numpy()
) # B,num_proposal,10
pred_sem_cls_prob = np.max(sem_cls_probs, -1) # B,num_proposal
num_proposal = pred_center.shape[1]
# Since we operate in upright_depth coord for points, while util functions
# assume upright_camera coord.
bsize = pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_box_sizes = np.zeros((bsize, num_proposal))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_corners_3d_upright_camera[i, j] = corners_3d_upright_camera
# pred_box_sizes[i, j] = np.linalg.norm(
# corners_3d_upright_camera[0] - corners_3d_upright_camera[1]
# ) * np.linalg.norm(corners_3d_upright_camera[2] -
# corners_3d_upright_camera[1]) * np.linalg.norm(
# corners_3d_upright_camera[4] -
# corners_3d_upright_camera[1])
K = pred_center.shape[1] # K==num_proposal
nonempty_box_mask = np.ones((bsize, K))
# end_points["pred_box_sizes"] = torch.Tensor(pred_box_sizes)
# end_points["raw_pred_boxes"] = pred_corners_3d_upright_camera
if config_dict["remove_empty_box"]:
# -------------------------------------
# Remove predicted boxes without any point within them..
batch_pc = end_points["point_clouds"].cpu().numpy()[:, :, 0:3] # B,N,3
for i in range(bsize):
pc = batch_pc[i, :, :] # (N,3)
for j in range(K):
box3d = pred_corners_3d_upright_camera[i, j, :, :] # (8,3)
box3d = flip_axis_to_depth(box3d)
pc_in_box, inds = extract_pc_in_box3d(pc, box3d)
if len(pc_in_box) < 5:
nonempty_box_mask[i, j] = 0
# -------------------------------------
obj_logits = end_points["objectness_scores"].detach().cpu().numpy()
obj_prob = softmax(obj_logits)[:, :, 1] # (B,K)
cls_entropy = end_points["semantic_cls_entropy"]
obj_entropy = end_points["objectness_entropy"]
extra = np.ones_like(obj_entropy)
if extension == "objectness":
extra = 1 - obj_entropy
elif extension == "classification":
extra = 1 - cls_entropy
elif extension == "obj_and_cls":
extra = (1 - obj_entropy) * (1 - cls_entropy)
obj_prob = obj_prob * extra
# box_size_entropy = end_points["box_size_entropy"]
if not config_dict["use_3d_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,7) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_2d_with_prob = np.zeros((K, 5))
for j in range(K):
boxes_2d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_2d_with_prob[j, 2] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_2d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_2d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_2d_with_prob[j, 4] = obj_prob[i, j]
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_2d_faster(
boxes_2d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
elif config_dict["use_3d_nms"] and (not config_dict["cls_nms"]):
# ---------- NMS input: pred_with_prob in (B,K,7) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 7))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
elif config_dict["use_3d_nms"] and config_dict["cls_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,8) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 8))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
boxes_3d_with_prob[j, 7] = pred_sem_cls[
i, j
] # only suppress if the two boxes are of the same class!!
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster_samecls(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
batch_pred_map_cls = (
[]
) # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)
# final_mask = np.zeros_like(pred_mask)
# print(extension)
for i in range(bsize):
if config_dict["per_class_proposal"]:
cur_list = []
for ii in range(config_dict["dataset_config"].num_class):
cur_list += [
(
ii,
pred_corners_3d_upright_camera[i, j],
sem_cls_probs[i, j, ii] * obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
batch_pred_map_cls.append(cur_list)
# print("Accepted" ,len(cur_list))
else:
batch_pred_map_cls.append(
[
(
pred_sem_cls[i, j].item(),
pred_corners_3d_upright_camera[i, j],
obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
)
# for j in range(pred_center.shape[1]):
# if pred_mask[i,j]==1 and obj_prob[i,j]>config_dict['conf_thresh']:
# final_mask[i,j] = 1
# print("*******************")
end_points["batch_pred_map_cls"] = batch_pred_map_cls
# print(extension,sum([len(a) for a in batch_pred_map_cls]),obj_prob)
# end_points["final_masks"] = final_mask
return batch_pred_map_cls
def parse_predictions_ensemble_only_entropy(mc_samples, config_dict, extension=None):
"""Parse predictions to OBB parameters and suppress overlapping boxes
Args:
end_points: list of dicts, results of MC sampling
{point_clouds, center, heading_scores, heading_residuals,
size_scores, size_residuals, sem_cls_scores}
config_dict: dict
{dataset_config, remove_empty_box, use_3d_nms, nms_iou,
use_old_type_nms, conf_thresh, per_class_proposal}
Returns:
batch_pred_map_cls: a list of len == batch size (BS)
[pred_list_i], i = 0, 1, ..., BS-1
where pred_list_i = [(pred_sem_cls, box_params, box_score)_j]
where j = 0, ..., num of valid detections - 1 from sample input i
"""
# end_points = accumulate_mc_samples(mc_samples)
# obj_logits = end_points['objectness_scores'].detach().cpu().numpy()
# obj_prob = softmax(obj_logits)[:, :, 1] # (B,K)
# cls_entropy = end_points["semantic_cls_entropy"]
# obj_entropy = end_points["objectness_entropy"]
# extra = np.ones_like(obj_entropy)
# if extension == "objectness":
# extra = 1 - obj_entropy
# elif extension == "classification":
# extra = 1 - cls_entropy
# elif extension == "obj_and_cls":
# extra = (1 - obj_entropy )*(1 - cls_entropy)
# obj_prob =obj_prob * extra
end_points = accumulate_mc_samples(mc_samples)
pred_center = end_points["center"] # B,num_proposal,3
pred_heading_class = torch.argmax(
end_points["heading_scores"], -1
) # B,num_proposal
pred_heading_residual = torch.gather(
end_points["heading_residuals"], 2, pred_heading_class.unsqueeze(-1)
) # B,num_proposal,1
pred_heading_residual.squeeze_(2)
pred_size_class = torch.argmax(end_points["size_scores"], -1) # B,num_proposal
pred_size_residual = torch.gather(
end_points["size_residuals"],
2,
pred_size_class.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 1, 3),
) # B,num_proposal,1,3
pred_size_residual.squeeze_(2)
pred_sem_cls = torch.argmax(end_points["sem_cls_scores"], -1) # B,num_proposal
sem_cls_probs = softmax(
end_points["sem_cls_scores"].detach().cpu().numpy()
) # B,num_proposal,10
pred_sem_cls_prob = np.max(sem_cls_probs, -1) # B,num_proposal
num_proposal = pred_center.shape[1]
# Since we operate in upright_depth coord for points, while util functions
# assume upright_camera coord.
bsize = pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_center.shape[0]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
pred_box_sizes = np.zeros((bsize, num_proposal))
pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_corners_3d_upright_camera[i, j] = corners_3d_upright_camera
pred_box_sizes[i, j] = (
np.linalg.norm(
corners_3d_upright_camera[0] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[2] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[4] - corners_3d_upright_camera[1]
)
)
K = pred_center.shape[1] # K==num_proposal
nonempty_box_mask = np.ones((bsize, K))
end_points["pred_box_sizes"] = torch.Tensor(pred_box_sizes)
end_points["raw_pred_boxes"] = pred_corners_3d_upright_camera
if config_dict["remove_empty_box"]:
# -------------------------------------
# Remove predicted boxes without any point within them..
batch_pc = end_points["point_clouds"].cpu().numpy()[:, :, 0:3] # B,N,3
for i in range(bsize):
pc = batch_pc[i, :, :] # (N,3)
for j in range(K):
box3d = pred_corners_3d_upright_camera[i, j, :, :] # (8,3)
box3d = flip_axis_to_depth(box3d)
pc_in_box, inds = extract_pc_in_box3d(pc, box3d)
if len(pc_in_box) < 5:
nonempty_box_mask[i, j] = 0
# -------------------------------------
obj_logits = end_points["objectness_scores"].detach().cpu().numpy()
obj_prob = softmax(obj_logits)[:, :, 1] # (B,K)
cls_entropy = end_points["semantic_cls_entropy"]
obj_entropy = end_points["objectness_entropy"]
extra = np.ones_like(obj_entropy)
if extension == "objectness":
extra = 1 - obj_entropy
elif extension == "classification":
extra = 1 - cls_entropy
elif extension == "obj_and_cls":
extra = (1 - obj_entropy) * (1 - cls_entropy)
obj_prob = obj_prob * extra
# box_size_entropy = end_points["box_size_entropy"]
if not config_dict["use_3d_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,7) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_2d_with_prob = np.zeros((K, 5))
for j in range(K):
boxes_2d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_2d_with_prob[j, 2] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_2d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_2d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_2d_with_prob[j, 4] = obj_prob[i, j]
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_2d_faster(
boxes_2d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
elif config_dict["use_3d_nms"] and (not config_dict["cls_nms"]):
# ---------- NMS input: pred_with_prob in (B,K,7) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 7))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
elif config_dict["use_3d_nms"] and config_dict["cls_nms"]:
# ---------- NMS input: pred_with_prob in (B,K,8) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 8))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
boxes_3d_with_prob[j, 7] = pred_sem_cls[
i, j
] # only suppress if the two boxes are of the same class!!
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster_samecls(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
batch_pred_map_cls = (
[]
) # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)
# final_mask = np.zeros_like(pred_mask)
# print(extension)
print("Batch size ", bsize)
for i in range(bsize):
if bsize > 1:
batch_pred_map_cls.append(
[
(
(obj_entropy + cls_entropy)[i, j].item(),
pred_corners_3d_upright_camera[i, j],
obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
)
else:
batch_pred_map_cls.append(
[
(
(obj_entropy + cls_entropy)[j].item(),
pred_corners_3d_upright_camera[i, j],
obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
)
end_points["batch_pred_map_cls"] = batch_pred_map_cls
# end_points["final_masks"] = final_mask
# box_size_entropy = end_points["box_size_entropy"]
# ---------- NMS output: pred_mask in (B,K) -----------
obj_and_cls_uncertainties = np.array(
[np.sum([(a[0]) for a in batch_pred_map_cls[i]]) for i in range(bsize)]
) # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)
# final_mask = np.zeros_like(pred_mask)
# print(extension)
# end_points["final_masks"] = final_mask
return obj_and_cls_uncertainties
def make_box_and_unrotate(end_points, config_dict, rot):
pred_center = end_points["center"].cpu().numpy() # B,num_proposal,3
pred_heading_class = torch.argmax(
end_points["heading_scores"], -1
) # B,num_proposal
pred_heading_residual = torch.gather(
end_points["heading_residuals"], 2, pred_heading_class.unsqueeze(-1)
) # B,num_proposal,1
pred_heading_residual.squeeze_(2)
pred_size_class = torch.argmax(end_points["size_scores"], -1) # B,num_proposal
pred_size_residual = torch.gather(
end_points["size_residuals"],
2,
pred_size_class.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 1, 3),
) # B,num_proposal,1,3
pred_size_residual.squeeze_(2)
bsize = pred_center.shape[0]
num_proposal = pred_center.shape[1]
pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))
box_sizes = np.zeros((bsize, num_proposal))
# print("*********************")
# print(pred_center[0,0])
# print("*********************")
# pred_center_upright_camera = flip_axis_to_camera(pred_center)
pred_center_upright_camera = pred_center
for i in range(bsize):
for j in range(num_proposal):
heading_angle = config_dict["dataset_config"].class2angle(
pred_heading_class[i, j].detach().cpu().numpy(),
pred_heading_residual[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(pred_size_class[i, j].detach().cpu().numpy()),
pred_size_residual[i, j].detach().cpu().numpy(),
)
box_sizes[i, j] = box_size[0] * box_size[1] * box_size[2]
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, pred_center_upright_camera[i, j, :]
)
pred_corners_3d_upright_camera[i, j] = corners_3d_upright_camera
for i in range(bsize):
for j in range(num_proposal):
# rot = np.eye(3)
pred_center[i, j], _ = pc_util.rotate_point_cloud(
pred_center_upright_camera[i, j], rotation_matrix=rot.T
) # do rotation to all points here
pred_center[i, j] = flip_axis_to_camera(pred_center[i, j])
pred_corners_3d_upright_camera[i, j], _ = pc_util.rotate_point_cloud(
pred_corners_3d_upright_camera[i, j], rotation_matrix=rot.T
)
pred_corners_3d_upright_camera[i, j] = flip_axis_to_camera(
pred_corners_3d_upright_camera[i, j]
)
# boxes = pc_util.point_cloud_to_bbox(pred_corners_3d_upright_camera[i, j])
# if (rot == np.eye(3)).sum() != 0:
# print("Box center ",boxes[:3])
# print("Pred center ",pred_center[i, j])
return pred_corners_3d_upright_camera, pred_center, box_sizes
# return pred_center
def parse_predictions_augmented(
mc_samples, config_dict, extension=None, rotations=None
):
"""Parse predictions to OBB parameters and suppress overlapping boxes
Args:
end_points: list of dicts, results of MC sampling
{point_clouds, center, heading_scores, heading_residuals,
size_scores, size_residuals, sem_cls_scores}
config_dict: dict
{dataset_config, remove_empty_box, use_3d_nms, nms_iou,
use_old_type_nms, conf_thresh, per_class_proposal}
Returns:
batch_pred_map_cls: a list of len == batch size (BS)
[pred_list_i], i = 0, 1, ..., BS-1
where pred_list_i = [(pred_sem_cls, box_params, box_score)_j]
where j = 0, ..., num of valid detections - 1 from sample input i
"""
# inds = np.array([0,1,3,2])
rotations = np.array(rotations)
pred_corners_3d_upright_camera, pred_center, box_sizes = map(
list,
zip(
*[
make_box_and_unrotate(mc_samples[idx], config_dict, rot)
for idx, rot in enumerate(rotations)
]
),
)
# K = pred_corners_3d_upright_camera[0].shape[1] # K==num_proposal
# bsize = 1# pred_corners_3d_upright_camera[0].shape[0]
# numbox = 10
# for idx,pred_boxes in enumerate(pred_corners_3d_upright_camera):
# boxes_to_be_dumped = []
# for b in range(bsize):
# for j in range(numbox):
# pcd_to_box = pc_util.point_cloud_to_bbox(pred_boxes[b,j])
# boxes_to_be_dumped.append(pcd_to_box)
# boxes_to_be_dumped = np.array(boxes_to_be_dumped)
# pc_util.write_bbox(boxes_to_be_dumped,str(idx) + ".ply")
end_points = accumulate_scores(mc_samples)
# end_points = mc_samples[3]
pred_corners_3d_upright_camera = (
torch.Tensor(pred_corners_3d_upright_camera).mean(dim=0).cpu().numpy()
)
pred_center = torch.Tensor(pred_center).mean(dim=0).cpu().numpy()
pred_sem_cls = (
torch.argmax(end_points["sem_cls_scores"], -1).cpu().numpy()
) # B,num_proposal
sem_cls_probs = softmax(
end_points["sem_cls_scores"].detach().cpu().numpy()
) # B,num_proposal,10
pred_sem_cls_prob = np.max(sem_cls_probs, -1) # B,num_proposal
# Since we operate in upright_depth coord for points, while util functions
# assume upright_camera coord.
K = pred_corners_3d_upright_camera.shape[1] # K==num_proposal
bsize = pred_corners_3d_upright_camera.shape[0]
nonempty_box_mask = np.ones((bsize, K))
end_points["raw_pred_boxes"] = pred_corners_3d_upright_camera
if config_dict["remove_empty_box"]:
# -------------------------------------
# Remove predicted boxes without any point within them..
batch_pc = end_points["point_clouds"].cpu().numpy()[:, :, 0:3] # B,N,3
for i in range(bsize):
pc = batch_pc[i, :, :] # (N,3)
for j in range(K):
box3d = pred_corners_3d_upright_camera[i, j, :, :] # (8,3)
box3d = flip_axis_to_depth(box3d)
pc_in_box, inds = extract_pc_in_box3d(pc, box3d)
if len(pc_in_box) < 5:
nonempty_box_mask[i, j] = 0
# -------------------------------------
obj_logits = end_points["objectness_scores"].detach().cpu().numpy()
obj_prob = softmax(obj_logits)[:, :, 1] # (B,K)
# cls_entropy = end_points["semantic_cls_entropy"]
# obj_entropy = end_points["objectness_entropy"]
# extra = np.ones_like(obj_entropy)
# if extension == "objectness":
# extra = 1 - obj_entropy
# elif extension == "classification":
# extra = 1 - cls_entropy
# elif extension == "obj_and_cls":
# extra = (1 - obj_entropy )*(1 - cls_entropy)
# obj_prob =obj_prob * extra
# ---------- NMS output: pred_mask in (B,K) -----------
# ---------- NMS input: pred_with_prob in (B,K,8) -----------
pred_mask = np.zeros((bsize, K))
for i in range(bsize):
boxes_3d_with_prob = np.zeros((K, 8))
for j in range(K):
boxes_3d_with_prob[j, 0] = np.min(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 1] = np.min(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 2] = np.min(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 3] = np.max(
pred_corners_3d_upright_camera[i, j, :, 0]
)
boxes_3d_with_prob[j, 4] = np.max(
pred_corners_3d_upright_camera[i, j, :, 1]
)
boxes_3d_with_prob[j, 5] = np.max(
pred_corners_3d_upright_camera[i, j, :, 2]
)
boxes_3d_with_prob[j, 6] = obj_prob[i, j]
boxes_3d_with_prob[j, 7] = pred_sem_cls[
i, j
] # only suppress if the two boxes are of the same class!!
nonempty_box_inds = np.where(nonempty_box_mask[i, :] == 1)[0]
pick = nms_3d_faster_samecls(
boxes_3d_with_prob[nonempty_box_mask[i, :] == 1, :],
config_dict["nms_iou"],
config_dict["use_old_type_nms"],
)
assert len(pick) > 0
pred_mask[i, nonempty_box_inds[pick]] = 1
end_points["pred_mask"] = pred_mask
# ---------- NMS output: pred_mask in (B,K) -----------
batch_pred_map_cls = (
[]
) # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)
# final_mask = np.zeros_like(pred_mask)
# print(extension)
for i in range(bsize):
if config_dict["per_class_proposal"]:
cur_list = []
for ii in range(config_dict["dataset_config"].num_class):
cur_list += [
(
ii,
pred_corners_3d_upright_camera[i, j],
sem_cls_probs[i, j, ii] * obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
batch_pred_map_cls.append(cur_list)
# print("Accepted" ,len(cur_list))
else:
batch_pred_map_cls.append(
[
(
pred_sem_cls[i, j].item(),
pred_corners_3d_upright_camera[i, j],
obj_prob[i, j],
)
for j in range(pred_center.shape[1])
if pred_mask[i, j] == 1
and obj_prob[i, j] > config_dict["conf_thresh"]
]
)
# for j in range(pred_center.shape[1]):
# if pred_mask[i,j]==1 and obj_prob[i,j]>config_dict['conf_thresh']:
# final_mask[i,j] = 1
# print("*******************")
end_points["batch_pred_map_cls"] = batch_pred_map_cls
# end_points["final_masks"] = final_mask
return batch_pred_map_cls
def parse_groundtruths(end_points, config_dict):
"""Parse groundtruth labels to OBB parameters.
Args:
end_points: dict
{center_label, heading_class_label, heading_residual_label,
size_class_label, size_residual_label, sem_cls_label,
box_label_mask}
config_dict: dict
{dataset_config}
Returns:
batch_gt_map_cls: a list of len == batch_size (BS)
[gt_list_i], i = 0, 1, ..., BS-1
where gt_list_i = [(gt_sem_cls, gt_box_params)_j]
where j = 0, ..., num of objects - 1 at sample input i
"""
center_label = end_points["center_label"]
heading_class_label = end_points["heading_class_label"]
heading_residual_label = end_points["heading_residual_label"]
size_class_label = end_points["size_class_label"]
size_residual_label = end_points["size_residual_label"]
box_label_mask = end_points["box_label_mask"]
sem_cls_label = end_points["sem_cls_label"]
bsize = center_label.shape[0]
K2 = center_label.shape[1] # K2==MAX_NUM_OBJ
gt_corners_3d_upright_camera = np.zeros((bsize, K2, 8, 3))
gt_box_sizes = np.zeros((bsize, K2))
gt_center_upright_camera = flip_axis_to_camera(
center_label[:, :, 0:3].detach().cpu().numpy()
)
for i in range(bsize):
for j in range(K2):
if box_label_mask[i, j] == 0:
continue
heading_angle = config_dict["dataset_config"].class2angle(
heading_class_label[i, j].detach().cpu().numpy(),
heading_residual_label[i, j].detach().cpu().numpy(),
)
box_size = config_dict["dataset_config"].class2size(
int(size_class_label[i, j].detach().cpu().numpy()),
size_residual_label[i, j].detach().cpu().numpy(),
)
corners_3d_upright_camera = get_3d_box(
box_size, heading_angle, gt_center_upright_camera[i, j, :]
)
gt_corners_3d_upright_camera[i, j] = corners_3d_upright_camera
gt_box_sizes[i, j] = (
np.linalg.norm(
corners_3d_upright_camera[0] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[2] - corners_3d_upright_camera[1]
)
* np.linalg.norm(
corners_3d_upright_camera[4] - corners_3d_upright_camera[1]
)
)
# gt_box_sizes[i] = gt_box_sizes[i,:np.argmin(gt_box_sizes[i])]
end_points["gt_box_sizes"] = gt_box_sizes
end_points["raw_gt_boxes"] = gt_corners_3d_upright_camera
batch_gt_map_cls = []
for i in range(bsize):
batch_gt_map_cls.append(
[
(sem_cls_label[i, j].item(), gt_corners_3d_upright_camera[i, j])
for j in range(gt_corners_3d_upright_camera.shape[1])
if box_label_mask[i, j] == 1
]
)
end_points["batch_gt_map_cls"] = batch_gt_map_cls
return batch_gt_map_cls
def find_matching_boxes_center(proposals):
"""
Args
boxes1,boxes2: list of tuples -> (class,box corners, objectness_score)
TODO:extend to batch
"""
B = len(proposals[0])
# B=1
FAR_THRESHOLD = 0.6
NEAR_THRESHOLD = 0.3
ACCEPTANCE_THRESHOLD = 4
print("ACCEPTANCE THRESHOLD ", ACCEPTANCE_THRESHOLD)
final_proposals = []
for b in range(B):
centers1 = torch.from_numpy(
np.array([pc_util.point_cloud_to_bbox(bx[1])[:3] for bx in proposals[0][b]])
).unsqueeze(0)
centers2 = torch.from_numpy(
np.array([pc_util.point_cloud_to_bbox(bx[1])[:3] for bx in proposals[1][b]])
).unsqueeze(0)
centers3 = torch.from_numpy(
np.array([pc_util.point_cloud_to_bbox(bx[1])[:3] for bx in proposals[2][b]])
).unsqueeze(0)
centers4 = torch.from_numpy(
np.array([pc_util.point_cloud_to_bbox(bx[1])[:3] for bx in proposals[3][b]])
).unsqueeze(0)
K = centers1.shape[1]
K2 = centers1.shape[0]
dist12, _, _, _ = nn_distance(centers1, centers2) # dist1: BxK, dist2: BxK2
dist13, _, _, _ = nn_distance(centers1, centers3) # dist1: BxK, dist2: BxK2
dist14, _, _, _ = nn_distance(centers1, centers4) # dist1: BxK, dist2: BxK2
# Generate objectness label and mask
# objectness_label: 1 if pred object center is within NEAR_THRESHOLD of any GT object
# objectness_mask: 0 if pred object center is in gray zone (DONOTCARE), 1 otherwise
euclidean_dist12 = torch.sqrt(dist12 + 1e-6)
objectness_label12 = torch.zeros((1, K), dtype=torch.long).cuda()
objectness_mask12 = torch.zeros((1, K)).cuda()
objectness_label12[euclidean_dist12 < NEAR_THRESHOLD] = 1
objectness_mask12[euclidean_dist12 < NEAR_THRESHOLD] = 1
objectness_mask12[euclidean_dist12 > FAR_THRESHOLD] = 1
euclidean_dist13 = torch.sqrt(dist13 + 1e-6)
objectness_label13 = torch.zeros((1, K), dtype=torch.long).cuda()
objectness_mask13 = torch.zeros((1, K)).cuda()
objectness_label13[euclidean_dist13 < NEAR_THRESHOLD] = 1
objectness_mask13[euclidean_dist13 < NEAR_THRESHOLD] = 1
objectness_mask13[euclidean_dist13 > FAR_THRESHOLD] = 1
euclidean_dist14 = torch.sqrt(dist14 + 1e-6)
objectness_label14 = torch.zeros((1, K), dtype=torch.long).cuda()
objectness_mask14 = torch.zeros((1, K)).cuda()
objectness_label14[euclidean_dist14 < NEAR_THRESHOLD] = 1
objectness_mask14[euclidean_dist14 < NEAR_THRESHOLD] = 1
objectness_mask14[euclidean_dist14 > FAR_THRESHOLD] = 1
initial_mask = torch.ones((1, K)).cuda()
aggregated_mask = (
objectness_mask13 + objectness_mask12 + objectness_mask14 + initial_mask
) >= ACCEPTANCE_THRESHOLD
_, aggregated_mask = np.nonzero(aggregated_mask.cpu().numpy())
filtered_preds = np.array(proposals[0][b], dtype=np.object)[aggregated_mask]
final_proposals.append(filtered_preds)
return final_proposals
def find_matching_boxes_iou(proposals):
"""
Args
boxes1,boxes2: list of tuples -> (class,box corners, objectness_score)
TODO:extend to batch
"""
B = len(proposals[0])
FAR_THRESHOLD = 0.6
NEAR_THRESHOLD = 0.3
ACCEPTANCE_THRESHOLD = 4
IOU_THRESH = 0.25
print("ACCEPTANCE THRESHOLD ", ACCEPTANCE_THRESHOLD)
final_proposals = []
proposals_inv = []
for b in range(B):
boxes1 = np.array([bx[1] for bx in proposals[0][b]])
boxes2 = np.array([bx[1] for bx in proposals[1][b]])
boxes3 = np.array([bx[1] for bx in proposals[2][b]])
boxes4 = np.array([bx[1] for bx in proposals[3][b]])
# K = boxes1.shape[1]
K = boxes1.shape[0]
iou_scores12 = nn_distance_iou(boxes1, boxes2) # dist1: BxK, dist2: BxK2
iou_scores13 = nn_distance_iou(boxes1, boxes3) # dist1: BxK, dist2: BxK2
iou_scores14 = nn_distance_iou(boxes1, boxes4) # dist1: BxK, dist2: BxK2
iou_mask12 = np.array(iou_scores12 >= IOU_THRESH, dtype=np.int)
iou_mask13 = np.array(iou_scores13 >= IOU_THRESH, dtype=np.int)
iou_mask14 = np.array(iou_scores14 >= IOU_THRESH, dtype=np.int)
initial_mask = np.ones((1, K))
bool_aggregated_mask = (
iou_mask12 + iou_mask13 + iou_mask14 + initial_mask
) >= ACCEPTANCE_THRESHOLD
_, aggregated_mask = np.nonzero(bool_aggregated_mask)
_, aggregated_mask_inv = np.nonzero(np.logical_not(bool_aggregated_mask))
# take ones from original
filtered_preds = np.array(proposals[0][b], dtype=np.object)[aggregated_mask]
eliminated_preds = np.array(proposals[0][b], dtype=np.object)[
aggregated_mask_inv
]
final_proposals.append(filtered_preds)
proposals_inv.append(eliminated_preds)
return final_proposals, proposals_inv
def dump_boxes(boxes, prefix=None):
batch_size = len(boxes)
for b in range(batch_size):
boxes_to_be_dumped = []
num_boxes = len(boxes[b])
for j in range(num_boxes):
boxes_to_be_dumped.append(
pc_util.point_cloud_to_bbox(flip_axis_to_depth(boxes[b][j][1]))
)
boxes_to_be_dumped = np.array(boxes_to_be_dumped)
if prefix is None:
name = "scene"
else:
name = prefix
dump = np.zeros((len(boxes_to_be_dumped), 7))
dump[:, :6] = boxes_to_be_dumped
pc_util.write_oriented_bbox(dump, name + str(b) + ".ply")
def aggregate_predictions(batch_pred_map_cls_multiple, rotations, dump_dir=None):
batch_size = len(batch_pred_map_cls_multiple[0])
# batch_size = 1
angles = [0, 90, 180, 270]
for b in range(batch_size):
all_boxes = []
for idx, rot in enumerate(rotations):
all_boxes.append([])
pred_boxes_in_scene = [
box_tuple[1] for box_tuple in batch_pred_map_cls_multiple[idx][b]
]
stacked_boxes = flip_axis_to_depth(np.vstack(pred_boxes_in_scene))
# stacked_boxes = np.vstack(pred_boxes_in_scene)
rotated_boxes, _ = pc_util.rotate_point_cloud(
stacked_boxes, rotation_matrix=rot.T
) # unrotate stacked_boxes
rotated_boxes = rotated_boxes.reshape((len(pred_boxes_in_scene), 8, 3))
boxes_to_be_dumped = []
for i, bx in enumerate(rotated_boxes):
elem = batch_pred_map_cls_multiple[idx][b][i]
bx = flip_axis_to_camera(bx)
batch_pred_map_cls_multiple[idx][b][i] = (elem[0], bx, elem[2])
# final_proposals = find_matching_boxes_center(batch_pred_map_cls_multiple[:])
final_proposals, proposals_inv = find_matching_boxes_iou(
batch_pred_map_cls_multiple[:]
)
if dump_dir is not None:
dump_boxes(final_proposals, dump_dir + "/Selected")
dump_boxes(proposals_inv, dump_dir + "/Discarded")
dump_boxes(batch_pred_map_cls_multiple[0], dump_dir + "/0_")
dump_boxes(batch_pred_map_cls_multiple[1], dump_dir + "/90_")
dump_boxes(batch_pred_map_cls_multiple[2], dump_dir + "/180_")
dump_boxes(batch_pred_map_cls_multiple[3], dump_dir + "/270_")
# final_proposals = batch_pred_map_cls_multiple[0]
# boxes_to_be_dumped = np.array(all_boxes[idx])
# pc_util.write_bbox(boxes_to_be_dumped,str(idx) + ".ply")
return final_proposals
class APCalculator(object):
"""Calculating Average Precision"""
def __init__(self, ap_iou_thresh=0.25, class2type_map=None):
"""
Args:
ap_iou_thresh: float between 0 and 1.0
IoU threshold to judge whether a prediction is positive.
class2type_map: [optional] dict {class_int:class_name}
"""
self.ap_iou_thresh = ap_iou_thresh
self.class2type_map = class2type_map
self.reset()
def step(self, batch_pred_map_cls, batch_gt_map_cls):
"""Accumulate one batch of prediction and groundtruth.
Args:
batch_pred_map_cls: a list of lists [[(pred_cls, pred_box_params, score),...],...]
batch_gt_map_cls: a list of lists [[(gt_cls, gt_box_params),...],...]
should have the same length with batch_pred_map_cls (batch_size)
"""
bsize = len(batch_pred_map_cls)
assert bsize == len(batch_gt_map_cls)
for i in range(bsize):
self.gt_map_cls[self.scan_cnt] = batch_gt_map_cls[i]
self.pred_map_cls[self.scan_cnt] = batch_pred_map_cls[i]
self.scan_cnt += 1
def compute_metrics(self):
"""Use accumulated predictions and groundtruths to compute Average Precision."""
rec, prec, ap = eval_det_multiprocessing(
self.pred_map_cls,
self.gt_map_cls,
ovthresh=self.ap_iou_thresh,
get_iou_func=get_iou_obb,
)
# rec, prec, ap,ious = eval_det_iou(self.pred_map_cls,
# self.gt_map_cls,
# ovthresh=self.ap_iou_thresh,
# get_iou_func=get_iou_obb)
ret_dict = {}
for key in sorted(ap.keys()):
clsname = self.class2type_map[key] if self.class2type_map else str(key)
ret_dict["%s Average Precision" % (clsname)] = ap[key]
ret_dict["mAP"] = np.mean(list(ap.values()))
rec_list = []
for key in sorted(ap.keys()):
clsname = self.class2type_map[key] if self.class2type_map else str(key)
try:
ret_dict["%s Recall" % (clsname)] = rec[key][-1]
rec_list.append(rec[key][-1])
except:
ret_dict["%s Recall" % (clsname)] = 0
rec_list.append(0)
# for key in sorted(ious.keys()):
# clsname = self.class2type_map[key] if self.class2type_map else str(
# key)
# ret_dict['%s Average IOU' % (clsname)] = np.array(ious[key]).mean()
ret_dict["AR"] = np.mean(rec_list)
return ret_dict
# In [1]
def reset(self):
self.gt_map_cls = {} # {scan_id: [(classname, bbox)]}
self.pred_map_cls = {} # {scan_id: [(classname, bbox, score)]}
self.scan_cnt = 0
|
{"hexsha": "ed7f23edf3b3a82ebe0c9431c383a5b9c9c7b1f7", "size": 87853, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/ap_helper.py", "max_stars_repo_name": "keremyldrr/votenet_with_mc_dropout", "max_stars_repo_head_hexsha": "9c26774287be01d5b19dc2740259c7606c17ca7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/ap_helper.py", "max_issues_repo_name": "keremyldrr/votenet_with_mc_dropout", "max_issues_repo_head_hexsha": "9c26774287be01d5b19dc2740259c7606c17ca7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/ap_helper.py", "max_forks_repo_name": "keremyldrr/votenet_with_mc_dropout", "max_forks_repo_head_hexsha": "9c26774287be01d5b19dc2740259c7606c17ca7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.171007371, "max_line_length": 125, "alphanum_fraction": 0.5661844217, "include": true, "reason": "import numpy", "num_tokens": 22503}
|
#include <boost/mpl/aux_/preprocessed/plain/set.hpp>
|
{"hexsha": "7be6c8e24021a563246f51efc7dfc255eb95cde6", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_mpl_aux__preprocessed_plain_set.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_mpl_aux__preprocessed_plain_set.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_mpl_aux__preprocessed_plain_set.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.7924528302, "num_tokens": 14}
|
import pandas as pd
from sklearn.model_selection import ParameterGrid
import numpy as np
from enum import Enum
class DataEnum(Enum):
FISHING = 'FISHING'
HURRICANES = 'HURRICANES'
GEOLIFE = 'GEOLIFE'
class AlgoEnum(Enum):
CBSMoT = 'CB-SMoT'
DBSMoT = 'DB-SMoT'
def get_data(d, algorithm):
ret = None
if d == DataEnum.FISHING:
data = get_fv()
label = 'label'
elif d == DataEnum.HURRICANES:
data = get_hurr()
label = 'label'
elif d == DataEnum.GEOLIFE:
data = get_geolife()
label = 'transportation_mode'
if algorithm == AlgoEnum.CBSMoT:
parms = cbsmot_parms(d)
elif algorithm == AlgoEnum.DBSMoT:
parms = dbsmot_parms(d)
ret = {'data': data,
'parameter_grid': parms,
'file_name': str(algorithm.value) + "_" + str(d.value) + "_results.csv",
'label':label}
return ret
def get_fv():
dfs = []
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d1.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d2.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d3.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d4.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d5.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d6.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d7.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d8.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d9.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Fishing Vessels/fv_d10.txt', sep=';')))
return dfs
def get_hurr():
dfs = []
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d1.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d2.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d3.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d4.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d5.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d6.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d7.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d8.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d9.txt', sep=';')))
dfs.append(split_df(pd.read_csv('databases/Hurricanes/h_d10.txt', sep=';')))
return dfs
def get_geolife():
dfs = []
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_1.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_2.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_3.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_4.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_5.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_6.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_7.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_8.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_9.csv', sep=',')])
dfs.append([pd.read_csv('databases/geolife/geolife_w_features_10.csv', sep=',')])
return dfs
def cbsmot_parms(d):
ret = None
if d == DataEnum.HURRICANES:
ret = ParameterGrid({'area': list(np.arange(0.1, 1, 0.1)),
'min_time': np.array(range(0, 24, 6))*3600,
'time_tolerance': [0],
'merge_tolerance': [0]})
elif d == DataEnum.FISHING:
ret = ParameterGrid({'area': list(np.arange(0.1, 1, 0.1)),
'min_time': np.array(range(2, 13, 2))*3600,
'time_tolerance': [0],
'merge_tolerance': [0]})
elif d == DataEnum.GEOLIFE:
ret = ParameterGrid({'area': np.arange(0.1, 0.9, 0.05),
'min_time': np.arange(0.1, 3, 0.1)*3600,
'time_tolerance': [0],
'merge_tolerance':[0]})
return ret
def dbsmot_parms(d):
ret = None
if d == DataEnum.HURRICANES:
ret = ParameterGrid({})
elif d == DataEnum.FISHING:
ret = ParameterGrid({})
elif d == DataEnum.GEOLIFE:
ret = ParameterGrid({})
return ret
def split_df(df,label='tid'):
real_dfs = []
df.set_index(keys=['tid'],drop=False,inplace=True)
tids = df['tid'].unique().tolist()
for tid in tids:
real_dfs.append(df.loc[df.tid ==tid])
return real_dfs
|
{"hexsha": "252ae012977eccfce8714c5d8bdcb6142e1086a8", "size": 4925, "ext": "py", "lang": "Python", "max_stars_repo_path": "databases/load_datasets.py", "max_stars_repo_name": "JRose6/TrajLib", "max_stars_repo_head_hexsha": "2a5749bf6e9517835801926d6a5e92564ef2c7f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "databases/load_datasets.py", "max_issues_repo_name": "JRose6/TrajLib", "max_issues_repo_head_hexsha": "2a5749bf6e9517835801926d6a5e92564ef2c7f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "databases/load_datasets.py", "max_forks_repo_name": "JRose6/TrajLib", "max_forks_repo_head_hexsha": "2a5749bf6e9517835801926d6a5e92564ef2c7f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.368852459, "max_line_length": 86, "alphanum_fraction": 0.6223350254, "include": true, "reason": "import numpy", "num_tokens": 1409}
|
"""
==============================
Interpolating the Sine function.
* Interpolating the sine function using Lagrangian and Newton's methods.
==============================
"""
import matplotlib.pyplot as plt
import numpy as np
from projects.nnum.interpolation.lagrangian import LagrangianInterpolator
print(__doc__)
interpolation_degree = 3
n_samples = 5
n_predictions = 400
n_interval = 4
f = np.log
x = lambda i: i # np.pi / 4 * i
X_train = np.zeros((n_samples, 1))
for i in range(n_samples):
X_train[i, 0] = x(i)
y_train = np.array([f(X_train[i]) for i in range(n_samples)])
X_test = x(np.random.rand(n_predictions, 1) * n_interval)
i = LagrangianInterpolator(interpolation_degree,
fitting_profile='local').fit(X_train, y_train)
y_pred = np.array([i.predict(t) for t in X_test])
figure = plt.figure(figsize=(16, 9))
plt.scatter(X_test.flatten(), y_pred, color='crimson')
plt.scatter(X_train.flatten(), y_train, color='orange', s=200)
plt.axis('tight')
plt.show()
|
{"hexsha": "f8d5d475d5df8dd08712c8a23de615097f2c9a9c", "size": 1008, "ext": "py", "lang": "Python", "max_stars_repo_path": "projects/nnum/examples/interpolation/sine.py", "max_stars_repo_name": "lucasdavid/numerical-analysis", "max_stars_repo_head_hexsha": "461d156769dae65471665ca72ff41e6cd3c8e944", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/nnum/examples/interpolation/sine.py", "max_issues_repo_name": "lucasdavid/numerical-analysis", "max_issues_repo_head_hexsha": "461d156769dae65471665ca72ff41e6cd3c8e944", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/nnum/examples/interpolation/sine.py", "max_forks_repo_name": "lucasdavid/numerical-analysis", "max_forks_repo_head_hexsha": "461d156769dae65471665ca72ff41e6cd3c8e944", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2, "max_line_length": 73, "alphanum_fraction": 0.6686507937, "include": true, "reason": "import numpy", "num_tokens": 262}
|
#
# BSD 3-Clause License
#
# Copyright (c) 2017-2018, plures
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import gumath as gm
import gumath.functions as fn
import gumath.examples as ex
from xnd import xnd
from ndtypes import ndt
from extending import Graph, bfloat16
import sys, time
import math
import unittest
import argparse
try:
import numpy as np
except ImportError:
np = None
TEST_CASES = [
([float(i)/100.0 for i in range(2000)], "2000 * float64", "float64"),
([[float(i)/100.0 for i in range(1000)], [float(i+1) for i in range(1000)]],
"2 * 1000 * float64", "float64"),
(1000 * [[float(i+1) for i in range(2)]], "1000 * 2 * float64", "float64"),
([float(i)/10.0 for i in range(2000)], "2000 * float32", "float32"),
([[float(i)/10.0 for i in range(1000)], [float(i+1) for i in range(1000)]],
"2 * 1000 * float32", "float32"),
(1000 * [[float(i+1) for i in range(2)]], "1000 * 2 * float32", "float32"),
]
class TestCall(unittest.TestCase):
def test_sin_scalar(self):
x1 = xnd(1.2, type="float64")
y1 = fn.sin(x1)
x2 = xnd(1.23e1, type="float32")
y2 = fn.sin(x2)
if np is not None:
a1 = np.array(1.2, dtype="float64")
b1 = np.sin(a1)
a2 = np.array(1.23e1, dtype="float32")
b2 = np.sin(a2)
np.testing.assert_equal(y1.value, b1)
np.testing.assert_equal(y2.value, b2)
def test_sin(self):
for lst, t, dtype in TEST_CASES:
x = xnd(lst, type=t)
y = fn.sin(x)
if np is not None:
a = np.array(lst, dtype=dtype)
b = np.sin(a)
np.testing.assert_equal(y, b)
def test_sin_strided(self):
for lst, t, dtype in TEST_CASES:
x = xnd(lst, type=t)
if x.type.ndim < 2:
continue
y = x[::-2, ::-2]
z = fn.sin(y)
if np is not None:
a = np.array(lst, dtype=dtype)
b = a[::-2, ::-2]
c = np.sin(b)
np.testing.assert_equal(z, c)
def test_copy(self):
for lst, t, dtype in TEST_CASES:
x = xnd(lst, type=t)
y = fn.copy(x)
if np is not None:
a = np.array(lst, dtype=dtype)
b = np.copy(a)
np.testing.assert_equal(y, b)
def test_copy_strided(self):
for lst, t, dtype in TEST_CASES:
x = xnd(lst, type=t)
if x.type.ndim < 2:
continue
y = x[::-2, ::-2]
z = fn.copy(y)
if np is not None:
a = np.array(lst, dtype=dtype)
b = a[::-2, ::-2]
c = np.copy(b)
np.testing.assert_equal(y, b)
@unittest.skipIf(sys.platform == "win32", "missing C99 complex support")
def test_quaternion(self):
lst = [[[1+2j, 4+3j],
[-4+3j, 1-2j]],
[[4+2j, 1+10j],
[-1+10j, 4-2j]],
[[-4+2j, 3+10j],
[-3+10j, -4-2j]]]
x = xnd(lst, type="3 * quaternion64")
y = ex.multiply(x, x)
if np is not None:
a = np.array(lst, dtype="complex64")
b = np.einsum("ijk,ikl->ijl", a, a)
np.testing.assert_equal(y, b)
x = xnd(lst, type="3 * quaternion128")
y = ex.multiply(x, x)
if np is not None:
a = np.array(lst, dtype="complex128")
b = np.einsum("ijk,ikl->ijl", a, a)
np.testing.assert_equal(y, b)
x = xnd("xyz")
self.assertRaises(TypeError, ex.multiply, x, x)
@unittest.skipIf(sys.platform == "win32", "missing C99 complex support")
def test_quaternion_error(self):
lst = [[[1+2j, 4+3j],
[-4+3j, 1-2j]],
[[4+2j, 1+10j],
[-1+10j, 4-2j]],
[[-4+2j, 3+10j],
[-3+10j, -4-2j]]]
x = xnd(lst, type="3 * Foo(2 * 2 * complex64)")
self.assertRaises(TypeError, ex.multiply, x, x)
def test_void(self):
x = ex.randint()
self.assertEqual(x.type, ndt("int32"))
def test_multiple_return(self):
x, y = ex.randtuple()
self.assertEqual(x.type, ndt("int32"))
self.assertEqual(y.type, ndt("int32"))
x, y = ex.divmod10(xnd(233))
self.assertEqual(x.value, 23)
self.assertEqual(y.value, 3)
class TestMissingValues(unittest.TestCase):
def test_missing_values(self):
x = [{'index': 0, 'name': 'brazil', 'value': 10},
{'index': 1, 'name': 'france', 'value': None},
{'index': 1, 'name': 'russia', 'value': 2}]
y = [{'index': 0, 'name': 'iceland', 'value': 5},
{'index': 1, 'name': 'norway', 'value': None},
{'index': 1, 'name': 'italy', 'value': None}]
z = xnd([x, y], type="2 * 3 * {index: int64, name: string, value: ?int64}")
ans = ex.count_valid_missing(z)
self.assertEqual(ans.value, [{'valid': 2, 'missing': 1}, {'valid': 1, 'missing': 2}])
class TestRaggedArrays(unittest.TestCase):
def test_sin(self):
s = math.sin
lst = [[[1.0],
[2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0],
[8.0, 9.0],
[10.0, 11.0, 12.0]]]
ans = [[[s(1.0)],
[s(2.0), s(3.0)],
[s(4.0), s(5.0), s(6.0)]],
[[s(7.0)],
[s(8.0), s(9.0)],
[s(10.0), s(11.0), s(12.0)]]]
x = xnd(lst)
y = fn.sin(x)
self.assertEqual(y.value, ans)
class TestGraphs(unittest.TestCase):
def test_shortest_path(self):
graphs = [[[(1, 1.2), (2, 4.4)],
[(2, 2.2)],
[(1, 2.3)]],
[[(1, 1.2), (2, 4.4)],
[(2, 2.2)],
[(1, 2.3)],
[(2, 1.1)]]]
ans = [[[[0], [0, 1], [0, 1, 2]], # graph1, start 0
[[], [1], [1, 2]], # graph1, start 1
[[], [2, 1], [2]]], # graph1, start 2
[[[0], [0, 1], [0, 1, 2], []], # graph2, start 0
[[], [1], [1, 2], []], # graph2, start 1
[[], [2, 1], [2], []], # graph2, start 2
[[], [3, 2, 1], [3, 2], [3]]]] # graph2, start 3
for i, lst in enumerate(graphs):
N = len(lst)
graph = Graph(lst)
for start in range(N):
node = xnd(start, type="node")
x = graph.shortest_paths(node)
self.assertEqual(x.value, ans[i][start])
def test_constraint(self):
lst = [[(0, 1.2)],
[(2, 2.2), (1, 0.1)]]
self.assertRaises(ValueError, Graph, lst)
@unittest.skipIf(sys.platform == "win32", "unresolved external symbols")
class TestBFloat16(unittest.TestCase):
def test_init(self):
lst = [1.2e10, 2.1121, -3e20]
ans = [11945377792.0, 2.109375, -2.997595911977802e+20]
x = bfloat16(lst)
self.assertEqual(x.value, ans)
class TestPdist(unittest.TestCase):
def test_exceptions(self):
x = xnd([], dtype="float64")
self.assertRaises(TypeError, ex.euclidian_pdist, x)
x = xnd([[]], dtype="float64")
self.assertRaises(TypeError, ex.euclidian_pdist, x)
x = xnd([[], []], dtype="float64")
self.assertRaises(TypeError, ex.euclidian_pdist, x)
x = xnd([[1], [1]], dtype="int64")
self.assertRaises(TypeError, ex.euclidian_pdist, x)
def test_pdist(self):
x = xnd([[1]], dtype="float64")
y = ex.euclidian_pdist(x)
self.assertEqual(y.value, [])
x = xnd([[1, 2, 3]], dtype="float64")
y = ex.euclidian_pdist(x)
self.assertEqual(y.value, [])
x = xnd([[-1.2200, -100.5000, 20.1250, 30.1230],
[ 2.2200, 2.2720, -122.8400, 122.3330],
[ 2.1000, -25.0000, 100.2000, -99.5000]], dtype="float64")
y = ex.euclidian_pdist(x)
self.assertEqual(y.value, [198.78529349275314, 170.0746899276903, 315.75385646576035])
@unittest.skipIf(gm.xndvectorize is None, "test requires numpy and numba")
class TestNumba(unittest.TestCase):
def test_numba(self):
@gm.xndvectorize("... * N * M * float64, ... * M * P * float64 -> ... * N * P * float64")
def matmul(x, y, res):
col = np.arange(y.shape[0])
for j in range(y.shape[1]):
for k in range(y.shape[0]):
col[k] = y[k, j]
for i in range(x.shape[0]):
s = 0
for k in range(x.shape[1]):
s += x[i, k] * col[k]
res[i, j] = s
a = np.arange(50000.0).reshape(1000, 5, 10)
b = np.arange(70000.0).reshape(1000, 10, 7)
c = np.einsum("ijk,ikl->ijl", a, b)
x = xnd(a.tolist(), type="1000 * 5 * 10 * float64")
y = xnd(b.tolist(), type="1000 * 10 * 7 * float64")
z = matmul(x, y)
np.testing.assert_equal(z, c)
def test_numba_add_scalar(self):
import numba as nb
@nb.guvectorize(["void(int64[:], int64, int64[:])"], '(n),()->(n)')
def g(x, y, res):
for i in range(x.shape[0]):
res[i] = x[i] + y
a = np.arange(5000).reshape(100, 5, 10)
b = np.arange(500).reshape(100, 5)
c = g(a, b)
x = xnd(a.tolist(), type="100 * 5 * 10 * int64")
y = xnd(b.tolist(), type="100 * 5 * int64")
z = ex.add_scalar(x, y)
np.testing.assert_equal(z, c)
a = np.arange(500)
b = np.array(100)
c = g(a, b)
x = xnd(a.tolist(), type="500 * int64")
y = xnd(b.tolist(), type="int64")
z = ex.add_scalar(x, y)
np.testing.assert_equal(z, c)
ALL_TESTS = [
TestCall,
TestRaggedArrays,
TestMissingValues,
TestGraphs,
TestBFloat16,
TestPdist,
TestNumba,
]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--failfast", action="store_true",
help="stop the test run on first error")
args = parser.parse_args()
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for case in ALL_TESTS:
s = loader.loadTestsFromTestCase(case)
suite.addTest(s)
runner = unittest.TextTestRunner(failfast=args.failfast, verbosity=2)
result = runner.run(suite)
ret = not result.wasSuccessful()
sys.exit(ret)
|
{"hexsha": "b9aa097e0bfa99f98a44a3249fdaa3f8b09c80e9", "size": 12166, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/test_gumath.py", "max_stars_repo_name": "mrkn/gumath", "max_stars_repo_head_hexsha": "5725aa2bda2d9a9581e7adedda00e9f1dcaa881a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/test_gumath.py", "max_issues_repo_name": "mrkn/gumath", "max_issues_repo_head_hexsha": "5725aa2bda2d9a9581e7adedda00e9f1dcaa881a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/test_gumath.py", "max_forks_repo_name": "mrkn/gumath", "max_forks_repo_head_hexsha": "5725aa2bda2d9a9581e7adedda00e9f1dcaa881a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9655172414, "max_line_length": 97, "alphanum_fraction": 0.5205490712, "include": true, "reason": "import numpy,import numba", "num_tokens": 3555}
|
###############################################################################
#
# File: evaluate_unflow.py
#
# Primitive hacking of things from eval_gui.py in the UnFlow package to
# allow running evaluations
#
# History:
# 07-30-20 - Levi Burner - Created file
#
###############################################################################
import os
import sys
import numpy as np
import tensorflow as tf
from motion_illusions.UnFlow.src.e2eflow.core.flow_util import flow_to_color, flow_error_avg, outlier_pct
from motion_illusions.UnFlow.src.e2eflow.core.flow_util import flow_error_image
from motion_illusions.UnFlow.src.e2eflow.util import config_dict
from motion_illusions.UnFlow.src.e2eflow.core.image_warp import image_warp
from motion_illusions.UnFlow.src.e2eflow.core.unsupervised import unsupervised_loss
from motion_illusions.UnFlow.src.e2eflow.core.input import resize_input, resize_output_crop, resize_output, resize_output_flow
from motion_illusions.UnFlow.src.e2eflow.core.train import restore_networks
from motion_illusions.UnFlow.src.e2eflow.ops import forward_warp
from motion_illusions.UnFlow.src.e2eflow.core.losses import DISOCC_THRESH, occlusion
from motion_illusions.UnFlow.src.e2eflow.util import convert_input_strings
def flow_to_int16(flow):
_, h, w, _ = tf.unstack(tf.shape(flow))
u, v = tf.unstack(flow, num=2, axis=3)
r = tf.cast(tf.maximum(0.0, tf.minimum(u * 64.0 + 32768.0, 65535.0)), tf.uint16)
g = tf.cast(tf.maximum(0.0, tf.minimum(v * 64.0 + 32768.0, 65535.0)), tf.uint16)
b = tf.ones([1, h, w], tf.uint16)
return tf.stack([r, g, b], axis=3)
def evaluate_experiment(config_file_path, name, input_fn, data_input, num_frames_to_evaluate):
normalize_fn = data_input._normalize_image
resized_h = data_input.dims[0]
resized_w = data_input.dims[1]
current_config = config_dict(config_file_path)
exp_dir = os.path.join(current_config['dirs']['log'], 'ex', name)
config_path = os.path.join(exp_dir, 'config.ini')
if not os.path.isfile(config_path):
config_path = '../config.ini'
if not os.path.isdir(exp_dir) or not tf.train.get_checkpoint_state(exp_dir):
exp_dir = os.path.join(current_config['dirs']['checkpoints'], name)
config = config_dict(config_path)
params = config['train']
convert_input_strings(params, config_dict(config_file_path)['dirs'])
dataset_params_name = 'train_' + 'kitti' # TODO HARD CODED DOESN'T MAKE SENSE
if dataset_params_name in config:
params.update(config[dataset_params_name])
ckpt = tf.train.get_checkpoint_state(exp_dir)
if not ckpt:
raise RuntimeError("Error: experiment must contain a checkpoint")
ckpt_path = exp_dir + "/" + os.path.basename(ckpt.model_checkpoint_path)
with tf.Graph().as_default(): #, tf.device('gpu:' + FLAGS.gpu):
inputs = input_fn()
im1, im2, input_shape = inputs[:3]
truth = inputs[3:]
height, width, _ = tf.unstack(tf.squeeze(input_shape), num=3, axis=0)
im1 = resize_input(im1, height, width, resized_h, resized_w)
im2 = resize_input(im2, height, width, resized_h, resized_w) # TODO adapt train.py
_, flow, flow_bw = unsupervised_loss(
(im1, im2),
normalization=data_input.get_normalization(),
params=params, augment=False, return_flow=True)
im1 = resize_output(im1, height, width, 3)
im2 = resize_output(im2, height, width, 3)
flow = resize_output_flow(flow, height, width, 2)
flow_bw = resize_output_flow(flow_bw, height, width, 2)
flow_fw_int16 = flow_to_int16(flow)
flow_bw_int16 = flow_to_int16(flow_bw)
im1_pred = image_warp(im2, flow)
im1_diff = tf.abs(im1 - im1_pred)
#im2_diff = tf.abs(im1 - im2)
#flow_bw_warped = image_warp(flow_bw, flow)
if len(truth) == 4:
flow_occ, mask_occ, flow_noc, mask_noc = truth
flow_occ = resize_output_crop(flow_occ, height, width, 2)
flow_noc = resize_output_crop(flow_noc, height, width, 2)
mask_occ = resize_output_crop(mask_occ, height, width, 1)
mask_noc = resize_output_crop(mask_noc, height, width, 1)
#div = divergence(flow_occ)
#div_bw = divergence(flow_bw)
occ_pred = 1 - (1 - occlusion(flow, flow_bw)[0])
def_pred = 1 - (1 - occlusion(flow, flow_bw)[1])
disocc_pred = forward_warp(flow_bw) < DISOCC_THRESH
disocc_fw_pred = forward_warp(flow) < DISOCC_THRESH
image_slots = [((im1 * 0.5 + im2 * 0.5) / 255, 'overlay'),
(im1_diff / 255, 'brightness error'),
#(im1 / 255, 'first image', 1, 0),
#(im2 / 255, 'second image', 1, 0),
#(im2_diff / 255, '|first - second|', 1, 2),
(flow_to_color(flow), 'flow'),
#(flow_to_color(flow_bw), 'flow bw prediction'),
#(tf.image.rgb_to_grayscale(im1_diff) > 20, 'diff'),
#(occ_pred, 'occ'),
#(def_pred, 'disocc'),
#(disocc_pred, 'reverse disocc'),
#(disocc_fw_pred, 'forward disocc prediction'),
#(div, 'div'),
#(div < -2, 'neg div'),
#(div > 5, 'pos div'),
#(flow_to_color(flow_occ, mask_occ), 'flow truth'),
(flow_error_image(flow, flow_occ, mask_occ, mask_noc),
'flow error') # (blue: correct, red: wrong, dark: occluded)
]
# list of (scalar_op, title)
scalar_slots = [(flow_error_avg(flow_noc, flow, mask_noc), 'EPE_noc'),
(flow_error_avg(flow_occ, flow, mask_occ), 'EPE_all'),
(outlier_pct(flow_noc, flow, mask_noc), 'outliers_noc'),
(outlier_pct(flow_occ, flow, mask_occ), 'outliers_all')]
elif len(truth) == 2:
flow_gt, mask = truth
flow_gt = resize_output_crop(flow_gt, height, width, 2)
mask = resize_output_crop(mask, height, width, 1)
image_slots = [((im1 * 0.5 + im2 * 0.5) / 255, 'overlay'),
(im1_diff / 255, 'brightness error'),
(flow_to_color(flow), 'flow'),
(flow_to_color(flow_gt, mask), 'gt'),
]
# list of (scalar_op, title)
scalar_slots = [(flow_error_avg(flow_gt, flow, mask), 'EPE_all')]
else:
image_slots = [(im1 / 255, 'first image'),
#(im1_pred / 255, 'warped second image', 0, 1),
(im1_diff / 255, 'warp error'),
#(im2 / 255, 'second image', 1, 0),
#(im2_diff / 255, '|first - second|', 1, 2),
(flow_to_color(flow), 'flow prediction')]
scalar_slots = []
num_ims = len(image_slots)
image_ops = [t[0] for t in image_slots]
scalar_ops = [t[0] for t in scalar_slots]
image_names = [t[1] for t in image_slots]
scalar_names = [t[1] for t in scalar_slots]
all_ops = image_ops + scalar_ops
image_lists = []
averages = np.zeros(len(scalar_ops))
sess_config = tf.ConfigProto(allow_soft_placement=True)
exp_out_dir = os.path.join('../out', name)
# TODO
# if FLAGS.output_visual or FLAGS.output_benchmark:
# if os.path.isdir(exp_out_dir):
# shutil.rmtree(exp_out_dir)
# os.makedirs(exp_out_dir)
# shutil.copyfile(config_path, os.path.join(exp_out_dir, 'config.ini'))
with tf.Session(config=sess_config) as sess:
saver = tf.train.Saver(tf.global_variables())
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
restore_networks(sess, params, ckpt, ckpt_path)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess,
coord=coord)
# TODO adjust for batch_size > 1 (also need to change image_lists appending)
# TODO
max_iter = num_frames_to_evaluate #FLAGS.num if FLAGS.num > 0 else None
try:
num_iters = 0
while not coord.should_stop() and (max_iter is None or num_iters != max_iter):
all_results = sess.run([flow, flow_bw, flow_fw_int16, flow_bw_int16] + all_ops)
flow_fw_res, flow_bw_res, flow_fw_int16_res, flow_bw_int16_res = all_results[:4]
all_results = all_results[4:]
image_results = all_results[:num_ims]
scalar_results = all_results[num_ims:]
iterstr = str(num_iters).zfill(6)
# if FLAGS.output_visual:
# path_col = os.path.join(exp_out_dir, iterstr + '_flow.png')
# path_overlay = os.path.join(exp_out_dir, iterstr + '_img.png')
# path_error = os.path.join(exp_out_dir, iterstr + '_err.png')
# write_rgb_png(image_results[0] * 255, path_overlay)
# write_rgb_png(image_results[1] * 255, path_col)
# write_rgb_png(image_results[2] * 255, path_error)
# if FLAGS.output_benchmark:
# path_fw = os.path.join(exp_out_dir, iterstr)
# if FLAGS.output_png:
# write_rgb_png(flow_fw_int16_res, path_fw + '_10.png', bitdepth=16)
# else:
# write_flo(flow_fw_res, path_fw + '_10.flo')
# if FLAGS.output_backward:
# path_fw = os.path.join(exp_out_dir, iterstr + '_01.png')
# write_rgb_png(flow_bw_int16_res, path_bw, bitdepth=16)
#if num_iters < FLAGS.num_vis:
image_lists.append(image_results)
averages += scalar_results
if num_iters > 0:
sys.stdout.write('\r')
num_iters += 1
sys.stdout.write("-- evaluating '{}': {}/{}"
.format(name, num_iters, max_iter))
sys.stdout.flush()
print()
except tf.errors.OutOfRangeError:
pass
averages /= num_iters
coord.request_stop()
coord.join(threads)
for t, avg in zip(scalar_slots, averages):
_, scalar_name = t
print("({}) {} = {}".format(name, scalar_name, avg))
return image_lists, image_names
|
{"hexsha": "82ff054a644d1a336e0e63b5c35185f35c034fb4", "size": 11056, "ext": "py", "lang": "Python", "max_stars_repo_path": "motion_illusions/evaluate_unflow.py", "max_stars_repo_name": "ysnan/motion_illusions", "max_stars_repo_head_hexsha": "1b7e8901cbd228a6bdfc8762f6d4756f62361b1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-10T13:21:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-10T13:21:38.000Z", "max_issues_repo_path": "motion_illusions/evaluate_unflow.py", "max_issues_repo_name": "ysnan/motion_illusions", "max_issues_repo_head_hexsha": "1b7e8901cbd228a6bdfc8762f6d4756f62361b1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "motion_illusions/evaluate_unflow.py", "max_forks_repo_name": "ysnan/motion_illusions", "max_forks_repo_head_hexsha": "1b7e8901cbd228a6bdfc8762f6d4756f62361b1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6551724138, "max_line_length": 126, "alphanum_fraction": 0.5630426918, "include": true, "reason": "import numpy", "num_tokens": 2627}
|
using LinQuadOptInterface
using .ClpCInterface
const LQOI = LinQuadOptInterface
const MOI = LQOI.MOI
const SUPPORTED_OBJECTIVES = [
LQOI.Linear,
LQOI.SinVar
]
const SUPPORTED_CONSTRAINTS = [
(LQOI.Linear, LQOI.EQ),
(LQOI.Linear, LQOI.LE),
(LQOI.Linear, LQOI.GE),
(LQOI.SinVar, LQOI.EQ),
(LQOI.SinVar, LQOI.LE),
(LQOI.SinVar, LQOI.GE),
(LQOI.SinVar, LQOI.IV),
(LQOI.VecVar, MOI.Nonnegatives),
(LQOI.VecVar, MOI.Nonpositives),
(LQOI.VecVar, MOI.Zeros),
(LQOI.VecLin, MOI.Nonnegatives),
(LQOI.VecLin, MOI.Nonpositives),
(LQOI.VecLin, MOI.Zeros)
]
mutable struct Optimizer <: LQOI.LinQuadOptimizer
LQOI.@LinQuadOptimizerBase
params::Dict{Symbol,Any}
Optimizer(::Nothing) = new()
end
### Options
# map option name to C function
const optionmap = Dict(
:PrimalTolerance => set_primal_tolerance,
:DualTolerance => set_dual_tolerance,
:DualObjectiveLimit => set_dual_objective_limit,
:MaximumIterations => set_maximum_iterations,
:MaximumSeconds => set_maximum_seconds,
:LogLevel => set_log_level,
:Scaling => scaling,
:Perturbation => set_perturbation,
)
# These options are set by using the ClpSolve object
const solveoptionmap = Dict(
:PresolveType => set_presolve_type,
:SolveType => set_solve_type,
:InfeasibleReturn => set_infeasible_return,
)
function Optimizer(;kwargs...)
optimizer = Optimizer(nothing)
optimizer.params = Dict{String,Any}()
MOI.empty!(optimizer)
for (name,value) in kwargs
optimizer.params[Symbol(name)] = value
end
return optimizer
end
LQOI.LinearQuadraticModel(::Type{Optimizer},env) = ClpModel()
LQOI.supported_constraints(optimizer::Optimizer) = SUPPORTED_CONSTRAINTS
LQOI.supported_objectives(optimizer::Optimizer) = SUPPORTED_OBJECTIVES
"""
replace_inf(x::Real)
Return `Inf` if `x>1e20`, `-Inf` if `x<-1e20`, and `x` otherwise.
"""
function replace_inf(x::Real)
if x > 1e20
return Inf
elseif x < -1e20
return -Inf
else
return x
end
end
function LQOI.change_variable_bounds!(instance::Optimizer, cols::Vector{Int},
values::Vector{Float64}, senses::Vector)
upperbounds = get_col_upper(instance.inner)
lowerbounds = get_col_lower(instance.inner)
for (col, value, sense) in zip(cols, values, senses)
if sense == Cchar('U')
upperbounds[col] = value
elseif sense == Cchar('L')
lowerbounds[col] = value
else
error("sense is Cchar('$(Char(sense))'), but only Cchar('U') " *
"Cchar('L') are supported.")
end
end
chg_column_upper(instance.inner, upperbounds)
chg_column_lower(instance.inner, lowerbounds)
end
function LQOI.get_variable_lowerbound(instance::Optimizer, col::Int)
lower = get_col_lower(instance.inner)
return replace_inf(lower[col])
end
function LQOI.get_variable_upperbound(instance::Optimizer, col::Int)
upper = get_col_upper(instance.inner)
return replace_inf(upper[col])
end
function LQOI.get_number_linear_constraints(instance::Optimizer)
return get_num_rows(instance.inner)
end
"""
append_row(instance::Optimizer, row::Int, lower::Float64, upper::Float64,
rows::Vector{Int}, cols::Vector{Int}, coefs::Vector{Float64})
Given a sparse matrix in the triplet-form `(rows, cols, coefs)`, add row `row`
with upper bound `upper` and lower bound `lower` to the instance `instance`.
"""
function append_row(instance::Optimizer, row::Int, lower::Float64,
upper::Float64, rows::Vector{Int}, cols::Vector{Int},
coefs::Vector{Float64})
indices = if row == length(rows)
rows[row]:length(cols)
else
rows[row]:(rows[row+1]-1)
end
add_row(instance.inner, Cint(length(indices)), Cint.(cols[indices] .- 1),
coefs[indices], lower, upper)
end
function LQOI.add_linear_constraints!(instance::Optimizer, A::LQOI.CSRMatrix{Float64},
senses::Vector{Cchar}, right_hand_sides::Vector{Float64})
rows = A.row_pointers
cols = A.columns
coefs = A.coefficients
for (row, (rhs, sense)) in enumerate(zip(right_hand_sides, senses))
if rhs > 1e20
error("rhs must always be less than 1e20")
elseif rhs < -1e20
error("rhs must always be greater than -1e20")
end
lower = -Inf
upper = Inf
if sense == Cchar('L')
upper = rhs
elseif sense == Cchar('G')
lower = rhs
elseif sense == Cchar('E')
upper = lower = rhs
else
error("sense must be Cchar(x) where x is in ['L','G',E']")
end
append_row(instance, row, lower, upper, rows, cols, coefs)
end
end
function LQOI.add_ranged_constraints!(instance::Clp.Optimizer,
A::LinQuadOptInterface.CSRMatrix{Float64},
lb::Vector{Float64}, ub::Vector{Float64})
rows = A.row_pointers
cols = A.columns
coefs = A.coefficients
for row in 1:length(lb)
append_row(instance, row, lb[row], ub[row], rows, cols, coefs)
end
end
function LQOI.get_rhs(instance::Optimizer, row::Int)
lower_bounds = get_row_lower(instance.inner)
upper_bounds = get_row_upper(instance.inner)
lower_bound = replace_inf(lower_bounds[row])
upper_bound = replace_inf(upper_bounds[row])
if lower_bound > -Inf
return lower_bound
elseif upper_bound < Inf
return upper_bound
else
error("Either row_lower or row_upper must be of abs less than 1e20")
end
end
function LQOI.get_linear_constraint(instance::Optimizer, row::Int)::Tuple{Vector{Int}, Vector{Float64}}
A = get_constraint_matrix(instance.inner)
A_row = A[row,:]
return Array{Int}(A_row.nzind), A_row.nzval
end
function LQOI.change_objective_coefficient!(instance::Optimizer, col, coef)
objcoefs = get_obj_coefficients(instance.inner)
objcoefs[col] = coef
chg_obj_coefficients(instance.inner, objcoefs)
end
function LQOI.change_rhs_coefficient!(instance::Optimizer, row, coef)
lower_bounds = get_row_lower(instance.inner)
upper_bounds = get_row_upper(instance.inner)
lower_bound = replace_inf(lower_bounds[row])
upper_bound = replace_inf(upper_bounds[row])
if lower_bound > -Inf
lower_bounds[row] = coef
chg_row_lower(instance.inner, lower_bounds)
elseif upper_bound < Inf
upper_bounds[row] = coef
chg_row_upper(instance.inner, upper_bounds)
else
error("Either row_lower or row_upper must be of abs less than 1e20")
end
end
function LQOI.delete_linear_constraints!(instance::Optimizer, start_row::Int, end_row::Int)
delete_rows(instance.inner, [Cint(i-1) for i in start_row:end_row])
end
function LQOI.change_linear_constraint_sense!(instance::Optimizer, rows::Vector{Int}, senses::Vector{Cchar})
lower = replace_inf.(get_row_lower(instance.inner))
upper = replace_inf.(get_row_upper(instance.inner))
for (sense, row) in zip(senses, rows)
lb = lower[row]
ub = upper[row]
if lb > -Inf
rhs = lb
elseif ub < Inf
rhs = ub
else
error("Either row_lower or row_upper must be of abs less than 1e20")
end
if sense == Cchar('G')
lower[row] = rhs
upper[row] = Inf
elseif sense == Cchar('L')
lower[row] = -Inf
upper[row] = rhs
elseif sense == Cchar('E')
lower[row] = rhs
upper[row] = rhs
end
end
chg_row_upper(instance.inner, upper)
chg_row_lower(instance.inner, lower)
end
function LQOI.set_linear_objective!(instance::Optimizer, cols::Vector{Int}, coefs::Vector{Float64})
objective_coefficients = zeros(Float64, get_num_cols(instance.inner))
for (col, coef) in zip(cols, coefs)
objective_coefficients[col] += coef
end
chg_obj_coefficients(instance.inner, objective_coefficients)
end
function LQOI.change_objective_sense!(instance::Optimizer, sense::Symbol)
if sense == :min
set_obj_sense(instance.inner, 1.0)
elseif sense == :max
set_obj_sense(instance.inner, -1.0)
else
error("sense must be either :min or :max")
end
end
function LQOI.get_linear_objective!(instance::Optimizer, x::Vector{Float64})
copyto!(x, get_obj_coefficients(instance.inner))
end
function LQOI.solve_linear_problem!(instance::Optimizer)
solveroptions = ClpSolve()
model = instance.inner
for (name, value) in instance.params
if haskey(optionmap, name)
optionmap[name](model, value)
elseif haskey(solveoptionmap, name)
solveoptionmap[name](solveroptions,value)
else
error("Unrecognized option: $name")
end
end
initial_solve_with_options(instance.inner, solveroptions)
end
function LQOI.get_variable_primal_solution!(instance::Optimizer, x::Vector{Float64})
copyto!(x, primal_column_solution(instance.inner))
end
function LQOI.get_linear_primal_solution!(instance::Optimizer, x::Vector{Float64})
copyto!(x, primal_row_solution(instance.inner))
end
function LQOI.get_variable_dual_solution!(instance::Optimizer, x::Vector{Float64})
copyto!(x, dual_column_solution(instance.inner))
end
function LQOI.get_linear_dual_solution!(instance::Optimizer, x::Vector{Float64})
copyto!(x, dual_row_solution(instance.inner))
end
function LQOI.get_objective_value(instance::Optimizer)
return objective_value(instance.inner)
end
function LQOI.get_farkas_dual!(instance::Optimizer, result::Vector{Float64})
copyto!(result, infeasibility_ray(instance.inner))
Compat.rmul!(result, -1.0)
end
function LQOI.get_unbounded_ray!(instance::Optimizer, result::Vector{Float64})
copyto!(result, unbounded_ray(instance.inner))
end
function LQOI.get_termination_status(instance::Optimizer)
status = ClpCInterface.status(instance.inner)
if status == 0
return MOI.Success
elseif status == 1
if is_proven_primal_infeasible(instance.inner)
return MOI.Success
else
return MOI.InfeasibleNoResult
end
elseif status == 2
if is_proven_dual_infeasible(instance.inner)
return MOI.Success
else
return MOI.UnboundedNoResult
end
elseif status == 3
return MOI.OtherLimit
elseif status == 4
return MOI.OtherError
else
error("status returned was $(status), but it must be in [0,1,2,3,4]")
end
end
function LQOI.get_primal_status(instance::Optimizer)
if is_proven_dual_infeasible(instance.inner)
return MOI.InfeasibilityCertificate
elseif primal_feasible(instance.inner)
return MOI.FeasiblePoint
else
return MOI.UnknownResultStatus
end
end
function LQOI.get_dual_status(instance::Optimizer)
if is_proven_primal_infeasible(instance.inner)
return MOI.InfeasibilityCertificate
elseif dual_feasible(instance.inner)
return MOI.FeasiblePoint
else
return MOI.UnknownResultStatus
end
end
function LQOI.get_number_variables(instance::Optimizer)
return get_num_cols(instance.inner)
end
function LQOI.add_variables!(instance::Optimizer, number_of_variables::Int)
for i in 1:number_of_variables
add_column(instance.inner, Cint(0), Int32[], Float64[], -Inf, Inf, 0.0)
end
end
function LQOI.delete_variables!(instance::Optimizer, start_col::Int, end_col::Int)
delete_columns(instance.inner, [Cint(i-1) for i in start_col:end_col])
end
|
{"hexsha": "d18b8e07a037234219ec415ec304aa617b755e1a", "size": 11601, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MOIWrapper.jl", "max_stars_repo_name": "ianfiske/Clp.jl", "max_stars_repo_head_hexsha": "a767718f97be041c9d339c652c41fb98d9a2f2db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MOIWrapper.jl", "max_issues_repo_name": "ianfiske/Clp.jl", "max_issues_repo_head_hexsha": "a767718f97be041c9d339c652c41fb98d9a2f2db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MOIWrapper.jl", "max_forks_repo_name": "ianfiske/Clp.jl", "max_forks_repo_head_hexsha": "a767718f97be041c9d339c652c41fb98d9a2f2db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.269541779, "max_line_length": 108, "alphanum_fraction": 0.6813205758, "num_tokens": 3054}
|
"""
transforms的实例。
【输入】*inputs必须是张量或者是图像的路径(包含文件名)!!
如果输入是多张图像路径/多个张量,将他们依次传入driver_transform()即可,注意最后一个参数是mode...
【输出】是最终喂给模型的张量(numpy.ndarray/torch.tensor/tensorflow.placeholder等等)。
【注意】在做分割的时候,彩色图像和分割图像需要做同步的处理!
特别是在含有随机变换的时候!!
对图像的预处理本质上是做矩阵运算。
如:pytorch的torchvision.transforms本质上是通过numpy/Pillow进行变换的。
下面就以比较复杂的处理DRIVER数据集为例,演示具体的数据预处理:
"""
import torch
import random
import numbers
import numpy as np
import torchvision.transforms as T
from torchvision.transforms import functional as F
class Crop(object):
def __init__(self, parameters=None):
self.params = parameters
def __call__(self, img):
i, j, h, w = self.params
return F.crop(img, i, j, h, w)
class MyRandomCrop(object):
def __init__(self, size, parameters=None, padding=0, pad_if_needed=False):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
self.padding = padding
self.pad_if_needed = pad_if_needed
self.params = parameters
@staticmethod
def get_params(rawimg_size, output_size):
w, h = rawimg_size
th, tw = output_size
if w == tw and h == th:
return 0, 0, h, w
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
return [i, j, th, tw]
def __call__(self, img):
if self.padding > 0:
img = F.pad(img, self.padding)
# pad the width if needed
if self.pad_if_needed and img.size[0] < self.size[1]:
img = F.pad(img, (int((1 + self.size[1] - img.size[0]) / 2), 0))
# pad the height if needed
if self.pad_if_needed and img.size[1] < self.size[0]:
img = F.pad(img, (0, int((1 + self.size[0] - img.size[1]) / 2)))
i, j, h, w = self.params
return F.crop(img, i, j, h, w)
def __repr__(self):
return self.__class__.__name__ + '(size={0}, padding={1})'.format(self.size, self.padding)
class RandomHorizontalFlip(object):
def __init__(self):
pass
def __call__(self, img):
return F.hflip(img)
def __repr__(self):
return self.__class__.__name__ + '(p={})'.format(self.p)
class RandomVerticalFlip(object):
def __init__(self, p=0.5):
self.p = p
def __call__(self, img):
return F.vflip(img)
def __repr__(self):
return self.__class__.__name__ + '(p={})'.format(self.p)
normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
def _train_transform(*inputs):
image, target = inputs
print("np.asanyarray(image).shape", np.asanyarray(image).shape)
print("np.asanyarray(target).shape", np.asanyarray(target).shape)
transforms = []
# 1. 先从图像中剪裁INPUT_IMAGE_SIZE大小 然后进行后面的数据增强
params = MyRandomCrop.get_params(rawimg_size=image.size, output_size=(512,512))
transforms.append(MyRandomCrop(size=(512, 512), parameters=params))
# 2. 图像翻转
if random.random() < 0.5:
transforms.append(RandomHorizontalFlip()) # torchvision.transforms.functional.hflip(img)
if random.random() < 0.5:
transforms.append(RandomVerticalFlip())
# 3.旋转图像: 不旋转、旋转90、180或270度
RotationDegrees = [0, 90, 180, 270]
RotationDegree = random.randint(0, 3)
RotationDegree = RotationDegrees[RotationDegree]
transforms.append(T.RandomRotation((RotationDegree, RotationDegree)))
# image和GT做相同处理的部分
transform = T.Compose(transforms)
image = transform(image)
target = transform(target)
"""以下做不同的处理: """
# 4. 调整彩图的亮度、对比度、色调
# 5. 对彩图进行标准化、并转换为torch.tensor
ts = T.Compose([
# T.ColorJitter(brightness=0.2, contrast=0.2, hue=0.02),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
image = ts(image)
# 6. 对GT图像进行二值化、并转换为torch.tensor TODO: 注意需要添加一个维度包起来, 和input对应
target = torch.from_numpy(np.asanyarray(target, dtype=np.uint8) / 255).int()
target = target.unsqueeze(0)
return image, target
def _valid_transform(*inputs):
return T.Compose([
T.Scale(512),
T.CenterCrop(512),
T.ToTensor(),
normalize,
])
def _test_transform(*inputs):
return T.Compose([
T.Scale(512),
T.CenterCrop(512),
T.ToTensor(),
normalize,
])
transforms = dict({
"train": _train_transform,
"valid": _valid_transform,
"test": _test_transform
})
def driver_transform(*inputs, mode="train"):
assert mode in ['train', 'valid', 'test']
assert type(inputs) == tuple
x, y = inputs
print(x, y)
quit()
# 在这里可以将inputs参数unpack
transforms_function = transforms[mode]
return transforms_function(*inputs)
if __name__ == '__main__':
driver_transform(10, 20, mode="kkk")
|
{"hexsha": "711d5b032550406f0321f7c41c9dd3886175ff64", "size": 4956, "ext": "py", "lang": "Python", "max_stars_repo_path": "dataLoader/transformation/transform_demo.py", "max_stars_repo_name": "achanger/Deep-Learning-on-Pytorch", "max_stars_repo_head_hexsha": "c38c29c4c19c816fee97514e47fce402ec699b75", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dataLoader/transformation/transform_demo.py", "max_issues_repo_name": "achanger/Deep-Learning-on-Pytorch", "max_issues_repo_head_hexsha": "c38c29c4c19c816fee97514e47fce402ec699b75", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dataLoader/transformation/transform_demo.py", "max_forks_repo_name": "achanger/Deep-Learning-on-Pytorch", "max_forks_repo_head_hexsha": "c38c29c4c19c816fee97514e47fce402ec699b75", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6451612903, "max_line_length": 98, "alphanum_fraction": 0.6140032284, "include": true, "reason": "import numpy", "num_tokens": 1537}
|
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a Fast R-CNN network."""
from fast_rcnn.config import cfg
import roi_data_layer.roidb as rdl_roidb
from roi_data_layer.layer import RoIDataLayer
from utils.timer import Timer
import numpy as np
import os
import tensorflow as tf
import sys
from tensorflow.python.client import timeline
import time
class SolverWrapper(object):
"""A simple wrapper around Caffe's solver.
This wrapper gives us control over he snapshotting process, which we
use to unnormalize the learned bounding-box regression weights.
"""
def __init__(self, sess, network, timdb, vimdb, troidb, vroidb, output_dir, pretrained_model=None):
"""Initialize the SolverWrapper."""
self.net = network
self.timdb = timdb
self.timdb = vimdb
self.troidb = troidb
self.vroidb = vroidb
self.output_dir = output_dir
self.pretrained_model = pretrained_model
print 'Computing bounding-box regression targets...'
if cfg.TRAIN.BBOX_REG:
self.bbox_means, self.bbox_stds = rdl_roidb.add_bbox_regression_targets(
roidb)
print 'done'
# For checkpoint
self.saver = tf.train.Saver(max_to_keep=100)
def _add_loss_summaries(self, total_loss):
"""Add summaries for losses in CIFAR-10 model.
Generates moving average for all losses and associated summaries for
visualizing the performance of the network.
Args:
total_loss: Total loss from loss().
Returns:
loss_averages_op: op for generating moving averages of losses.
"""
# Compute the moving average of all individual losses and the total
# loss.
loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')
losses = tf.get_collection('losses')
loss_averages_op = loss_averages.apply(losses + [total_loss])
# Attach a scalar summary to all individual losses and the total loss; do the
# same for the averaged version of the losses.
for l in losses + [total_loss]:
# Name each loss as '(raw)' and name the moving average version of the loss
# as the original loss name.
tf.scalar_summary(l.op.name + ' (raw)', l)
tf.scalar_summary(l.op.name, loss_averages.average(l))
return loss_averages_op
def snapshot(self, sess, iter):
"""Take a snapshot of the network after unnormalizing the learned
bounding-box regression weights. This enables easy use at test-time.
"""
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
infix = ('_' + cfg.TRAIN.SNAPSHOT_INFIX
if cfg.TRAIN.SNAPSHOT_INFIX != '' else '')
filename = (cfg.TRAIN.SNAPSHOT_PREFIX + infix +
'_iter_{:d}'.format(iter + 1) + '.ckpt')
filename = os.path.join(self.output_dir, filename)
self.saver.save(sess, filename)
print 'Wrote snapshot to: {:s}'.format(filename)
def eval_model(self, sess):
data_layer = get_data_layer(self.vroidb, 'TEST')
cls_score = self.net.get_output('cls_score')
correct = tf.nn.in_top_k(cls_score, self.net.get_output('labels'), 1)
eval_correct = tf.reduce_sum(tf.cast(correct, tf.int32))
seg_pre = tf.boolean_mask(self.net.get_output(
'seg_score'), self.net.get_output('sweight'))
seg_gt = tf.boolean_mask(self.net.get_output(
'segmentation'), self.net.get_output('sweight'))
seg_correct = tf.reduce_sum(tf.cast(tf.greater(
tf.mul(seg_gt, tf.where(tf.greater(seg_pre, 0), 1, -1)), 0), tf.int32))
true_count = 0
num_examples = len(self.vroidb) * \
cfg.TRAIN.BATCH_SIZE / cfg.TRAIN.IMS_PER_BATCH
for i in xrange(len(self.vroidb) / cfg.TRAIN.IMS_PER_BATCH):
blobs = data_layer.forward()
# Make one SGD update
feed_dict = {self.net.data: blobs['data'], self.net.rois: blob['rois'], self.net.labels: blobs['label'], self.net.keep_prob: 0.5,
self.net.sweights: blobs['mask_weights'] > 0, self.net.segmentation: blobs['mask_targets']}
true_count, seg_count = sess.run(
eval_correct, seg_correct, feed_dict=feed_dict)
seg_pre += float(seg_count) / (cfg.MHEIGHT * cfg.MWIDTH)
cls_pre += true_count
cls_precision = float(cls_pre) / num_examples
seg_precision = seg_pre / num_examples
print(' Num examples: %d Cls-Precision @ 1: %0.04f Seg-Precision: %0.04f' %
(num_examples, cls_precision, seg_precision))
def train_model(self, sess, max_iters):
"""Network training loop."""
data_layer = get_data_layer(self.troidb, 'TRAIN')
# # RPN
# # classification loss
# rpn_cls_score = tf.reshape(self.net.get_output('rpn_cls_score_reshape'),[-1,2])
# rpn_label = tf.reshape(self.net.get_output('rpn-data')[0],[-1])
# # ignore_label(-1)
# rpn_cls_score = tf.reshape(tf.gather(rpn_cls_score,tf.where(tf.not_equal(rpn_label,-1))),[-1,2])
# rpn_label = tf.reshape(tf.gather(rpn_label,tf.where(tf.not_equal(rpn_label,-1))),[-1])
# rpn_cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(rpn_cls_score, rpn_label))#
#
# # bounding box regression L1 loss
# rpn_bbox_pred = self.net.get_output('rpn_bbox_pred')
# rpn_bbox_targets = tf.transpose(self.net.get_output('rpn-data')[1],[0,2,3,1])
# rpn_bbox_inside_weights = tf.transpose(self.net.get_output('rpn-data')[2],[0,2,3,1])
# rpn_bbox_outside_weights = tf.transpose(self.net.get_output('rpn-data')[3],[0,2,3,1])
# smoothL1_sign = tf.cast(tf.less(tf.abs(tf.sub(rpn_bbox_pred, rpn_bbox_targets)),1),tf.float32)
# rpn_loss_box = tf.mul(tf.reduce_mean(tf.reduce_sum(tf.mul(rpn_bbox_outside_weights,tf.add(
# tf.mul(tf.mul(tf.pow(tf.mul(rpn_bbox_inside_weights, tf.sub(rpn_bbox_pred, rpn_bbox_targets))*3,2),0.5),smoothL1_sign),
# tf.mul(tf.sub(tf.abs(tf.sub(rpn_bbox_pred,
# rpn_bbox_targets)),0.5/9.0),tf.abs(smoothL1_sign-1)))),
# reduction_indices=[1,2])),10)
# R-CNN
# classification loss
cls_score = self.net.get_output('cls_score')
#label = tf.placeholder(tf.int32, shape=[None])
cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
cls_score, self.net.get_output('labels')))
tf.add_to_collection('losses', cross_entropy)
# # bounding box regression L1 loss
# bbox_pred = self.net.get_output('bbox_pred')
# bbox_targets = self.net.get_output('roi-data')[2]
# bbox_inside_weights = self.net.get_output('roi-data')[3]
# bbox_outside_weights = self.net.get_output('roi-data')[4]
# loss_box = tf.reduce_mean(tf.reduce_sum(tf.mul(bbox_outside_weights,tf.mul(bbox_inside_weights, tf.abs(tf.sub(bbox_pred, bbox_targets)))), reduction_indices=[1]))
seg_gt = tf.boolean_mask(self.net.get_output(
'segmentation'), self.net.get_output('sweight'))
seg_pre = tf.boolean_mask(self.net.get_output(
'seg_score'), self.net.get_output('sweight'))
tf.image_summary('groundtruth', tf.reshape(seg_gt,[-1,cfg.MHEIGHT,cfg.MWIDTH,1]), max_images=100)
tf.image_summary('prediction', tf.reshape(seg_pre,[-1,cfg.MHEIGHT,cfg.MWIDTH,1]), max_images=100)
seg_loss = tf.reduce_mean(tf.nn.softplus(
tf.mul(tf.mul(seg_pre, seg_gt), -1)))
tf.add_to_collection('losses', seg_loss)
summary_op = tf.merge_all_summaries()
summary_writer = tf.train.SummaryWriter(self.output_dir, sess.graph)
print self.output_dir
loss = tf.add_n([cross_entropy, seg_loss],'totalloss')
loss_averages_op = self._add_loss_summaries(loss)
# optimizer and learning rate
global_step = tf.Variable(0, trainable=False)
lr = tf.train.exponential_decay(cfg.TRAIN.LEARNING_RATE, global_step,
cfg.TRAIN.STEPSIZE, 0.1, staircase=True)
momentum = cfg.TRAIN.MOMENTUM
with tf.control_dependencies([loss_averages_op]):
opt = tf.train.MomentumOptimizer(lr, momentum)
#train_op = opt.minimize(loss, global_step=global_step)
grads = opt.compute_gradients(loss)
train_op = opt.apply_gradients(grads, global_step=global_step)
for var in tf.trainable_variables():
tf.histogram_summary(var.op.name, var)
for grad, var in grads:
if grad is not None:
tf.histogram_summary(var.op.name + '/gradients', grad)
# iintialize variables
sess.run(tf.initialize_all_variables())
if self.pretrained_model is not None:
print('Loading pretrained model '
'weights from {:s}').format(self.pretrained_model)
self.net.load(self.pretrained_model, sess, True)
last_snapshot_iter = -1
timer = Timer()
for iter in range(max_iters):
# get one batch
blobs = data_layer.forward()
print iter
print blobs['data'].shape, blobs['rois'].shape
# Make one SGD update
feed_dict = {self.net.data: blobs['data'], self.net.rois: blobs['rois'], self.net.labels: blobs['labels'], self.net.keep_prob: 0.5,
self.net.sweights: blobs['mask_weights'] > 0, self.net.segmentation: blobs['mask_targets']}
run_options = None
run_metadata = None
if cfg.TRAIN.DEBUG_TIMELINE:
run_options = tf.RunOptions(
trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
timer.tic()
seg_loss_value, cls_loss_value, _ = sess.run([seg_loss, cross_entropy, train_op], feed_dict=feed_dict,
options=run_options,
run_metadata=run_metadata)
timer.toc()
if cfg.TRAIN.DEBUG_TIMELINE:
trace = timeline.Timeline(step_stats=run_metadata.step_stats)
trace_file = open(str(long(time.time() * 1000)) +
'-train-timeline.ctf.json', 'w')
trace_file.write(
trace.generate_chrome_trace_format(show_memory=False))
trace_file.close()
if (iter + 1) % (cfg.TRAIN.DISPLAY) == 0:
print 'iter: %d / %d, total loss: %.4f, seg_loss: %.4f, cls_loss: %.4f,lr: %f' %\
(iter + 1, max_iters, cls_loss_value + seg_loss_value,
seg_loss_value, cls_loss_value, lr.eval())
print 'speed: {:.3f}s / iter'.format(timer.average_time)
if (iter + 1) % cfg.TRAIN.SNAPSHOT_ITERS == 0:
last_snapshot_iter = iter
self.snapshot(sess, iter)
self.eval_model(self, sess)
if (iter + 1) % 100 == 0:
summary_str = sess.run(summary_op,feed_dict=feed_dict)
summary_writer.add_summary(summary_str, iter+1)
print 'summary %d done '%(iter + 1)
if last_snapshot_iter != iter:
self.snapshot(sess, iter)
def get_training_roidb(imdb):
"""Returns a roidb (Region of Interest database) for use in training."""
if cfg.TRAIN.USE_FLIPPED and imdb._image_set != 'val':
# if cfg.TRAIN.USE_FLIPPED:
print 'Appending horizontally-flipped training examples...'
imdb.append_flipped_images()
print 'done'
print 'Preparing training data...'
rdl_roidb.prepare_roidb(imdb)
print 'done'
return imdb.roidb
def get_data_layer(roidb, num_classes):
"""return a data layer."""
layer = RoIDataLayer(roidb, num_classes)
return layer
def filter_roidb(roidb):
"""Remove roidb entries that have no usable RoIs."""
def is_valid(entry):
# Valid images have:
# (1) At least one foreground RoI OR
# (2) At least one background RoI
overlaps = entry['max_overlaps']
# find boxes with sufficient overlap
fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0]
# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) &
(overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]
# image is only valid if such boxes exist
valid = len(fg_inds) > 0 or len(bg_inds) > 0
return valid
num = len(roidb)
if num>30000:
delinds=[23895,23895+49999]
else:
delinds=[]
filtered_roidb = [entry for i, entry in enumerate(roidb) if is_valid(entry) and i not in delinds]
num_after = len(filtered_roidb)
print 'Filtered {} roidb entries: {} -> {}'.format(num - num_after,
num, num_after)
return filtered_roidb
def train_net(network, timdb, vimdb, troidb, vroidb, output_dir, pretrained_model=None, max_iters=40000):
"""Train a Fast R-CNN network."""
troidb = filter_roidb(troidb)
vroidb = filter_roidb(vroidb)
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
sw = SolverWrapper(sess, network, timdb, vimdb, troidb,
vroidb, output_dir, pretrained_model=pretrained_model)
print 'Solving...'
sw.train_model(sess, max_iters)
print 'done solving'
|
{"hexsha": "cbbeaa978a77f1e2db070bbb618e90ef0dc6ba4b", "size": 13928, "ext": "py", "lang": "Python", "max_stars_repo_path": "tlib/fast_rcnn/train.py", "max_stars_repo_name": "shallowyuan/cosegmentor-crf", "max_stars_repo_head_hexsha": "c84a9418b70f3f3c7c6a7e998de5835182619f30", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tlib/fast_rcnn/train.py", "max_issues_repo_name": "shallowyuan/cosegmentor-crf", "max_issues_repo_head_hexsha": "c84a9418b70f3f3c7c6a7e998de5835182619f30", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tlib/fast_rcnn/train.py", "max_forks_repo_name": "shallowyuan/cosegmentor-crf", "max_forks_repo_head_hexsha": "c84a9418b70f3f3c7c6a7e998de5835182619f30", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8553846154, "max_line_length": 171, "alphanum_fraction": 0.6187535899, "include": true, "reason": "import numpy", "num_tokens": 3331}
|
[STATEMENT]
lemma add_mset_commute:
"add_mset x (add_mset y M) = add_mset y (add_mset x M)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. add_mset x (add_mset y M) = add_mset y (add_mset x M)
[PROOF STEP]
by (auto simp: multiset_eq_iff)
|
{"llama_tokens": 117, "file": null, "length": 1}
|
[STATEMENT]
lemma null_space_orthogonal_complement_row_space:
fixes A::"'a^'cols::{finite, wellorder}^'rows::{finite, wellorder}"
shows "null_space A = COLS.v.orthogonal_complement (row_space (\<chi> i j. cnj (A $ i $ j)))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. null_space A = COLS.v.orthogonal_complement (row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)))
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. null_space A = COLS.v.orthogonal_complement (row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)))
[PROOF STEP]
interpret m: matrix inner_rows inner_cols
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Generalizations2.matrix inner_rows inner_cols
[PROOF STEP]
by unfold_locales
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. null_space A = COLS.v.orthogonal_complement (row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)))
[PROOF STEP]
let ?A="(\<chi> i j. cnj (A $ i $ j))"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. null_space A = COLS.v.orthogonal_complement (row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)))
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. null_space A = COLS.v.orthogonal_complement (row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)))
[PROOF STEP]
proof (unfold null_space_def COLS.v.orthogonal_complement_def, auto)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>x y. \<lbrakk>A *v x = 0; y \<in> row_space (\<chi>i j. cnj_class.cnj (A $ i $ j))\<rbrakk> \<Longrightarrow> COLS.v.orthogonal y x
2. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
fix x xa
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>x y. \<lbrakk>A *v x = 0; y \<in> row_space (\<chi>i j. cnj_class.cnj (A $ i $ j))\<rbrakk> \<Longrightarrow> COLS.v.orthogonal y x
2. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
assume Ax: "A *v x = 0" and xa: "xa \<in> row_space (\<chi> i j. cnj (A $ i $ j))"
[PROOF STATE]
proof (state)
this:
A *v x = 0
xa \<in> row_space (\<chi>i j. cnj_class.cnj (A $ i $ j))
goal (2 subgoals):
1. \<And>x y. \<lbrakk>A *v x = 0; y \<in> row_space (\<chi>i j. cnj_class.cnj (A $ i $ j))\<rbrakk> \<Longrightarrow> COLS.v.orthogonal y x
2. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
obtain y where y: "xa = transpose (\<chi> i j. cnj (A $ i $ j)) *v y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>y. xa = Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using xa
[PROOF STATE]
proof (prove)
using this:
xa \<in> row_space (\<chi>i j. cnj_class.cnj (A $ i $ j))
goal (1 subgoal):
1. (\<And>y. xa = Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
unfolding row_space_eq
[PROOF STATE]
proof (prove)
using this:
xa \<in> {w. \<exists>y. Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y = w}
goal (1 subgoal):
1. (\<And>y. xa = Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
xa = Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y
goal (2 subgoals):
1. \<And>x y. \<lbrakk>A *v x = 0; y \<in> row_space (\<chi>i j. cnj_class.cnj (A $ i $ j))\<rbrakk> \<Longrightarrow> COLS.v.orthogonal y x
2. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
have y2: "y v* (\<chi> i j. cnj (A $ i $ j)) = xa"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. y v* (\<chi>i j. cnj_class.cnj (A $ i $ j)) = xa
[PROOF STEP]
using transpose_vector y
[PROOF STATE]
proof (prove)
using this:
?x v* ?A = Finite_Cartesian_Product.transpose ?A *v ?x
xa = Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y
goal (1 subgoal):
1. y v* (\<chi>i j. cnj_class.cnj (A $ i $ j)) = xa
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
y v* (\<chi>i j. cnj_class.cnj (A $ i $ j)) = xa
goal (2 subgoals):
1. \<And>x y. \<lbrakk>A *v x = 0; y \<in> row_space (\<chi>i j. cnj_class.cnj (A $ i $ j))\<rbrakk> \<Longrightarrow> COLS.v.orthogonal y x
2. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
show "COLS.v.orthogonal xa x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. COLS.v.orthogonal xa x
[PROOF STEP]
using m.dot_lmul_matrix[of y ?A x]
[PROOF STATE]
proof (prove)
using this:
inner_cols (y v* (\<chi>i j. cnj_class.cnj (A $ i $ j))) x = inner_rows y ((\<chi>i j. cnj_class.cnj ((\<chi>i j. cnj_class.cnj (A $ i $ j)) $ i $ j)) *v x)
goal (1 subgoal):
1. COLS.v.orthogonal xa x
[PROOF STEP]
unfolding cnj_cnj_matrix Ax ROWS.v.inner_zero_right
[PROOF STATE]
proof (prove)
using this:
inner_cols (y v* (\<chi>i j. cnj_class.cnj (A $ i $ j))) x = (0::'a)
goal (1 subgoal):
1. COLS.v.orthogonal xa x
[PROOF STEP]
unfolding y2
[PROOF STATE]
proof (prove)
using this:
inner_cols xa x = (0::'a)
goal (1 subgoal):
1. COLS.v.orthogonal xa x
[PROOF STEP]
unfolding COLS.v.orthogonal_def
[PROOF STATE]
proof (prove)
using this:
inner_cols xa x = (0::'a)
goal (1 subgoal):
1. inner_cols xa x = (0::'a)
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
COLS.v.orthogonal xa x
goal (1 subgoal):
1. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
fix x
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
assume xa: "\<forall>xa\<in>row_space (\<chi> i j. cnj (A $ i $ j)). COLS.v.orthogonal xa x"
[PROOF STATE]
proof (state)
this:
\<forall>xa\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal xa x
goal (1 subgoal):
1. \<And>x. \<forall>y\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal y x \<Longrightarrow> A *v x = 0
[PROOF STEP]
show "A *v x = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A *v x = 0
[PROOF STEP]
using xa
[PROOF STATE]
proof (prove)
using this:
\<forall>xa\<in>row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)). COLS.v.orthogonal xa x
goal (1 subgoal):
1. A *v x = 0
[PROOF STEP]
unfolding row_space_eq COLS.v.orthogonal_def
[PROOF STATE]
proof (prove)
using this:
\<forall>xa\<in>{w. \<exists>y. Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y = w}. inner_cols xa x = (0::'a)
goal (1 subgoal):
1. A *v x = 0
[PROOF STEP]
using COLS.v.inner_eq_zero_iff
[PROOF STATE]
proof (prove)
using this:
\<forall>xa\<in>{w. \<exists>y. Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y = w}. inner_cols xa x = (0::'a)
(inner_cols ?x ?x = (0::'a)) = (?x = 0)
goal (1 subgoal):
1. A *v x = 0
[PROOF STEP]
using m.dot_lmul_matrix[of _ ?A]
[PROOF STATE]
proof (prove)
using this:
\<forall>xa\<in>{w. \<exists>y. Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y = w}. inner_cols xa x = (0::'a)
(inner_cols ?x ?x = (0::'a)) = (?x = 0)
inner_cols (?x v* (\<chi>i j. cnj_class.cnj (A $ i $ j))) ?y = inner_rows ?x ((\<chi>i j. cnj_class.cnj ((\<chi>i j. cnj_class.cnj (A $ i $ j)) $ i $ j)) *v ?y)
goal (1 subgoal):
1. A *v x = 0
[PROOF STEP]
unfolding transpose_vector
[PROOF STATE]
proof (prove)
using this:
\<forall>xa\<in>{w. \<exists>y. Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v y = w}. inner_cols xa x = (0::'a)
(inner_cols ?x ?x = (0::'a)) = (?x = 0)
inner_cols (Finite_Cartesian_Product.transpose (\<chi>i j. cnj_class.cnj (A $ i $ j)) *v ?x) ?y = inner_rows ?x ((\<chi>i j. cnj_class.cnj ((\<chi>i j. cnj_class.cnj (A $ i $ j)) $ i $ j)) *v ?y)
goal (1 subgoal):
1. A *v x = 0
[PROOF STEP]
by auto
(metis ROWS.i4 m.cnj_cnj_matrix m.dot_lmul_matrix transpose_vector)
[PROOF STATE]
proof (state)
this:
A *v x = 0
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
null_space A = COLS.v.orthogonal_complement (row_space (\<chi>i j. cnj_class.cnj (A $ i $ j)))
goal:
No subgoals!
[PROOF STEP]
qed
|
{"llama_tokens": 4065, "file": "QR_Decomposition_Generalizations2", "length": 33}
|
[STATEMENT]
lemma reaches_on_run_hd_t:
assumes "reaches_on run_hd init_hd vs e"
shows "\<exists>x. reaches_on run_t t0 (map fst vs) x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
[PROOF STEP]
proof (cases vs rule: rev_cases)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. vs = [] \<Longrightarrow> \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
2. \<And>ys y. vs = ys @ [y] \<Longrightarrow> \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
[PROOF STEP]
case (snoc ys y)
[PROOF STATE]
proof (state)
this:
vs = ys @ [y]
goal (2 subgoals):
1. vs = [] \<Longrightarrow> \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
2. \<And>ys y. vs = ys @ [y] \<Longrightarrow> \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
reaches_on run_hd init_hd vs e
goal (1 subgoal):
1. \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
[PROOF STEP]
apply (cases y)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>a b. \<lbrakk>reaches_on run_hd init_hd vs e; y = (a, b)\<rbrakk> \<Longrightarrow> \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
[PROOF STEP]
apply (auto simp: snoc dest!: reaches_on_split_last)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>a b s'. \<lbrakk>y = (a, b); reaches_on run_hd init_hd ys s'; run_hd s' = Some (e, a, b)\<rbrakk> \<Longrightarrow> \<exists>x. reaches_on local.run_t local.t0 (map fst ys @ [a]) x
[PROOF STEP]
apply (meson reaches_on_app[OF reach_event_t0_t] read_t.simps(2) read_t_run)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
\<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
goal (1 subgoal):
1. vs = [] \<Longrightarrow> \<exists>x. reaches_on local.run_t local.t0 (map fst vs) x
[PROOF STEP]
qed (auto intro: reaches_on.intros)
|
{"llama_tokens": 904, "file": "VYDRA_MDL_Monitor", "length": 9}
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Groups of optimizers for use in benchmarks
"""
import typing as tp
import numpy as np
import nevergrad as ng
from nevergrad.common.decorators import Registry
from nevergrad.optimization import base as obase
from nevergrad.optimization.optimizerlib import ConfSplitOptimizer
from nevergrad.optimization.optimizerlib import registry as optimizerlib_registry
from nevergrad.optimization.optimizerlib import ParametrizedOnePlusOne
Optim = tp.Union[obase.ConfiguredOptimizer, str]
registry: Registry[tp.Callable[[], tp.Iterable[Optim]]] = Registry()
def get_optimizers(*names: str, seed: tp.Optional[int] = None) -> tp.List[Optim]:
"""Returns an deterministically ordered list of optimizers, belonging to the
provided groups. If a seed is provided, it is used to shuffle the list.
Parameters
----------
*names: str
names of the groups to use. See nevergrad/benchmarks/optimizer_groups.txt
(generated/updated when running pytest)
for the list of groups and what they contain
seed: optional int
a seed to shuffle the list of optimizers
"""
optims: tp.List[Optim] = []
for name in names:
for optim in registry[name]():
if optim not in optims: # avoid duplicates
optims.append(optim)
if seed is not None:
np.random.RandomState(seed).shuffle(optims)
return optims
@registry.register
def large() -> tp.Sequence[Optim]:
return [
"NGO",
"Shiwa",
"DiagonalCMA",
"CMA",
"PSO",
"DE",
"MiniDE",
"QrDE",
"MiniQrDE",
"LhsDE",
"OnePlusOne",
"SQP",
"Cobyla",
"Powell",
"TwoPointsDE",
"OnePointDE",
"AlmostRotationInvariantDE",
"RotationInvariantDE",
"Portfolio",
"CMandAS2",
"CM",
"MultiCMA",
"TripleCMA",
"MultiScaleCMA",
"RSQP",
"RCobyla",
"RPowell",
"MetaModel",
"PolyCMA",
]
@registry.register
def emna_variants() -> tp.Sequence[Optim]:
return [
"IsoEMNA",
"NaiveIsoEMNA",
"AnisoEMNA",
"NaiveAnisoEMNA",
"CMA",
"NaiveTBPSA",
"NaiveIsoEMNATBPSA",
"IsoEMNATBPSA",
"NaiveAnisoEMNATBPSA",
"AnisoEMNATBPSA",
]
@registry.register
def splitters() -> tp.Sequence[Optim]:
optims: tp.List[Optim] = []
for num_optims in [None, 3, 5, 9, 13]:
for str_optim in ["CMA", "ECMA", "DE", "TwoPointsDE"]:
optim = optimizerlib_registry[str_optim]
name = "Split" + str_optim + ("Auto" if num_optims is None else str(num_optims))
opt = ConfSplitOptimizer(multivariate_optimizer=optim, num_optims=num_optims).set_name(name)
optims.append(opt)
return optims
@registry.register
def progressive() -> tp.Sequence[Optim]:
optims: tp.List[Optim] = []
for mutation in ["discrete", "gaussian"]:
for num_optims in [None, 13, 10000]:
name = (
"Prog"
+ ("Disc" if mutation == "discrete" else "")
+ ("Auto" if num_optims is None else ("Inf" if num_optims == 10000 else str(num_optims)))
)
mv = ParametrizedOnePlusOne(noise_handling="optimistic", mutation=mutation)
opt = ConfSplitOptimizer(
num_optims=num_optims, progressive=True, multivariate_optimizer=mv
).set_name(name)
optims.append(opt)
return optims
@registry.register
def basics() -> tp.Sequence[Optim]:
return ["NGOpt10", "CMandAS2", "CMA", "DE", "MetaModel"]
@registry.register
def baselines() -> tp.Sequence[Optim]:
# This list should not change. This is the basics for comparison.
# No algorithm with unstable other dependency.
return ["OnePlusOne", "DiscreteOnePlusOne", "NoisyDiscreteOnePlusOne", "PSO", "DE", "TwoPointsDE"]
@registry.register
def parallel_basics() -> tp.Sequence[Optim]:
return ["NGOpt10", "CMandAS2", "CMA", "DE", "MetaModel"]
@registry.register
def cma() -> tp.Sequence[Optim]:
return ["DiagonalCMA", "CMA"]
@registry.register
def competence_map() -> tp.Sequence[Optim]:
return ["NGO", "Shiwa"]
@registry.register
def competitive() -> tp.Sequence[Optim]:
return get_optimizers("cma", "competence_map") + [
"MetaNGOpt10",
"NaiveTBPSA",
"PSO",
"DE",
"LhsDE",
"RandomSearch",
"OnePlusOne",
"TwoPointsDE",
]
@registry.register
def all_bo() -> tp.Sequence[Optim]:
return sorted(x for x in ng.optimizers.registry if "BO" in x)
@registry.register
def discrete() -> tp.Sequence[Optim]:
return [name for name in optimizerlib_registry.keys() if "iscrete" in name and "oisy" not in name]
@registry.register
def noisy() -> tp.Sequence[Optim]:
return ["OptimisticDiscreteOnePlusOne", "OptimisticNoisyOnePlusOne", "TBPSA", "SPSA", "NGOpt10"]
@registry.register
def structure() -> tp.Sequence[Optim]:
return ["RecES", "RecMixES", "RecMutDE", "ParametrizationDE"]
@registry.register
def small_discrete() -> tp.Sequence[Optim]:
return [
"DiscreteOnePlusOne",
"Shiwa",
"CMA",
"PSO",
"TwoPointsDE",
"DE",
"OnePlusOne",
"AdaptiveDiscreteOnePlusOne",
"CMandAS2",
"PortfolioDiscreteOnePlusOne",
"DoubleFastGADiscreteOnePlusOne",
"MultiDiscrete",
"DiscreteBSOOnePlusOne",
"AnisotropicAdaptiveDiscreteOnePlusOne",
"DiscreteLenglerOnePlusOne",
]
@registry.register
def scipy() -> tp.Sequence[Optim]:
return ["RSQP", "RCobyla", "RPowell", "SQPCMA", "SQP", "Cobyla", "Powell"]
@registry.register
def es() -> tp.Sequence[Optim]:
es = [
ng.families.EvolutionStrategy(
recombination_ratio=recomb, only_offsprings=only, popsize=pop, offsprings=pop * 5
)
for only in [True, False]
for recomb in [0.1, 0.5]
for pop in [20, 40, 80]
]
return es
@registry.register
def multimodal() -> tp.Sequence[Optim]:
return ["NaiveTBPSA", "MultiCMA", "TripleCMA", "MultiScaleCMA", "PolyCMA", "QORandomSearch"]
# TODO(oteytaud): we should simplify the following.
@registry.register
def oneshot() -> tp.Sequence[Optim]:
return sorted(
x
for x, y in optimizerlib_registry.items()
if y.one_shot
and "4" not in x
and "7" not in x
and "LHS" not in x
and "alton" not in x
and ("ando" not in x or "QO" in x)
) # QORandomSearch is the only valid variant of RandomSearch.
@registry.register
def structured_moo() -> tp.Sequence[Optim]:
return [
"CMA",
"NGOpt10",
"MetaNGOpt10",
"DE",
"PSO",
"RecES",
"RecMixES",
"RecMutDE",
"ParametrizationDE",
]
@registry.register
def spsa() -> tp.Sequence[Optim]:
# return sorted(x for x, y in ng.optimizers.registry.items() if (any(e in x for e in "TBPSA SPSA".split()) and "iscr" not in x))
return ["NaiveTBPSA", "SPSA", "TBPSA"]
|
{"hexsha": "a2abf01ac10fba311aefe91da7fba6783aa04a26", "size": 7339, "ext": "py", "lang": "Python", "max_stars_repo_path": "nevergrad/benchmark/optgroups.py", "max_stars_repo_name": "juliendehos/nevergrad", "max_stars_repo_head_hexsha": "b31a66bdc883e29a6c8572e341b4b56cc4157a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nevergrad/benchmark/optgroups.py", "max_issues_repo_name": "juliendehos/nevergrad", "max_issues_repo_head_hexsha": "b31a66bdc883e29a6c8572e341b4b56cc4157a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nevergrad/benchmark/optgroups.py", "max_forks_repo_name": "juliendehos/nevergrad", "max_forks_repo_head_hexsha": "b31a66bdc883e29a6c8572e341b4b56cc4157a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7992424242, "max_line_length": 132, "alphanum_fraction": 0.6172503066, "include": true, "reason": "import numpy", "num_tokens": 2032}
|
(* Title: POPLmark/POPLmark.thy
Author: Stefan Berghofer, TU Muenchen, 2005
*)
theory POPLmark
imports Basis
begin
section \<open>Formalization of the basic calculus\<close>
text \<open>
\label{sec:basic-calculus}
In this section, we describe the formalization of the basic calculus
without records. As a main result, we prove {\it type safety}, presented
as two separate theorems, namely {\it preservation} and {\it progress}.
\<close>
subsection \<open>Types and Terms\<close>
text \<open>
The types of System \fsub{} are represented by the following datatype:
\<close>
datatype type =
TVar nat
| Top
| Fun type type (infixr "\<rightarrow>" 200)
| TyAll type type ("(3\<forall><:_./ _)" [0, 10] 10)
text \<open>
The subtyping and typing judgements depend on a {\it context} (or environment) @{term \<Gamma>}
containing bindings for term and type variables. A context is a list of bindings,
where the @{term i}th element @{term "\<Gamma>\<langle>i\<rangle>"} corresponds to the variable
with index @{term i}.
\<close>
datatype binding = VarB type | TVarB type
type_synonym env = "binding list"
text \<open>
In contrast to the usual presentation of type systems often found in textbooks, new
elements are added to the left of a context using the \<open>Cons\<close> operator \<open>\<Colon>\<close> for lists.
We write @{term is_TVarB} for the predicate that returns @{term True} when applied to
a type variable binding, function @{term type_ofB} extracts the type contained in a binding,
and @{term "mapB f"} applies @{term f} to the type contained in a binding.
\<close>
primrec is_TVarB :: "binding \<Rightarrow> bool"
where
"is_TVarB (VarB T) = False"
| "is_TVarB (TVarB T) = True"
primrec type_ofB :: "binding \<Rightarrow> type"
where
"type_ofB (VarB T) = T"
| "type_ofB (TVarB T) = T"
primrec mapB :: "(type \<Rightarrow> type) \<Rightarrow> binding \<Rightarrow> binding"
where
"mapB f (VarB T) = VarB (f T)"
| "mapB f (TVarB T) = TVarB (f T)"
text \<open>
The following datatype represents the terms of System \fsub{}:
\<close>
datatype trm =
Var nat
| Abs type trm ("(3\<lambda>:_./ _)" [0, 10] 10)
| TAbs type trm ("(3\<lambda><:_./ _)" [0, 10] 10)
| App trm trm (infixl "\<bullet>" 200)
| TApp trm type (infixl "\<bullet>\<^sub>\<tau>" 200)
subsection \<open>Lifting and Substitution\<close>
text \<open>
One of the central operations of $\lambda$-calculus is {\it substitution}.
In order to avoid that free variables in a term or type get ``captured''
when substituting it for a variable occurring in the scope of a binder,
we have to increment the indices of its free variables during substitution.
This is done by the lifting functions \<open>\<up>\<^sub>\<tau> n k\<close> and \<open>\<up> n k\<close>
for types and terms, respectively, which increment the indices of all free
variables with indices \<open>\<ge> k\<close> by @{term n}. The lifting functions on
types and terms are defined by
\<close>
primrec liftT :: "nat \<Rightarrow> nat \<Rightarrow> type \<Rightarrow> type" ("\<up>\<^sub>\<tau>")
where
"\<up>\<^sub>\<tau> n k (TVar i) = (if i < k then TVar i else TVar (i + n))"
| "\<up>\<^sub>\<tau> n k Top = Top"
| "\<up>\<^sub>\<tau> n k (T \<rightarrow> U) = \<up>\<^sub>\<tau> n k T \<rightarrow> \<up>\<^sub>\<tau> n k U"
| "\<up>\<^sub>\<tau> n k (\<forall><:T. U) = (\<forall><:\<up>\<^sub>\<tau> n k T. \<up>\<^sub>\<tau> n (k + 1) U)"
primrec lift :: "nat \<Rightarrow> nat \<Rightarrow> trm \<Rightarrow> trm" ("\<up>")
where
"\<up> n k (Var i) = (if i < k then Var i else Var (i + n))"
| "\<up> n k (\<lambda>:T. t) = (\<lambda>:\<up>\<^sub>\<tau> n k T. \<up> n (k + 1) t)"
| "\<up> n k (\<lambda><:T. t) = (\<lambda><:\<up>\<^sub>\<tau> n k T. \<up> n (k + 1) t)"
| "\<up> n k (s \<bullet> t) = \<up> n k s \<bullet> \<up> n k t"
| "\<up> n k (t \<bullet>\<^sub>\<tau> T) = \<up> n k t \<bullet>\<^sub>\<tau> \<up>\<^sub>\<tau> n k T"
text \<open>
It is useful to also define an ``unlifting'' function \<open>\<down>\<^sub>\<tau> n k\<close> for
decrementing all free variables with indices \<open>\<ge> k\<close> by @{term n}.
Moreover, we need several substitution functions, denoted by
\mbox{\<open>T[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau>\<close>}, \mbox{\<open>t[k \<mapsto>\<^sub>\<tau> S]\<close>}, and \mbox{\<open>t[k \<mapsto> s]\<close>},
which substitute type variables in types, type variables in terms,
and term variables in terms, respectively. They are defined as follows:
\<close>
primrec substTT :: "type \<Rightarrow> nat \<Rightarrow> type \<Rightarrow> type" ("_[_ \<mapsto>\<^sub>\<tau> _]\<^sub>\<tau>" [300, 0, 0] 300)
where
"(TVar i)[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau> =
(if k < i then TVar (i - 1) else if i = k then \<up>\<^sub>\<tau> k 0 S else TVar i)"
| "Top[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau> = Top"
| "(T \<rightarrow> U)[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau> = T[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau> \<rightarrow> U[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau>"
| "(\<forall><:T. U)[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau> = (\<forall><:T[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau>. U[k+1 \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau>)"
primrec decT :: "nat \<Rightarrow> nat \<Rightarrow> type \<Rightarrow> type" ("\<down>\<^sub>\<tau>")
where
"\<down>\<^sub>\<tau> 0 k T = T"
| "\<down>\<^sub>\<tau> (Suc n) k T = \<down>\<^sub>\<tau> n k (T[k \<mapsto>\<^sub>\<tau> Top]\<^sub>\<tau>)"
primrec subst :: "trm \<Rightarrow> nat \<Rightarrow> trm \<Rightarrow> trm" ("_[_ \<mapsto> _]" [300, 0, 0] 300)
where
"(Var i)[k \<mapsto> s] = (if k < i then Var (i - 1) else if i = k then \<up> k 0 s else Var i)"
| "(t \<bullet> u)[k \<mapsto> s] = t[k \<mapsto> s] \<bullet> u[k \<mapsto> s]"
| "(t \<bullet>\<^sub>\<tau> T)[k \<mapsto> s] = t[k \<mapsto> s] \<bullet>\<^sub>\<tau> \<down>\<^sub>\<tau> 1 k T"
| "(\<lambda>:T. t)[k \<mapsto> s] = (\<lambda>:\<down>\<^sub>\<tau> 1 k T. t[k+1 \<mapsto> s])"
| "(\<lambda><:T. t)[k \<mapsto> s] = (\<lambda><:\<down>\<^sub>\<tau> 1 k T. t[k+1 \<mapsto> s])"
primrec substT :: "trm \<Rightarrow> nat \<Rightarrow> type \<Rightarrow> trm" ("_[_ \<mapsto>\<^sub>\<tau> _]" [300, 0, 0] 300)
where
"(Var i)[k \<mapsto>\<^sub>\<tau> S] = (if k < i then Var (i - 1) else Var i)"
| "(t \<bullet> u)[k \<mapsto>\<^sub>\<tau> S] = t[k \<mapsto>\<^sub>\<tau> S] \<bullet> u[k \<mapsto>\<^sub>\<tau> S]"
| "(t \<bullet>\<^sub>\<tau> T)[k \<mapsto>\<^sub>\<tau> S] = t[k \<mapsto>\<^sub>\<tau> S] \<bullet>\<^sub>\<tau> T[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau>"
| "(\<lambda>:T. t)[k \<mapsto>\<^sub>\<tau> S] = (\<lambda>:T[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau>. t[k+1 \<mapsto>\<^sub>\<tau> S])"
| "(\<lambda><:T. t)[k \<mapsto>\<^sub>\<tau> S] = (\<lambda><:T[k \<mapsto>\<^sub>\<tau> S]\<^sub>\<tau>. t[k+1 \<mapsto>\<^sub>\<tau> S])"
text \<open>
Lifting and substitution extends to typing contexts as follows:
\<close>
primrec liftE :: "nat \<Rightarrow> nat \<Rightarrow> env \<Rightarrow> env" ("\<up>\<^sub>e")
where
"\<up>\<^sub>e n k [] = []"
| "\<up>\<^sub>e n k (B \<Colon> \<Gamma>) = mapB (\<up>\<^sub>\<tau> n (k + \<parallel>\<Gamma>\<parallel>)) B \<Colon> \<up>\<^sub>e n k \<Gamma>"
primrec substE :: "env \<Rightarrow> nat \<Rightarrow> type \<Rightarrow> env" ("_[_ \<mapsto>\<^sub>\<tau> _]\<^sub>e" [300, 0, 0] 300)
where
"[][k \<mapsto>\<^sub>\<tau> T]\<^sub>e = []"
| "(B \<Colon> \<Gamma>)[k \<mapsto>\<^sub>\<tau> T]\<^sub>e = mapB (\<lambda>U. U[k + \<parallel>\<Gamma>\<parallel> \<mapsto>\<^sub>\<tau> T]\<^sub>\<tau>) B \<Colon> \<Gamma>[k \<mapsto>\<^sub>\<tau> T]\<^sub>e"
primrec decE :: "nat \<Rightarrow> nat \<Rightarrow> env \<Rightarrow> env" ("\<down>\<^sub>e")
where
"\<down>\<^sub>e 0 k \<Gamma> = \<Gamma>"
| "\<down>\<^sub>e (Suc n) k \<Gamma> = \<down>\<^sub>e n k (\<Gamma>[k \<mapsto>\<^sub>\<tau> Top]\<^sub>e)"
text \<open>
Note that in a context of the form @{term "B \<Colon> \<Gamma>"}, all variables in @{term B} with
indices smaller than the length of @{term \<Gamma>} refer to entries in @{term \<Gamma>} and therefore
must not be affected by substitution and lifting. This is the reason why an
additional offset @{term "\<parallel>\<Gamma>\<parallel>"} needs to be added to the index @{term k}
in the second clauses of the above functions. Some standard properties of lifting
and substitution, which can be proved by structural induction on terms and types,
are proved below. Properties of this kind are
quite standard for encodings using de Bruijn indices and can also be found in
papers by Barras and Werner \cite{Barras-Werner-JAR} and Nipkow \cite{Nipkow-JAR01}.
\<close>
lemma liftE_length [simp]: "\<parallel>\<up>\<^sub>e n k \<Gamma>\<parallel> = \<parallel>\<Gamma>\<parallel>"
by (induct \<Gamma>) simp_all
lemma substE_length [simp]: "\<parallel>\<Gamma>[k \<mapsto>\<^sub>\<tau> U]\<^sub>e\<parallel> = \<parallel>\<Gamma>\<parallel>"
by (induct \<Gamma>) simp_all
lemma liftE_nth [simp]:
"(\<up>\<^sub>e n k \<Gamma>)\<langle>i\<rangle> = map_option (mapB (\<up>\<^sub>\<tau> n (k + \<parallel>\<Gamma>\<parallel> - i - 1))) (\<Gamma>\<langle>i\<rangle>)"
apply (induct \<Gamma> arbitrary: i)
apply simp
apply simp
apply (case_tac i)
apply simp
apply simp
done
lemma substE_nth [simp]:
"(\<Gamma>[0 \<mapsto>\<^sub>\<tau> T]\<^sub>e)\<langle>i\<rangle> = map_option (mapB (\<lambda>U. U[\<parallel>\<Gamma>\<parallel> - i - 1 \<mapsto>\<^sub>\<tau> T]\<^sub>\<tau>)) (\<Gamma>\<langle>i\<rangle>)"
apply (induct \<Gamma> arbitrary: i)
apply simp
apply simp
apply (case_tac i)
apply simp
apply simp
done
lemma liftT_liftT [simp]:
"i \<le> j \<Longrightarrow> j \<le> i + m \<Longrightarrow> \<up>\<^sub>\<tau> n j (\<up>\<^sub>\<tau> m i T) = \<up>\<^sub>\<tau> (m + n) i T"
by (induct T arbitrary: i j m n) simp_all
lemma liftT_liftT' [simp]:
"i + m \<le> j \<Longrightarrow> \<up>\<^sub>\<tau> n j (\<up>\<^sub>\<tau> m i T) = \<up>\<^sub>\<tau> m i (\<up>\<^sub>\<tau> n (j - m) T)"
apply (induct T arbitrary: i j m n)
apply simp_all
apply arith
apply (subgoal_tac "Suc j - m = Suc (j - m)")
apply simp
apply arith
done
lemma lift_size [simp]: "size (\<up>\<^sub>\<tau> n k T) = size T"
by (induct T arbitrary: k) simp_all
lemma liftT0 [simp]: "\<up>\<^sub>\<tau> 0 i T = T"
by (induct T arbitrary: i) simp_all
lemma lift0 [simp]: "\<up> 0 i t = t"
by (induct t arbitrary: i) simp_all
theorem substT_liftT [simp]:
"k \<le> k' \<Longrightarrow> k' < k + n \<Longrightarrow> (\<up>\<^sub>\<tau> n k T)[k' \<mapsto>\<^sub>\<tau> U]\<^sub>\<tau> = \<up>\<^sub>\<tau> (n - 1) k T"
by (induct T arbitrary: k k') simp_all
theorem liftT_substT' [simp]: "k' < k \<Longrightarrow>
\<up>\<^sub>\<tau> n k (T[k' \<mapsto>\<^sub>\<tau> U]\<^sub>\<tau>) = \<up>\<^sub>\<tau> n (k + 1) T[k' \<mapsto>\<^sub>\<tau> \<up>\<^sub>\<tau> n (k - k') U]\<^sub>\<tau>"
apply (induct T arbitrary: k k')
apply simp_all
apply arith
done
lemma liftT_substT_Top [simp]:
"k \<le> k' \<Longrightarrow> \<up>\<^sub>\<tau> n k' (T[k \<mapsto>\<^sub>\<tau> Top]\<^sub>\<tau>) = \<up>\<^sub>\<tau> n (Suc k') T[k \<mapsto>\<^sub>\<tau> Top]\<^sub>\<tau>"
apply (induct T arbitrary: k k')
apply simp_all
apply arith
done
lemma liftT_substT_strange:
"\<up>\<^sub>\<tau> n k T[n + k \<mapsto>\<^sub>\<tau> U]\<^sub>\<tau> = \<up>\<^sub>\<tau> n (Suc k) T[k \<mapsto>\<^sub>\<tau> \<up>\<^sub>\<tau> n 0 U]\<^sub>\<tau>"
apply (induct T arbitrary: n k)
apply simp_all
apply (thin_tac "\<And>x. PROP P x" for P :: "_ \<Rightarrow> prop")
apply (drule_tac x=n in meta_spec)
apply (drule_tac x="Suc k" in meta_spec)
apply simp
done
lemma lift_lift [simp]:
"k \<le> k' \<Longrightarrow> k' \<le> k + n \<Longrightarrow> \<up> n' k' (\<up> n k t) = \<up> (n + n') k t"
by (induct t arbitrary: k k') simp_all
lemma substT_substT:
"i \<le> j \<Longrightarrow> T[Suc j \<mapsto>\<^sub>\<tau> V]\<^sub>\<tau>[i \<mapsto>\<^sub>\<tau> U[j - i \<mapsto>\<^sub>\<tau> V]\<^sub>\<tau>]\<^sub>\<tau> = T[i \<mapsto>\<^sub>\<tau> U]\<^sub>\<tau>[j \<mapsto>\<^sub>\<tau> V]\<^sub>\<tau>"
apply (induct T arbitrary: i j U V)
apply (simp_all add: diff_Suc split: nat.split)
apply (thin_tac "\<And>x. PROP P x" for P :: "_ \<Rightarrow> prop")
apply (drule_tac x="Suc i" in meta_spec)
apply (drule_tac x="Suc j" in meta_spec)
apply simp
done
subsection \<open>Well-formedness\<close>
text \<open>
\label{sec:wf}
The subtyping and typing judgements to be defined in \secref{sec:subtyping}
and \secref{sec:typing} may only operate on types and contexts that
are well-formed. Intuitively, a type @{term T} is well-formed with respect to a
context @{term \<Gamma>}, if all variables occurring in it are defined in @{term \<Gamma>}.
More precisely, if @{term T} contains a type variable @{term "TVar i"}, then
the @{term i}th element of @{term \<Gamma>} must exist and have the form @{term "TVarB U"}.
\<close>
inductive
well_formed :: "env \<Rightarrow> type \<Rightarrow> bool" ("_ \<turnstile>\<^sub>w\<^sub>f _" [50, 50] 50)
where
wf_TVar: "\<Gamma>\<langle>i\<rangle> = \<lfloor>TVarB T\<rfloor> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f TVar i"
| wf_Top: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f Top"
| wf_arrow: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f U \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<rightarrow> U"
| wf_all: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<Longrightarrow> TVarB T \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f U \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f (\<forall><:T. U)"
text \<open>
A context @{term "\<Gamma>"} is well-formed, if all types occurring in it only refer to type variables
declared ``further to the right'':
\<close>
inductive
well_formedE :: "env \<Rightarrow> bool" ("_ \<turnstile>\<^sub>w\<^sub>f" [50] 50)
and well_formedB :: "env \<Rightarrow> binding \<Rightarrow> bool" ("_ \<turnstile>\<^sub>w\<^sub>f\<^sub>B _" [50, 50] 50)
where
"\<Gamma> \<turnstile>\<^sub>w\<^sub>f\<^sub>B B \<equiv> \<Gamma> \<turnstile>\<^sub>w\<^sub>f type_ofB B"
| wf_Nil: "[] \<turnstile>\<^sub>w\<^sub>f"
| wf_Cons: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f\<^sub>B B \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> B \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f"
text \<open>
The judgement \<open>\<Gamma> \<turnstile>\<^sub>w\<^sub>f\<^sub>B B\<close>, which denotes well-formedness of the binding @{term B}
with respect to context @{term \<Gamma>}, is just an abbreviation for \<open>\<Gamma> \<turnstile>\<^sub>w\<^sub>f type_ofB B\<close>.
We now present a number of properties of the well-formedness judgements that will be used
in the proofs in the following sections.
\<close>
inductive_cases well_formed_cases:
"\<Gamma> \<turnstile>\<^sub>w\<^sub>f TVar i"
"\<Gamma> \<turnstile>\<^sub>w\<^sub>f Top"
"\<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<rightarrow> U"
"\<Gamma> \<turnstile>\<^sub>w\<^sub>f (\<forall><:T. U)"
inductive_cases well_formedE_cases:
"B \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f"
lemma wf_TVarB: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> TVarB T \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f"
by (rule wf_Cons) simp_all
lemma wf_VarB: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> VarB T \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f"
by (rule wf_Cons) simp_all
lemma map_is_TVarb:
"map is_TVarB \<Gamma>' = map is_TVarB \<Gamma> \<Longrightarrow>
\<Gamma>\<langle>i\<rangle> = \<lfloor>TVarB T\<rfloor> \<Longrightarrow> \<exists>T. \<Gamma>'\<langle>i\<rangle> = \<lfloor>TVarB T\<rfloor>"
apply (induct \<Gamma> arbitrary: \<Gamma>' T i)
apply simp
apply (auto split: nat.split_asm)
apply (case_tac z)
apply simp_all
done
text \<open>
A type that is well-formed in a context @{term \<Gamma>} is also well-formed in another context
@{term \<Gamma>'} that contains type variable bindings at the same positions as @{term \<Gamma>}:
\<close>
lemma wf_equallength:
assumes H: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f T"
shows "map is_TVarB \<Gamma>' = map is_TVarB \<Gamma> \<Longrightarrow> \<Gamma>' \<turnstile>\<^sub>w\<^sub>f T" using H
by (induct arbitrary: \<Gamma>') (auto intro: well_formed.intros dest: map_is_TVarb)
text \<open>
A well-formed context of the form @{term "\<Delta> @ B \<Colon> \<Gamma>"} remains well-formed if we replace
the binding @{term B} by another well-formed binding @{term B'}:
\<close>
lemma wfE_replace:
"\<Delta> @ B \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f\<^sub>B B' \<Longrightarrow> is_TVarB B' = is_TVarB B \<Longrightarrow>
\<Delta> @ B' \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f"
apply (induct \<Delta>)
apply simp
apply (erule wf_Cons)
apply (erule well_formedE_cases)
apply assumption
apply simp
apply (erule well_formedE_cases)
apply (rule wf_Cons)
apply (case_tac a)
apply simp
apply (rule wf_equallength)
apply assumption
apply simp
apply simp
apply (rule wf_equallength)
apply assumption
apply simp
apply simp
done
text \<open>
The following weakening lemmas can easily be proved by structural induction on
types and contexts:
\<close>
lemma wf_weaken:
assumes H: "\<Delta> @ \<Gamma> \<turnstile>\<^sub>w\<^sub>f T"
shows "\<up>\<^sub>e (Suc 0) 0 \<Delta> @ B \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<up>\<^sub>\<tau> (Suc 0) \<parallel>\<Delta>\<parallel> T"
using H
apply (induct "\<Delta> @ \<Gamma>" T arbitrary: \<Delta>)
apply simp_all
apply (rule conjI)
apply (rule impI)
apply (rule wf_TVar)
apply simp
apply (rule impI)
apply (rule wf_TVar)
apply (subgoal_tac "Suc i - \<parallel>\<Delta>\<parallel> = Suc (i - \<parallel>\<Delta>\<parallel>)")
apply simp
apply arith
apply (rule wf_Top)
apply (rule wf_arrow)
apply simp
apply simp
apply (rule wf_all)
apply simp
apply (drule_tac x="TVarB T \<Colon> \<Delta>" in meta_spec)
apply simp
done
lemma wf_weaken': "\<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<Longrightarrow> \<Delta> @ \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<up>\<^sub>\<tau> \<parallel>\<Delta>\<parallel> 0 T"
apply (induct \<Delta>)
apply simp_all
apply (drule_tac B=a in wf_weaken [of "[]", simplified])
apply simp
done
text \<open>
Intuitively, lemma \<open>wf_weaken\<close> states that a type @{term T} which is well-formed
in a context is still well-formed in a larger context, whereas lemma \<open>wfE_weaken\<close>
states that a well-formed context remains well-formed when extended with a
well-formed binding. Owing to the encoding of variables using de Bruijn
indices, the statements of the above lemmas involve additional lifting functions.
The typing judgement, which will be described in \secref{sec:typing}, involves
the lookup of variables in a context. It has already been pointed out earlier that each
entry in a context may only depend on types declared ``further to the right''. To ensure that
a type @{term T} stored at position @{term i} in an environment @{term \<Gamma>} is valid in the full
environment, as opposed to the smaller environment consisting only of the entries in
@{term \<Gamma>} at positions greater than @{term i}, we need to increment the indices of all
free type variables in @{term T} by @{term "Suc i"}:
\<close>
lemma wf_liftB:
assumes H: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f"
shows "\<Gamma>\<langle>i\<rangle> = \<lfloor>VarB T\<rfloor> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<up>\<^sub>\<tau> (Suc i) 0 T"
using H
apply (induct arbitrary: i)
apply simp
apply (simp split: nat.split_asm)
apply (frule_tac B="VarB T" in wf_weaken [of "[]", simplified])
apply simp+
apply (rename_tac nat)
apply (drule_tac x=nat in meta_spec)
apply simp
apply (frule_tac T="\<up>\<^sub>\<tau> (Suc nat) 0 T" in wf_weaken [of "[]", simplified])
apply simp
done
text \<open>
We also need lemmas stating that substitution of well-formed types preserves the well-formedness
of types and contexts:
\<close>
theorem wf_subst:
"\<Delta> @ B \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f U \<Longrightarrow> \<Delta>[0 \<mapsto>\<^sub>\<tau> U]\<^sub>e @ \<Gamma> \<turnstile>\<^sub>w\<^sub>f T[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> U]\<^sub>\<tau>"
apply (induct T arbitrary: \<Delta>)
apply simp_all
apply (rule conjI)
apply (rule impI)
apply (drule_tac \<Gamma>=\<Gamma> and \<Delta>="\<Delta>[0 \<mapsto>\<^sub>\<tau> U]\<^sub>e" in wf_weaken')
apply simp
apply (rule impI conjI)+
apply (erule well_formed_cases)
apply (rule wf_TVar)
apply (simp split: nat.split_asm)
apply (rename_tac nat \<Delta> T nata)
apply (subgoal_tac "\<parallel>\<Delta>\<parallel> \<le> nat - Suc 0")
apply (subgoal_tac "nat - Suc \<parallel>\<Delta>\<parallel> = nata")
apply (simp (no_asm_simp))
apply arith
apply arith
apply (rule impI)
apply (erule well_formed_cases)
apply (rule wf_TVar)
apply simp
apply (rule wf_Top)
apply (erule well_formed_cases)
apply (rule wf_arrow)
apply simp+
apply (erule well_formed_cases)
apply (rule wf_all)
apply simp
apply (thin_tac "\<And>x. PROP P x" for P :: "_ \<Rightarrow> prop")
apply (drule_tac x="TVarB T1 \<Colon> \<Delta>" in meta_spec)
apply simp
done
theorem wfE_subst: "\<Delta> @ B \<Colon> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f U \<Longrightarrow> \<Delta>[0 \<mapsto>\<^sub>\<tau> U]\<^sub>e @ \<Gamma> \<turnstile>\<^sub>w\<^sub>f"
apply (induct \<Delta>)
apply simp
apply (erule well_formedE_cases)
apply assumption
apply simp
apply (case_tac a)
apply (erule well_formedE_cases)
apply (rule wf_Cons)
apply simp
apply (rule wf_subst)
apply assumption+
apply simp
apply (erule well_formedE_cases)
apply (rule wf_Cons)
apply simp
apply (rule wf_subst)
apply assumption+
done
subsection \<open>Subtyping\<close>
text \<open>
\label{sec:subtyping}
We now come to the definition of the subtyping judgement \<open>\<Gamma> \<turnstile> T <: U\<close>.
\<close>
inductive
subtyping :: "env \<Rightarrow> type \<Rightarrow> type \<Rightarrow> bool" ("_ \<turnstile> _ <: _" [50, 50, 50] 50)
where
SA_Top: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f S \<Longrightarrow> \<Gamma> \<turnstile> S <: Top"
| SA_refl_TVar: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f TVar i \<Longrightarrow> \<Gamma> \<turnstile> TVar i <: TVar i"
| SA_trans_TVar: "\<Gamma>\<langle>i\<rangle> = \<lfloor>TVarB U\<rfloor> \<Longrightarrow>
\<Gamma> \<turnstile> \<up>\<^sub>\<tau> (Suc i) 0 U <: T \<Longrightarrow> \<Gamma> \<turnstile> TVar i <: T"
| SA_arrow: "\<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1 \<Longrightarrow> \<Gamma> \<turnstile> S\<^sub>2 <: T\<^sub>2 \<Longrightarrow> \<Gamma> \<turnstile> S\<^sub>1 \<rightarrow> S\<^sub>2 <: T\<^sub>1 \<rightarrow> T\<^sub>2"
| SA_all: "\<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1 \<Longrightarrow> TVarB T\<^sub>1 \<Colon> \<Gamma> \<turnstile> S\<^sub>2 <: T\<^sub>2 \<Longrightarrow>
\<Gamma> \<turnstile> (\<forall><:S\<^sub>1. S\<^sub>2) <: (\<forall><:T\<^sub>1. T\<^sub>2)"
text \<open>
The rules \<open>SA_Top\<close> and \<open>SA_refl_TVar\<close>, which appear at the leaves of
the derivation tree for a judgement @{term "\<Gamma> \<turnstile> T <: U"}, contain additional
side conditions ensuring the well-formedness of the contexts and types involved.
In order for the rule \<open>SA_trans_TVar\<close> to be applicable, the context @{term \<Gamma>}
must be of the form \mbox{@{term "\<Gamma>\<^sub>1 @ B \<Colon> \<Gamma>\<^sub>2"}}, where @{term "\<Gamma>\<^sub>1"} has the length @{term i}.
Since the indices of variables in @{term B} can only refer to variables defined in
@{term "\<Gamma>\<^sub>2"}, they have to be incremented by @{term "Suc i"} to ensure that they point
to the right variables in the larger context \<open>\<Gamma>\<close>.
\<close>
lemma wf_subtype_env:
assumes PQ: "\<Gamma> \<turnstile> P <: Q"
shows "\<Gamma> \<turnstile>\<^sub>w\<^sub>f" using PQ
by induct assumption+
lemma wf_subtype:
assumes PQ: "\<Gamma> \<turnstile> P <: Q"
shows "\<Gamma> \<turnstile>\<^sub>w\<^sub>f P \<and> \<Gamma> \<turnstile>\<^sub>w\<^sub>f Q" using PQ
by induct (auto intro: well_formed.intros elim!: wf_equallength)
lemma wf_subtypeE:
assumes H: "\<Gamma> \<turnstile> T <: U"
and H': "\<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f U \<Longrightarrow> P"
shows "P"
apply (rule H')
apply (rule wf_subtype_env)
apply (rule H)
apply (rule wf_subtype [OF H, THEN conjunct1])
apply (rule wf_subtype [OF H, THEN conjunct2])
done
text \<open>
By induction on the derivation of @{term "\<Gamma> \<turnstile> T <: U"}, it can easily be shown
that all types and contexts occurring in a subtyping judgement must be well-formed:
\<close>
lemma wf_subtype_conj:
"\<Gamma> \<turnstile> T <: U \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<and> \<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<and> \<Gamma> \<turnstile>\<^sub>w\<^sub>f U"
by (erule wf_subtypeE) iprover
text \<open>
By induction on types, we can prove that the subtyping relation is reflexive:
\<close>
lemma subtype_refl: \<comment> \<open>A.1\<close>
"\<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f T \<Longrightarrow> \<Gamma> \<turnstile> T <: T"
by (induct T arbitrary: \<Gamma>) (blast intro:
subtyping.intros wf_Nil wf_TVarB elim: well_formed_cases)+
text \<open>
The weakening lemma for the subtyping relation is proved in two steps:
by induction on the derivation of the subtyping relation, we first prove
that inserting a single type into the context preserves subtyping:
\<close>
lemma subtype_weaken:
assumes H: "\<Delta> @ \<Gamma> \<turnstile> P <: Q"
and wf: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f\<^sub>B B"
shows "\<up>\<^sub>e 1 0 \<Delta> @ B \<Colon> \<Gamma> \<turnstile> \<up>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> P <: \<up>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> Q" using H
proof (induct "\<Delta> @ \<Gamma>" P Q arbitrary: \<Delta>)
case SA_Top
with wf show ?case
by (auto intro: subtyping.SA_Top wfE_weaken wf_weaken)
next
case SA_refl_TVar
with wf show ?case
by (auto intro!: subtyping.SA_refl_TVar wfE_weaken dest: wf_weaken)
next
case (SA_trans_TVar i U T)
thus ?case
proof (cases "i < \<parallel>\<Delta>\<parallel>")
case True
with SA_trans_TVar
have "(\<up>\<^sub>e 1 0 \<Delta> @ B \<Colon> \<Gamma>)\<langle>i\<rangle> = \<lfloor>TVarB (\<up>\<^sub>\<tau> 1 (\<parallel>\<Delta>\<parallel> - Suc i) U)\<rfloor>"
by simp
moreover from True SA_trans_TVar
have "\<up>\<^sub>e 1 0 \<Delta> @ B \<Colon> \<Gamma> \<turnstile>
\<up>\<^sub>\<tau> (Suc i) 0 (\<up>\<^sub>\<tau> 1 (\<parallel>\<Delta>\<parallel> - Suc i) U) <: \<up>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> T"
by simp
ultimately have "\<up>\<^sub>e 1 0 \<Delta> @ B \<Colon> \<Gamma> \<turnstile> TVar i <: \<up>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> T"
by (rule subtyping.SA_trans_TVar)
with True show ?thesis by simp
next
case False
then have "Suc i - \<parallel>\<Delta>\<parallel> = Suc (i - \<parallel>\<Delta>\<parallel>)" by arith
with False SA_trans_TVar have "(\<up>\<^sub>e 1 0 \<Delta> @ B \<Colon> \<Gamma>)\<langle>Suc i\<rangle> = \<lfloor>TVarB U\<rfloor>"
by simp
moreover from False SA_trans_TVar
have "\<up>\<^sub>e 1 0 \<Delta> @ B \<Colon> \<Gamma> \<turnstile> \<up>\<^sub>\<tau> (Suc (Suc i)) 0 U <: \<up>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> T"
by simp
ultimately have "\<up>\<^sub>e 1 0 \<Delta> @ B \<Colon> \<Gamma> \<turnstile> TVar (Suc i) <: \<up>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> T"
by (rule subtyping.SA_trans_TVar)
with False show ?thesis by simp
qed
next
case SA_arrow
thus ?case by simp (iprover intro: subtyping.SA_arrow)
next
case (SA_all T\<^sub>1 S\<^sub>1 S\<^sub>2 T\<^sub>2 \<Delta>)
with SA_all(4) [of "TVarB T\<^sub>1 \<Colon> \<Delta>"]
show ?case by simp (iprover intro: subtyping.SA_all)
qed
text \<open>
All cases are trivial, except for the \<open>SA_trans_TVar\<close> case, which
requires a case distinction on whether the index of the variable is smaller
than @{term "\<parallel>\<Delta>\<parallel>"}.
The stronger result that appending a new context @{term \<Delta>} to a context
@{term \<Gamma>} preserves subtyping can be proved by induction on @{term \<Delta>},
using the previous result in the induction step:
\<close>
lemma subtype_weaken': \<comment> \<open>A.2\<close>
"\<Gamma> \<turnstile> P <: Q \<Longrightarrow> \<Delta> @ \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Delta> @ \<Gamma> \<turnstile> \<up>\<^sub>\<tau> \<parallel>\<Delta>\<parallel> 0 P <: \<up>\<^sub>\<tau> \<parallel>\<Delta>\<parallel> 0 Q"
apply (induct \<Delta>)
apply simp_all
apply (erule well_formedE_cases)
apply simp
apply (drule_tac B="a" and \<Gamma>="\<Delta> @ \<Gamma>" in subtype_weaken [of "[]", simplified])
apply simp_all
done
text \<open>
An unrestricted transitivity rule has the disadvantage that it can
be applied in any situation. In order to make the above definition of the
subtyping relation {\it syntax-directed}, the transitivity rule \<open>SA_trans_TVar\<close>
is restricted to the case where the type on the left-hand side of the \<open><:\<close>
operator is a variable. However, the unrestricted transitivity rule
can be derived from this definition.
In order for the proof to go through, we have to simultaneously prove
another property called {\it narrowing}.
The two properties are proved by nested induction. The outer induction
is on the size of the type @{term Q}, whereas the two inner inductions for
proving transitivity and narrowing are on the derivation of the
subtyping judgements. The transitivity property is needed in the proof of
narrowing, which is by induction on the derivation of \mbox{@{term "\<Delta> @ TVarB Q \<Colon> \<Gamma> \<turnstile> M <: N"}}.
In the case corresponding to the rule \<open>SA_trans_TVar\<close>, we must prove
\mbox{@{term "\<Delta> @ TVarB P \<Colon> \<Gamma> \<turnstile> TVar i <: T"}}. The only interesting case
is the one where @{term "i = \<parallel>\<Delta>\<parallel>"}. By induction hypothesis, we know that
@{term "\<Delta> @ TVarB P \<Colon> \<Gamma> \<turnstile> \<up>\<^sub>\<tau> (i+1) 0 Q <: T"} and
@{term "(\<Delta> @ TVarB Q \<Colon> \<Gamma>)\<langle>i\<rangle> = \<lfloor>TVarB Q\<rfloor>"}.
By assumption, we have @{term "\<Gamma> \<turnstile> P <: Q"} and hence
\mbox{@{term "\<Delta> @ TVarB P \<Colon> \<Gamma> \<turnstile> \<up>\<^sub>\<tau> (i+1) 0 P <: \<up>\<^sub>\<tau> (i+1) 0 Q"}} by weakening.
Since @{term "\<up>\<^sub>\<tau> (i+1) 0 Q"} has the same size as @{term Q}, we can use
the transitivity property, which yields
@{term "\<Delta> @ TVarB P \<Colon> \<Gamma> \<turnstile> \<up>\<^sub>\<tau> (i+1) 0 P <: T"}. The claim then follows
easily by an application of \<open>SA_trans_TVar\<close>.
\<close>
text \<open>
In the proof of the preservation theorem presented in \secref{sec:evaluation},
we will also need a substitution theorem, which is proved by
induction on the subtyping derivation:
\<close>
lemma substT_subtype: \<comment> \<open>A.10\<close>
assumes H: "\<Delta> @ TVarB Q \<Colon> \<Gamma> \<turnstile> S <: T"
shows "\<Gamma> \<turnstile> P <: Q \<Longrightarrow> \<Delta>[0 \<mapsto>\<^sub>\<tau> P]\<^sub>e @ \<Gamma> \<turnstile> S[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> P]\<^sub>\<tau> <: T[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> P]\<^sub>\<tau>"
using H
apply (induct "\<Delta> @ TVarB Q \<Colon> \<Gamma>" S T arbitrary: \<Delta>)
apply simp_all
apply (rule SA_Top)
apply (rule wfE_subst)
apply assumption
apply (erule wf_subtypeE)
apply assumption
apply (rule wf_subst)
apply assumption
apply (erule wf_subtypeE)
apply assumption
apply (rule impI conjI)+
apply (rule subtype_refl)
apply (rule wfE_subst)
apply assumption
apply (erule wf_subtypeE)
apply assumption
apply (erule wf_subtypeE)
apply (drule_tac T=P and \<Delta>="\<Delta>[0 \<mapsto>\<^sub>\<tau> P]\<^sub>e" in wf_weaken')
apply simp
apply (rule conjI impI)+
apply (rule SA_refl_TVar)
apply (rule wfE_subst)
apply assumption
apply (erule wf_subtypeE)
apply assumption
apply (erule wf_subtypeE)
apply (drule wf_subst)
apply assumption
apply simp
apply (rule impI)
apply (rule SA_refl_TVar)
apply (rule wfE_subst)
apply assumption
apply (erule wf_subtypeE)
apply assumption
apply (erule wf_subtypeE)
apply (drule wf_subst)
apply assumption
apply simp
apply (rule conjI impI)+
apply simp
apply (drule_tac \<Gamma>=\<Gamma> and \<Delta>="\<Delta>[0 \<mapsto>\<^sub>\<tau> P]\<^sub>e" in subtype_weaken')
apply (erule wf_subtypeE)+
apply assumption
apply simp
apply (rule subtype_trans(1))
apply assumption+
apply (rule conjI impI)+
apply (rule SA_trans_TVar)
apply (simp split: nat.split_asm)
apply (subgoal_tac "\<parallel>\<Delta>\<parallel> \<le> i - Suc 0")
apply (rename_tac nat)
apply (subgoal_tac "i - Suc \<parallel>\<Delta>\<parallel> = nat")
apply (simp (no_asm_simp))
apply arith
apply arith
apply simp
apply (rule impI)
apply (rule SA_trans_TVar)
apply (simp split: nat.split_asm)
apply (subgoal_tac "Suc (\<parallel>\<Delta>\<parallel> - Suc 0) = \<parallel>\<Delta>\<parallel>")
apply (simp (no_asm_simp))
apply arith
apply (rule SA_arrow)
apply simp+
apply (rule SA_all)
apply simp
apply (drule_tac x="TVarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
done
lemma subst_subtype:
assumes H: "\<Delta> @ VarB V \<Colon> \<Gamma> \<turnstile> T <: U"
shows "\<down>\<^sub>e 1 0 \<Delta> @ \<Gamma> \<turnstile> \<down>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> T <: \<down>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> U"
using H
apply (induct "\<Delta> @ VarB V \<Colon> \<Gamma>" T U arbitrary: \<Delta>)
apply simp_all
apply (rule SA_Top)
apply (rule wfE_subst)
apply assumption
apply (rule wf_Top)
apply (rule wf_subst)
apply assumption
apply (rule wf_Top)
apply (rule impI conjI)+
apply (rule SA_Top)
apply (rule wfE_subst)
apply assumption
apply (rule wf_Top)+
apply (rule conjI impI)+
apply (rule SA_refl_TVar)
apply (rule wfE_subst)
apply assumption
apply (rule wf_Top)
apply (drule wf_subst)
apply (rule wf_Top)
apply simp
apply (rule impI)
apply (rule SA_refl_TVar)
apply (rule wfE_subst)
apply assumption
apply (rule wf_Top)
apply (drule wf_subst)
apply (rule wf_Top)
apply simp
apply (rule conjI impI)+
apply simp
apply (rule conjI impI)+
apply (simp split: nat.split_asm)
apply (rule SA_trans_TVar)
apply (subgoal_tac "\<parallel>\<Delta>\<parallel> \<le> i - Suc 0")
apply (rename_tac nat)
apply (subgoal_tac "i - Suc \<parallel>\<Delta>\<parallel> = nat")
apply (simp (no_asm_simp))
apply arith
apply arith
apply simp
apply (rule impI)
apply (rule SA_trans_TVar)
apply simp
apply (subgoal_tac "0 < \<parallel>\<Delta>\<parallel>")
apply simp
apply arith
apply (rule SA_arrow)
apply simp+
apply (rule SA_all)
apply simp
apply (drule_tac x="TVarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
done
subsection \<open>Typing\<close>
text \<open>
\label{sec:typing}
We are now ready to give a definition of the typing judgement \<open>\<Gamma> \<turnstile> t : T\<close>.
\<close>
inductive
typing :: "env \<Rightarrow> trm \<Rightarrow> type \<Rightarrow> bool" ("_ \<turnstile> _ : _" [50, 50, 50] 50)
where
T_Var: "\<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Gamma>\<langle>i\<rangle> = \<lfloor>VarB U\<rfloor> \<Longrightarrow> T = \<up>\<^sub>\<tau> (Suc i) 0 U \<Longrightarrow> \<Gamma> \<turnstile> Var i : T"
| T_Abs: "VarB T\<^sub>1 \<Colon> \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2 \<Longrightarrow> \<Gamma> \<turnstile> (\<lambda>:T\<^sub>1. t\<^sub>2) : T\<^sub>1 \<rightarrow> \<down>\<^sub>\<tau> 1 0 T\<^sub>2"
| T_App: "\<Gamma> \<turnstile> t\<^sub>1 : T\<^sub>1\<^sub>1 \<rightarrow> T\<^sub>1\<^sub>2 \<Longrightarrow> \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>1\<^sub>1 \<Longrightarrow> \<Gamma> \<turnstile> t\<^sub>1 \<bullet> t\<^sub>2 : T\<^sub>1\<^sub>2"
| T_TAbs: "TVarB T\<^sub>1 \<Colon> \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2 \<Longrightarrow> \<Gamma> \<turnstile> (\<lambda><:T\<^sub>1. t\<^sub>2) : (\<forall><:T\<^sub>1. T\<^sub>2)"
| T_TApp: "\<Gamma> \<turnstile> t\<^sub>1 : (\<forall><:T\<^sub>1\<^sub>1. T\<^sub>1\<^sub>2) \<Longrightarrow> \<Gamma> \<turnstile> T\<^sub>2 <: T\<^sub>1\<^sub>1 \<Longrightarrow>
\<Gamma> \<turnstile> t\<^sub>1 \<bullet>\<^sub>\<tau> T\<^sub>2 : T\<^sub>1\<^sub>2[0 \<mapsto>\<^sub>\<tau> T\<^sub>2]\<^sub>\<tau>"
| T_Sub: "\<Gamma> \<turnstile> t : S \<Longrightarrow> \<Gamma> \<turnstile> S <: T \<Longrightarrow> \<Gamma> \<turnstile> t : T"
text \<open>
Note that in the rule \<open>T_Var\<close>, the indices of the type @{term U} looked up in
the context @{term \<Gamma>} need to be incremented in order for the type to be well-formed
with respect to @{term \<Gamma>}. In the rule \<open>T_Abs\<close>, the type @{term "T\<^sub>2"} of the
abstraction body @{term "t\<^sub>2"} may not contain the variable with index \<open>0\<close>,
since it is a term variable. To compensate for the disappearance of the context
element @{term "VarB T\<^sub>1"} in the conclusion of thy typing rule, the indices of all
free type variables in @{term "T\<^sub>2"} have to be decremented by \<open>1\<close>.
\<close>
theorem wf_typeE1:
assumes H: "\<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile>\<^sub>w\<^sub>f" using H
by induct (blast elim: well_formedE_cases)+
theorem wf_typeE2:
assumes H: "\<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile>\<^sub>w\<^sub>f T" using H
apply induct
apply simp
apply (rule wf_liftB)
apply assumption+
apply (drule wf_typeE1)+
apply (erule well_formedE_cases)+
apply (rule wf_arrow)
apply simp
apply simp
apply (rule wf_subst [of "[]", simplified])
apply assumption
apply (rule wf_Top)
apply (erule well_formed_cases)
apply assumption
apply (rule wf_all)
apply (drule wf_typeE1)
apply (erule well_formedE_cases)
apply simp
apply assumption
apply (erule well_formed_cases)
apply (rule wf_subst [of "[]", simplified])
apply assumption
apply (erule wf_subtypeE)
apply assumption
apply (erule wf_subtypeE)
apply assumption
done
text \<open>
Like for the subtyping judgement, we can again prove that all types and contexts
involved in a typing judgement are well-formed:
\<close>
lemma wf_type_conj: "\<Gamma> \<turnstile> t : T \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<and> \<Gamma> \<turnstile>\<^sub>w\<^sub>f T"
by (frule wf_typeE1, drule wf_typeE2) iprover
text \<open>
The narrowing theorem for the typing judgement states that replacing the type
of a variable in the context by a subtype preserves typability:
\<close>
lemma narrow_type: \<comment> \<open>A.7\<close>
assumes H: "\<Delta> @ TVarB Q \<Colon> \<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile> P <: Q \<Longrightarrow> \<Delta> @ TVarB P \<Colon> \<Gamma> \<turnstile> t : T"
using H
apply (induct "\<Delta> @ TVarB Q \<Colon> \<Gamma>" t T arbitrary: \<Delta>)
apply simp_all
apply (rule T_Var)
apply (erule wfE_replace)
apply (erule wf_subtypeE)
apply simp+
apply (case_tac "i < \<parallel>\<Delta>\<parallel>")
apply simp
apply (case_tac "i = \<parallel>\<Delta>\<parallel>")
apply simp
apply (simp split: nat.split nat.split_asm)+
apply (rule T_Abs [simplified])
apply (drule_tac x="VarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
apply (rule_tac T\<^sub>1\<^sub>1=T\<^sub>1\<^sub>1 in T_App)
apply simp+
apply (rule T_TAbs)
apply (drule_tac x="TVarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
apply (rule_tac T\<^sub>1\<^sub>1=T\<^sub>1\<^sub>1 in T_TApp)
apply simp
apply (rule subtype_trans(2))
apply assumption+
apply (rule_tac S=S in T_Sub)
apply simp
apply (rule subtype_trans(2))
apply assumption+
done
lemma subtype_refl':
assumes t: "\<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile> T <: T"
proof (rule subtype_refl)
from t show "\<Gamma> \<turnstile>\<^sub>w\<^sub>f" by (rule wf_typeE1)
from t show "\<Gamma> \<turnstile>\<^sub>w\<^sub>f T" by (rule wf_typeE2)
qed
lemma Abs_type: \<comment> \<open>A.13(1)\<close>
assumes H: "\<Gamma> \<turnstile> (\<lambda>:S. s) : T"
shows "\<Gamma> \<turnstile> T <: U \<rightarrow> U' \<Longrightarrow>
(\<And>S'. \<Gamma> \<turnstile> U <: S \<Longrightarrow> VarB S \<Colon> \<Gamma> \<turnstile> s : S' \<Longrightarrow>
\<Gamma> \<turnstile> \<down>\<^sub>\<tau> 1 0 S' <: U' \<Longrightarrow> P) \<Longrightarrow> P"
using H
proof (induct \<Gamma> "\<lambda>:S. s" T arbitrary: U U' S s P)
case (T_Abs T\<^sub>1 \<Gamma> t\<^sub>2 T\<^sub>2)
from \<open>\<Gamma> \<turnstile> T\<^sub>1 \<rightarrow> \<down>\<^sub>\<tau> 1 0 T\<^sub>2 <: U \<rightarrow> U'\<close>
obtain ty1: "\<Gamma> \<turnstile> U <: T\<^sub>1" and ty2: "\<Gamma> \<turnstile> \<down>\<^sub>\<tau> 1 0 T\<^sub>2 <: U'"
by cases simp_all
from ty1 \<open>VarB T\<^sub>1 \<Colon> \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2\<close> ty2
show ?case by (rule T_Abs)
next
case (T_Sub \<Gamma> S' T)
from \<open>\<Gamma> \<turnstile> S' <: T\<close> and \<open>\<Gamma> \<turnstile> T <: U \<rightarrow> U'\<close>
have "\<Gamma> \<turnstile> S' <: U \<rightarrow> U'" by (rule subtype_trans(1))
then show ?case
by (rule T_Sub) (rule T_Sub(5))
qed
lemma Abs_type':
assumes H: "\<Gamma> \<turnstile> (\<lambda>:S. s) : U \<rightarrow> U'"
and R: "\<And>S'. \<Gamma> \<turnstile> U <: S \<Longrightarrow> VarB S \<Colon> \<Gamma> \<turnstile> s : S' \<Longrightarrow>
\<Gamma> \<turnstile> \<down>\<^sub>\<tau> 1 0 S' <: U' \<Longrightarrow> P"
shows "P" using H subtype_refl' [OF H]
by (rule Abs_type) (rule R)
lemma TAbs_type: \<comment> \<open>A.13(2)\<close>
assumes H: "\<Gamma> \<turnstile> (\<lambda><:S. s) : T"
shows "\<Gamma> \<turnstile> T <: (\<forall><:U. U') \<Longrightarrow>
(\<And>S'. \<Gamma> \<turnstile> U <: S \<Longrightarrow> TVarB U \<Colon> \<Gamma> \<turnstile> s : S' \<Longrightarrow>
TVarB U \<Colon> \<Gamma> \<turnstile> S' <: U' \<Longrightarrow> P) \<Longrightarrow> P"
using H
proof (induct \<Gamma> "\<lambda><:S. s" T arbitrary: U U' S s P)
case (T_TAbs T\<^sub>1 \<Gamma> t\<^sub>2 T\<^sub>2)
from \<open>\<Gamma> \<turnstile> (\<forall><:T\<^sub>1. T\<^sub>2) <: (\<forall><:U. U')\<close>
obtain ty1: "\<Gamma> \<turnstile> U <: T\<^sub>1" and ty2: "TVarB U \<Colon> \<Gamma> \<turnstile> T\<^sub>2 <: U'"
by cases simp_all
from \<open>TVarB T\<^sub>1 \<Colon> \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2\<close>
have "TVarB U \<Colon> \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2" using ty1
by (rule narrow_type [of "[]", simplified])
with ty1 show ?case using ty2 by (rule T_TAbs)
next
case (T_Sub \<Gamma> S' T)
from \<open>\<Gamma> \<turnstile> S' <: T\<close> and \<open>\<Gamma> \<turnstile> T <: (\<forall><:U. U')\<close>
have "\<Gamma> \<turnstile> S' <: (\<forall><:U. U')" by (rule subtype_trans(1))
then show ?case
by (rule T_Sub) (rule T_Sub(5))
qed
lemma TAbs_type':
assumes H: "\<Gamma> \<turnstile> (\<lambda><:S. s) : (\<forall><:U. U')"
and R: "\<And>S'. \<Gamma> \<turnstile> U <: S \<Longrightarrow> TVarB U \<Colon> \<Gamma> \<turnstile> s : S' \<Longrightarrow>
TVarB U \<Colon> \<Gamma> \<turnstile> S' <: U' \<Longrightarrow> P"
shows "P" using H subtype_refl' [OF H]
by (rule TAbs_type) (rule R)
lemma T_eq: "\<Gamma> \<turnstile> t : T \<Longrightarrow> T = T' \<Longrightarrow> \<Gamma> \<turnstile> t : T'" by simp
text \<open>
The weakening theorem states that inserting a binding @{term B}
does not affect typing:
\<close>
lemma type_weaken:
assumes H: "\<Delta> @ \<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile>\<^sub>w\<^sub>f\<^sub>B B \<Longrightarrow>
\<up>\<^sub>e 1 0 \<Delta> @ B \<Colon> \<Gamma> \<turnstile> \<up> 1 \<parallel>\<Delta>\<parallel> t : \<up>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> T" using H
apply (induct "\<Delta> @ \<Gamma>" t T arbitrary: \<Delta>)
apply simp_all
apply (rule conjI)
apply (rule impI)
apply (rule T_Var)
apply (erule wfE_weaken)
apply simp+
apply (rule impI)
apply (rule T_Var)
apply (erule wfE_weaken)
apply assumption
apply (subgoal_tac "Suc i - \<parallel>\<Delta>\<parallel> = Suc (i - \<parallel>\<Delta>\<parallel>)")
apply simp
apply arith
apply (rule refl)
apply (rule T_Abs [THEN T_eq])
apply (drule_tac x="VarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
apply simp
apply (rule_tac T\<^sub>1\<^sub>1="\<up>\<^sub>\<tau> (Suc 0) \<parallel>\<Delta>\<parallel> T\<^sub>1\<^sub>1" in T_App)
apply simp
apply simp
apply (rule T_TAbs)
apply (drule_tac x="TVarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
apply (erule_tac T_TApp [THEN T_eq])
apply (drule subtype_weaken)
apply simp+
apply (case_tac \<Delta>)
apply (simp add: liftT_substT_strange [of _ 0, simplified])+
apply (rule_tac S="\<up>\<^sub>\<tau> (Suc 0) \<parallel>\<Delta>\<parallel> S" in T_Sub)
apply simp
apply (drule subtype_weaken)
apply simp+
done
text \<open>
We can strengthen this result, so as to mean that concatenating a new context
@{term \<Delta>} to the context @{term \<Gamma>} preserves typing:
\<close>
lemma type_weaken': \<comment> \<open>A.5(6)\<close>
"\<Gamma> \<turnstile> t : T \<Longrightarrow> \<Delta> @ \<Gamma> \<turnstile>\<^sub>w\<^sub>f \<Longrightarrow> \<Delta> @ \<Gamma> \<turnstile> \<up> \<parallel>\<Delta>\<parallel> 0 t : \<up>\<^sub>\<tau> \<parallel>\<Delta>\<parallel> 0 T"
apply (induct \<Delta>)
apply simp
apply simp
apply (erule well_formedE_cases)
apply simp
apply (drule_tac B=a in type_weaken [of "[]", simplified])
apply simp+
done
text \<open>
This property is proved by structural induction on the context @{term \<Delta>},
using the previous result in the induction step. In the proof of the preservation
theorem, we will need two substitution theorems for term and type variables,
both of which are proved by induction on the typing derivation.
Since term and type variables are stored in the same context, we again have to
decrement the free type variables in @{term \<Delta>} and @{term T} by \<open>1\<close>
in the substitution rule for term variables in order to compensate for the
disappearance of the variable.
\<close>
theorem subst_type: \<comment> \<open>A.8\<close>
assumes H: "\<Delta> @ VarB U \<Colon> \<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile> u : U \<Longrightarrow>
\<down>\<^sub>e 1 0 \<Delta> @ \<Gamma> \<turnstile> t[\<parallel>\<Delta>\<parallel> \<mapsto> u] : \<down>\<^sub>\<tau> 1 \<parallel>\<Delta>\<parallel> T" using H
apply (induct "\<Delta> @ VarB U \<Colon> \<Gamma>" t T arbitrary: \<Delta>)
apply simp
apply (rule conjI)
apply (rule impI)
apply simp
apply (drule_tac \<Delta>="\<Delta>[0 \<mapsto>\<^sub>\<tau> Top]\<^sub>e" in type_weaken')
apply (rule wfE_subst)
apply assumption
apply (rule wf_Top)
apply simp
apply (rule impI conjI)+
apply (simp split: nat.split_asm)
apply (rule T_Var)
apply (erule wfE_subst)
apply (rule wf_Top)
apply (subgoal_tac "\<parallel>\<Delta>\<parallel> \<le> i - Suc 0")
apply (rename_tac nat)
apply (subgoal_tac "i - Suc \<parallel>\<Delta>\<parallel> = nat")
apply (simp (no_asm_simp))
apply arith
apply arith
apply simp
apply (rule impI)
apply (rule T_Var)
apply (erule wfE_subst)
apply (rule wf_Top)
apply simp
apply (subgoal_tac "Suc (\<parallel>\<Delta>\<parallel> - Suc 0) = \<parallel>\<Delta>\<parallel>")
apply (simp (no_asm_simp))
apply arith
apply simp
apply (drule_tac x="VarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply (rule T_Abs [THEN T_eq])
apply simp
apply (simp add: substT_substT [symmetric])
apply simp
apply (rule_tac T\<^sub>1\<^sub>1="T\<^sub>1\<^sub>1[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> Top]\<^sub>\<tau>" in T_App)
apply simp+
apply (rule T_TAbs)
apply (drule_tac x="TVarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
apply simp
apply (rule T_TApp [THEN T_eq])
apply simp
apply (rule subst_subtype [simplified])
apply assumption
apply (simp add: substT_substT [symmetric])
apply (rule_tac S="S[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> Top]\<^sub>\<tau>" in T_Sub)
apply simp
apply simp
apply (rule subst_subtype [simplified])
apply assumption
done
theorem substT_type: \<comment> \<open>A.11\<close>
assumes H: "\<Delta> @ TVarB Q \<Colon> \<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile> P <: Q \<Longrightarrow>
\<Delta>[0 \<mapsto>\<^sub>\<tau> P]\<^sub>e @ \<Gamma> \<turnstile> t[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> P] : T[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> P]\<^sub>\<tau>" using H
apply (induct "\<Delta> @ TVarB Q \<Colon> \<Gamma>" t T arbitrary: \<Delta>)
apply simp_all
apply (rule impI conjI)+
apply simp
apply (rule T_Var)
apply (erule wfE_subst)
apply (erule wf_subtypeE)
apply assumption
apply (simp split: nat.split_asm)
apply (subgoal_tac "\<parallel>\<Delta>\<parallel> \<le> i - Suc 0")
apply (rename_tac nat)
apply (subgoal_tac "i - Suc \<parallel>\<Delta>\<parallel> = nat")
apply (simp (no_asm_simp))
apply arith
apply arith
apply simp
apply (rule impI)
apply (case_tac "i = \<parallel>\<Delta>\<parallel>")
apply simp
apply (rule T_Var)
apply (erule wfE_subst)
apply (erule wf_subtypeE)
apply assumption
apply simp
apply (subgoal_tac "i < \<parallel>\<Delta>\<parallel>")
apply (subgoal_tac "Suc (\<parallel>\<Delta>\<parallel> - Suc 0) = \<parallel>\<Delta>\<parallel>")
apply (simp (no_asm_simp))
apply arith
apply arith
apply (rule T_Abs [THEN T_eq])
apply (drule_tac x="VarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
apply (simp add: substT_substT [symmetric])
apply (rule_tac T\<^sub>1\<^sub>1="T\<^sub>1\<^sub>1[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> P]\<^sub>\<tau>" in T_App)
apply simp+
apply (rule T_TAbs)
apply (drule_tac x="TVarB T\<^sub>1 \<Colon> \<Delta>" in meta_spec)
apply simp
apply (rule T_TApp [THEN T_eq])
apply simp
apply (rule substT_subtype)
apply assumption
apply assumption
apply (simp add: substT_substT [symmetric])
apply (rule_tac S="S[\<parallel>\<Delta>\<parallel> \<mapsto>\<^sub>\<tau> P]\<^sub>\<tau>" in T_Sub)
apply simp
apply (rule substT_subtype)
apply assumption
apply assumption
done
subsection \<open>Evaluation\<close>
text \<open>
\label{sec:evaluation}
For the formalization of the evaluation strategy, it is useful to first define
a set of {\it canonical values} that are not evaluated any further. The canonical
values of call-by-value \fsub{} are exactly the abstractions over term and type variables:
\<close>
inductive_set
"value" :: "trm set"
where
Abs: "(\<lambda>:T. t) \<in> value"
| TAbs: "(\<lambda><:T. t) \<in> value"
text \<open>
The notion of a @{term value} is now used in the defintion of the evaluation
relation \mbox{\<open>t \<longmapsto> t'\<close>}. There are several ways for defining this evaluation
relation: Aydemir et al.\ \cite{PoplMark} advocate the use of {\it evaluation
contexts} that allow to separate the description of the ``immediate'' reduction rules,
i.e.\ $\beta$-reduction, from the description of the context in which these reductions
may occur in. The rationale behind this approach is to keep the formalization more modular.
We will take a closer look at this style of presentation in section
\secref{sec:evaluation-ctxt}. For the rest of this section, we will use a different
approach: both the ``immediate'' reductions and the reduction context are described
within the same inductive definition, where the context is described by additional
congruence rules.
\<close>
inductive
eval :: "trm \<Rightarrow> trm \<Rightarrow> bool" (infixl "\<longmapsto>" 50)
where
E_Abs: "v\<^sub>2 \<in> value \<Longrightarrow> (\<lambda>:T\<^sub>1\<^sub>1. t\<^sub>1\<^sub>2) \<bullet> v\<^sub>2 \<longmapsto> t\<^sub>1\<^sub>2[0 \<mapsto> v\<^sub>2]"
| E_TAbs: "(\<lambda><:T\<^sub>1\<^sub>1. t\<^sub>1\<^sub>2) \<bullet>\<^sub>\<tau> T\<^sub>2 \<longmapsto> t\<^sub>1\<^sub>2[0 \<mapsto>\<^sub>\<tau> T\<^sub>2]"
| E_App1: "t \<longmapsto> t' \<Longrightarrow> t \<bullet> u \<longmapsto> t' \<bullet> u"
| E_App2: "v \<in> value \<Longrightarrow> t \<longmapsto> t' \<Longrightarrow> v \<bullet> t \<longmapsto> v \<bullet> t'"
| E_TApp: "t \<longmapsto> t' \<Longrightarrow> t \<bullet>\<^sub>\<tau> T \<longmapsto> t' \<bullet>\<^sub>\<tau> T"
text \<open>
Here, the rules \<open>E_Abs\<close> and \<open>E_TAbs\<close> describe the ``immediate'' reductions,
whereas \<open>E_App1\<close>, \<open>E_App2\<close>, and \<open>E_TApp\<close> are additional congruence
rules describing reductions in a context. The most important theorems of this section
are the {\it preservation} theorem, stating that the reduction of a well-typed term
does not change its type, and the {\it progress} theorem, stating that reduction of
a well-typed term does not ``get stuck'' -- in other words, every well-typed, closed
term @{term t} is either a value, or there is a term @{term t'} to which @{term t}
can be reduced. The preservation theorem
is proved by induction on the derivation of @{term "\<Gamma> \<turnstile> t : T"}, followed by a case
distinction on the last rule used in the derivation of @{term "t \<longmapsto> t'"}.
\<close>
theorem preservation: \<comment> \<open>A.20\<close>
assumes H: "\<Gamma> \<turnstile> t : T"
shows "t \<longmapsto> t' \<Longrightarrow> \<Gamma> \<turnstile> t' : T" using H
proof (induct arbitrary: t')
case (T_Var \<Gamma> i U T t')
from \<open>Var i \<longmapsto> t'\<close>
show ?case by cases
next
case (T_Abs T\<^sub>1 \<Gamma> t\<^sub>2 T\<^sub>2 t')
from \<open>(\<lambda>:T\<^sub>1. t\<^sub>2) \<longmapsto> t'\<close>
show ?case by cases
next
case (T_App \<Gamma> t\<^sub>1 T\<^sub>1\<^sub>1 T\<^sub>1\<^sub>2 t\<^sub>2 t')
from \<open>t\<^sub>1 \<bullet> t\<^sub>2 \<longmapsto> t'\<close>
show ?case
proof cases
case (E_Abs T\<^sub>1\<^sub>1' t\<^sub>1\<^sub>2)
with T_App have "\<Gamma> \<turnstile> (\<lambda>:T\<^sub>1\<^sub>1'. t\<^sub>1\<^sub>2) : T\<^sub>1\<^sub>1 \<rightarrow> T\<^sub>1\<^sub>2" by simp
then obtain S'
where T\<^sub>1\<^sub>1: "\<Gamma> \<turnstile> T\<^sub>1\<^sub>1 <: T\<^sub>1\<^sub>1'"
and t\<^sub>1\<^sub>2: "VarB T\<^sub>1\<^sub>1' \<Colon> \<Gamma> \<turnstile> t\<^sub>1\<^sub>2 : S'"
and S': "\<Gamma> \<turnstile> S'[0 \<mapsto>\<^sub>\<tau> Top]\<^sub>\<tau> <: T\<^sub>1\<^sub>2" by (rule Abs_type' [simplified]) blast
from \<open>\<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>1\<^sub>1\<close>
have "\<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>1\<^sub>1'" using T\<^sub>1\<^sub>1 by (rule T_Sub)
with t\<^sub>1\<^sub>2 have "\<Gamma> \<turnstile> t\<^sub>1\<^sub>2[0 \<mapsto> t\<^sub>2] : S'[0 \<mapsto>\<^sub>\<tau> Top]\<^sub>\<tau>"
by (rule subst_type [where \<Delta>="[]", simplified])
hence "\<Gamma> \<turnstile> t\<^sub>1\<^sub>2[0 \<mapsto> t\<^sub>2] : T\<^sub>1\<^sub>2" using S' by (rule T_Sub)
with E_Abs show ?thesis by simp
next
case (E_App1 t'')
from \<open>t\<^sub>1 \<longmapsto> t''\<close>
have "\<Gamma> \<turnstile> t'' : T\<^sub>1\<^sub>1 \<rightarrow> T\<^sub>1\<^sub>2" by (rule T_App)
hence "\<Gamma> \<turnstile> t'' \<bullet> t\<^sub>2 : T\<^sub>1\<^sub>2" using \<open>\<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>1\<^sub>1\<close>
by (rule typing.T_App)
with E_App1 show ?thesis by simp
next
case (E_App2 t'')
from \<open>t\<^sub>2 \<longmapsto> t''\<close>
have "\<Gamma> \<turnstile> t'' : T\<^sub>1\<^sub>1" by (rule T_App)
with T_App(1) have "\<Gamma> \<turnstile> t\<^sub>1 \<bullet> t'' : T\<^sub>1\<^sub>2"
by (rule typing.T_App)
with E_App2 show ?thesis by simp
qed
next
case (T_TAbs T\<^sub>1 \<Gamma> t\<^sub>2 T\<^sub>2 t')
from \<open>(\<lambda><:T\<^sub>1. t\<^sub>2) \<longmapsto> t'\<close>
show ?case by cases
next
case (T_TApp \<Gamma> t\<^sub>1 T\<^sub>1\<^sub>1 T\<^sub>1\<^sub>2 T\<^sub>2 t')
from \<open>t\<^sub>1 \<bullet>\<^sub>\<tau> T\<^sub>2 \<longmapsto> t'\<close>
show ?case
proof cases
case (E_TAbs T\<^sub>1\<^sub>1' t\<^sub>1\<^sub>2)
with T_TApp have "\<Gamma> \<turnstile> (\<lambda><:T\<^sub>1\<^sub>1'. t\<^sub>1\<^sub>2) : (\<forall><:T\<^sub>1\<^sub>1. T\<^sub>1\<^sub>2)" by simp
then obtain S'
where "TVarB T\<^sub>1\<^sub>1 \<Colon> \<Gamma> \<turnstile> t\<^sub>1\<^sub>2 : S'"
and "TVarB T\<^sub>1\<^sub>1 \<Colon> \<Gamma> \<turnstile> S' <: T\<^sub>1\<^sub>2" by (rule TAbs_type') blast
hence "TVarB T\<^sub>1\<^sub>1 \<Colon> \<Gamma> \<turnstile> t\<^sub>1\<^sub>2 : T\<^sub>1\<^sub>2" by (rule T_Sub)
hence "\<Gamma> \<turnstile> t\<^sub>1\<^sub>2[0 \<mapsto>\<^sub>\<tau> T\<^sub>2] : T\<^sub>1\<^sub>2[0 \<mapsto>\<^sub>\<tau> T\<^sub>2]\<^sub>\<tau>" using T_TApp(3)
by (rule substT_type [where \<Delta>="[]", simplified])
with E_TAbs show ?thesis by simp
next
case (E_TApp t'')
from \<open>t\<^sub>1 \<longmapsto> t''\<close>
have "\<Gamma> \<turnstile> t'' : (\<forall><:T\<^sub>1\<^sub>1. T\<^sub>1\<^sub>2)" by (rule T_TApp)
hence "\<Gamma> \<turnstile> t'' \<bullet>\<^sub>\<tau> T\<^sub>2 : T\<^sub>1\<^sub>2[0 \<mapsto>\<^sub>\<tau> T\<^sub>2]\<^sub>\<tau>" using \<open>\<Gamma> \<turnstile> T\<^sub>2 <: T\<^sub>1\<^sub>1\<close>
by (rule typing.T_TApp)
with E_TApp show ?thesis by simp
qed
next
case (T_Sub \<Gamma> t S T t')
from \<open>t \<longmapsto> t'\<close>
have "\<Gamma> \<turnstile> t' : S" by (rule T_Sub)
then show ?case using \<open>\<Gamma> \<turnstile> S <: T\<close>
by (rule typing.T_Sub)
qed
text \<open>
The progress theorem is also proved by induction on the derivation of
@{term "[] \<turnstile> t : T"}. In the induction steps, we need the following two lemmas
about {\it canonical forms}
stating that closed values of types @{term "T\<^sub>1 \<rightarrow> T\<^sub>2"} and @{term "\<forall><:T\<^sub>1. T\<^sub>2"}
must be abstractions over term and type variables, respectively.
\<close>
lemma Fun_canonical: \<comment> \<open>A.14(1)\<close>
assumes ty: "[] \<turnstile> v : T\<^sub>1 \<rightarrow> T\<^sub>2"
shows "v \<in> value \<Longrightarrow> \<exists>t S. v = (\<lambda>:S. t)" using ty
proof (induct "[]::env" v "T\<^sub>1 \<rightarrow> T\<^sub>2" arbitrary: T\<^sub>1 T\<^sub>2)
case T_Abs
show ?case by iprover
next
case (T_App t\<^sub>1 T\<^sub>1\<^sub>1 t\<^sub>2 T\<^sub>1 T\<^sub>2)
from \<open>t\<^sub>1 \<bullet> t\<^sub>2 \<in> value\<close>
show ?case by cases
next
case (T_TApp t\<^sub>1 T\<^sub>1\<^sub>1 T\<^sub>1\<^sub>2 T\<^sub>2 T\<^sub>1 T\<^sub>2')
from \<open>t\<^sub>1 \<bullet>\<^sub>\<tau> T\<^sub>2 \<in> value\<close>
show ?case by cases
next
case (T_Sub t S T\<^sub>1 T\<^sub>2)
from \<open>[] \<turnstile> S <: T\<^sub>1 \<rightarrow> T\<^sub>2\<close>
obtain S\<^sub>1 S\<^sub>2 where S: "S = S\<^sub>1 \<rightarrow> S\<^sub>2"
by cases (auto simp add: T_Sub)
show ?case by (rule T_Sub S)+
qed simp
lemma TyAll_canonical: \<comment> \<open>A.14(3)\<close>
assumes ty: "[] \<turnstile> v : (\<forall><:T\<^sub>1. T\<^sub>2)"
shows "v \<in> value \<Longrightarrow> \<exists>t S. v = (\<lambda><:S. t)" using ty
proof (induct "[]::env" v "\<forall><:T\<^sub>1. T\<^sub>2" arbitrary: T\<^sub>1 T\<^sub>2)
case (T_App t\<^sub>1 T\<^sub>1\<^sub>1 t\<^sub>2 T\<^sub>1 T\<^sub>2)
from \<open>t\<^sub>1 \<bullet> t\<^sub>2 \<in> value\<close>
show ?case by cases
next
case T_TAbs
show ?case by iprover
next
case (T_TApp t\<^sub>1 T\<^sub>1\<^sub>1 T\<^sub>1\<^sub>2 T\<^sub>2 T\<^sub>1 T\<^sub>2')
from \<open>t\<^sub>1 \<bullet>\<^sub>\<tau> T\<^sub>2 \<in> value\<close>
show ?case by cases
next
case (T_Sub t S T\<^sub>1 T\<^sub>2)
from \<open>[] \<turnstile> S <: (\<forall><:T\<^sub>1. T\<^sub>2)\<close>
obtain S\<^sub>1 S\<^sub>2 where S: "S = (\<forall><:S\<^sub>1. S\<^sub>2)"
by cases (auto simp add: T_Sub)
show ?case by (rule T_Sub S)+
qed simp
theorem progress:
assumes ty: "[] \<turnstile> t : T"
shows "t \<in> value \<or> (\<exists>t'. t \<longmapsto> t')" using ty
proof (induct "[]::env" t T)
case T_Var
thus ?case by simp
next
case T_Abs
from value.Abs show ?case ..
next
case (T_App t\<^sub>1 T\<^sub>1\<^sub>1 T\<^sub>1\<^sub>2 t\<^sub>2)
hence "t\<^sub>1 \<in> value \<or> (\<exists>t'. t\<^sub>1 \<longmapsto> t')" by simp
thus ?case
proof
assume t\<^sub>1_val: "t\<^sub>1 \<in> value"
with T_App obtain t S where t\<^sub>1: "t\<^sub>1 = (\<lambda>:S. t)"
by (auto dest!: Fun_canonical)
from T_App have "t\<^sub>2 \<in> value \<or> (\<exists>t'. t\<^sub>2 \<longmapsto> t')" by simp
thus ?thesis
proof
assume "t\<^sub>2 \<in> value"
with t\<^sub>1 have "t\<^sub>1 \<bullet> t\<^sub>2 \<longmapsto> t[0 \<mapsto> t\<^sub>2]"
by simp (rule eval.intros)
thus ?thesis by iprover
next
assume "\<exists>t'. t\<^sub>2 \<longmapsto> t'"
then obtain t' where "t\<^sub>2 \<longmapsto> t'" by iprover
with t\<^sub>1_val have "t\<^sub>1 \<bullet> t\<^sub>2 \<longmapsto> t\<^sub>1 \<bullet> t'" by (rule eval.intros)
thus ?thesis by iprover
qed
next
assume "\<exists>t'. t\<^sub>1 \<longmapsto> t'"
then obtain t' where "t\<^sub>1 \<longmapsto> t'" ..
hence "t\<^sub>1 \<bullet> t\<^sub>2 \<longmapsto> t' \<bullet> t\<^sub>2" by (rule eval.intros)
thus ?thesis by iprover
qed
next
case T_TAbs
from value.TAbs show ?case ..
next
case (T_TApp t\<^sub>1 T\<^sub>1\<^sub>1 T\<^sub>1\<^sub>2 T\<^sub>2)
hence "t\<^sub>1 \<in> value \<or> (\<exists>t'. t\<^sub>1 \<longmapsto> t')" by simp
thus ?case
proof
assume "t\<^sub>1 \<in> value"
with T_TApp obtain t S where "t\<^sub>1 = (\<lambda><:S. t)"
by (auto dest!: TyAll_canonical)
hence "t\<^sub>1 \<bullet>\<^sub>\<tau> T\<^sub>2 \<longmapsto> t[0 \<mapsto>\<^sub>\<tau> T\<^sub>2]" by simp (rule eval.intros)
thus ?thesis by iprover
next
assume "\<exists>t'. t\<^sub>1 \<longmapsto> t'"
then obtain t' where "t\<^sub>1 \<longmapsto> t'" ..
hence "t\<^sub>1 \<bullet>\<^sub>\<tau> T\<^sub>2 \<longmapsto> t' \<bullet>\<^sub>\<tau> T\<^sub>2" by (rule eval.intros)
thus ?thesis by iprover
qed
next
case (T_Sub t S T)
show ?case by (rule T_Sub)
qed
end
|
{"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/POPLmark-deBruijn/POPLmark.thy"}
|
function [h, p, ci, stats] = ttest2(D, varname, wh_keep1, wh_keep2, varargin)
% Two sample ttest for two samples of one subject-level variable
%
% :Usage:
% ::
%
% ttest2(D, varname, wh_keep1, wh_keep2, [optional inputs])
%
% ..
% Author and copyright information:
%
% Copyright (C) 2013 Tor Wager
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
% ..
%
%
% :Inputs:
%
% **D:**
% a canlab_dataset object
%
% **varname:**
% the name of a valid variable to get from dataset
%
% **wh_keep1:**
% subjects forming first sample
%
% **wh_keep2:**
% subjects forming second sample
%
% :Optional Inputs:
%
% **noverbose:**
% will suppress print out of results and bargraph
%
% **varargin:**
% other variables passed directly to MATLAB's ttest2
%
% :Outputs:
%
% same as MATLAB's ttest2 output
%
if any(wh_keep1 & wh_keep2), warning('YOUR SAMPLES ARE OVERLAPPING!!'); end
verbose=1;
if any(strcmp('noverbose', varargin))
verbose=0;
varargin(find(strcmp('noverbose', varargin))) = [];
end
x1 = get_var(D, varname, wh_keep1);
x2 = get_var(D, varname, wh_keep2);
[h, p, ci, stats] = ttest2(x1, x2, varargin{:});
if verbose, ttest2_printout(x1,x2, 1); end
end
|
{"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@canlab_dataset/ttest2.m"}
|
!(LICENSE:PD)
! @(#) draw a simple menu using ncurses(3c) from Fortran
! differences between Fortran and C usage
! printw(3c) is not implimented; do internal WRITE(3f) into a character variable and call addstr(3c)
! add C_NULL_CHAR to the end of strings when calling addstr(3c)
! C arrays start at 0, Fortran at 1 by default; so defined "choices(0:4)" instead of "choices(5)"
!
! NOTE: Assuming at least an 80x24 character window
module m_simple_key2
use M_ncurses
character(len=8) :: choices(0:4)=[ "Choice 1", "Choice 2", "Choice 3", "Choice 4", "Exit "] ! menu choices to display
integer :: n_choices ! number of choices in menu
contains
!-------------------------------------------------------------------------------
subroutine print_menu(menu_win, highlight) ! draw a menu using the list in choices(), highlighting one choice
implicit none
type(C_PTR) :: menu_win ! this is the subwindow to draw in
integer :: highlight ! this says which choice description to highlight
integer,save :: x=2 ! x position relative to left edge of subwindow to print choices
integer :: y ! y position where to display next choice description
integer :: i ! loop counter
integer :: ierr ! used to hold the return value of many curses(3f) functions
y=2
ierr=box(menu_win, 0_C_LONG, 0_C_LONG) ! outline the subwindow with a box
do i=0,n_choices-1,1 ! draw the menu
if(highlight == i + 1)then ! Highlight the present choice
ierr=wattron(menu_win, A_REVERSE) ! turn on highlighting
ierr=mvwaddstr(menu_win,y, x, trim(choices(i))//C_NULL_CHAR) ! print choice description
ierr=wattroff(menu_win, A_REVERSE) ! turn off highlighting
else
ierr=mvwaddstr(menu_win, y, x, choices(i)//C_NULL_CHAR) ! just print choice description without highlighting
endif
y=y+1 ! move down to location to display next menu choice
enddo
ierr=wrefresh(menu_win) ! post everything to the real screen
end subroutine print_menu
!-------------------------------------------------------------------------------
end module m_simple_key2
!-------------------------------------------------------------------------------
program simple_key
use m_simple_key2
implicit none
type (C_PTR) :: menu_win
integer :: highlight = 1
integer :: choice = 0
integer :: c
character(len=80) :: string
integer :: cursor_state
integer :: startx, starty
integer,parameter :: WIDTH=30,HEIGHT=10 ! size of subwindow to create menu in
integer :: ierr ! used to hold the return value of many curses(3f) functions
n_choices = size(choices) ! get the number of items in the menu
stdscr=initscr() ! initialize curses(3c)
ierr=clear() ! clear the screen in case initscr(3c) did not
! most curses(3c) programs always call cbreak(3c) and noecho(3c)
! to ensure only what is posted by curses to the screen appears
! and that the program can read almost any keystroke immediately
ierr=cbreak() ! Line buffering disabled. pass on most everything immediately
ierr=noecho() ! tell the system to not echo the user keystrokes so you have control
! of what appears
cursor_state=curs_set(0) ! The curs_set routine sets the cursor state to invisible, normal,
! or very visible for visibility equal to 0, 1, or 2 respectively. If
! the terminal supports the visibility requested, the previous cursor
! state is returned; otherwise, ERR is returned
startx = (80-WIDTH)/2 ! define the top left corner for a subwindow
starty = (24-HEIGHT)/2
call numbers()
menu_win = newwin(HEIGHT, WIDTH, starty, startx) ! start a subwindow for the menu to display in
ierr=keypad(menu_win, TRUE)
! enables the keypad of the user's terminal. If enabled
! the user can press a function key (such as an arrow key)
! and wgetch returns a single value representing the function key,
! as in KEY_LEFT.
! print usage instructions along the top of the main window
ierr=mvaddstr(0, 5, "Use arrow keys to go up and down, Press enter to select a choice"//C_NULL_CHAR)
ierr=mvaddstr(1, 5, "Other keys should just display their keycode values"//C_NULL_CHAR)
ierr=refresh() ! make sure everything is posted to the real screen
call print_menu(menu_win, highlight) ! draw the menu with the top choice highlighted
INFINITE: do ! look for an up or down arrow or return key
c = wgetch(menu_win) ! get next keypress
select case(c)
case(KEY_UP) ! if the up-arrow was pressed change which item to highlight
if(highlight == 1)then ! already at top of menu and going up
highlight = n_choices ! to wrap down to the bottom choice
else ! move hightlight up an option
highlight=highlight-1
endif
case(KEY_DOWN) ! move highlight choice according to down-arrow being pressed
if(highlight == n_choices)then
highlight = 1
else
highlight=highlight+1
endif
case(10) ! entered a RETURN so record which choice is highlighted as the selection
choice = highlight
case default ! for any other key show the key value and (maybe) the character
write(string,'("Character pressed is = ",i3," Hopefully it can be printed as ",a)') c,char(c)
ierr=mvaddstr(23, 5, trim(string)//C_NULL_CHAR)
ierr=refresh() ! make sure real screen is up-to-date
end select
call print_menu(menu_win, highlight) ! redraw the menu with the highlighting possibly moved
if(choice /= 0)then ! User did a choice so come out of the infinite loop
exit INFINITE
endif
enddo INFINITE
if(cursor_state >= 0)then ! restore cursor state so cursor (probably) shows at end of following output
ierr=curs_set(cursor_state)
endif
! print information on selection made
write(string,'("You chose choice ",i1," with choice string ",a)') choice, trim(choices(choice-1))
ierr=mvaddstr(23, 5, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"//C_NULL_CHAR)
ierr=mvaddstr(23, 5, trim(string)//C_NULL_CHAR)
ierr=clrtoeol() ! erase the tail of any old message (erases from current position to the end of the current line).
ierr=refresh() ! make sure everything is posted to the real screen
ierr=getch() ! Wait for a user keystroke. Some terminal types will restore or clear the screen so a pause is a good idea
ierr=endwin() ! exit curses mode
end program simple_key
!-------------------------------------------------------------------------------
subroutine numbers()
use M_ncurses
character(len=3) :: label
do i=0,999 ! label up to 1000 rows of the main screen with a number on the left edge
write(label,'(i3.3)')i
ierr=mvaddstr(i, 0, trim(label)//C_NULL_CHAR)
if(ierr.lt.0) exit ! if printed off-screen then stop
enddo
ierr=refresh() ! make sure everything is posted to the real screen
end subroutine numbers
!-------------------------------------------------------------------------------
|
{"hexsha": "77b84a463eccf083675a98118245b5b5b6da5a06", "size": 9276, "ext": "f90", "lang": "FORTRAN", "max_stars_repo_path": "example/nc_simple_key.f90", "max_stars_repo_name": "freevryheid/M_ncurses", "max_stars_repo_head_hexsha": "b4b1e2ee10928fac3843f5b8310fddf935d3b30a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-09-14T08:30:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T10:06:25.000Z", "max_issues_repo_path": "example/nc_simple_key.f90", "max_issues_repo_name": "freevryheid/M_ncurses", "max_issues_repo_head_hexsha": "b4b1e2ee10928fac3843f5b8310fddf935d3b30a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-03T06:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T23:11:31.000Z", "max_forks_repo_path": "example/nc_simple_key.f90", "max_forks_repo_name": "freevryheid/M_ncurses", "max_forks_repo_head_hexsha": "b4b1e2ee10928fac3843f5b8310fddf935d3b30a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-04T02:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T02:08:41.000Z", "avg_line_length": 70.2727272727, "max_line_length": 132, "alphanum_fraction": 0.5064683053, "num_tokens": 1818}
|
# Mel-cepstrum analysis
# re-coded from SPTK
!isdefined(Base, :FFTW) && using FFTW
function fill_al!{T<:AbstractFloat}(al::Vector{T}, α::AbstractFloat)
al[1] = one(T)
for i=2:length(al)
@inbounds al[i] = -α*al[i-1]
end
al
end
function fill_toeplitz!{T}(A::AbstractMatrix{T}, t::AbstractVector{T})
n = length(t)
for j=1:n, i=1:n
@inbounds A[i,j] = i-j+1 >= 1 ? t[i-j+1] : t[j-i+1]
end
A
end
function fill_hankel!{T}(A::AbstractMatrix{T}, h::AbstractVector{T})
n = length(h)>>1 + 1
for j=1:n, i=1:n
@inbounds A[i,j] = h[i+j-1]
end
A
end
function fill_only_real_part!{T}(y::AbstractVector{Complex{T}},
v::AbstractVector{T})
for i=1:length(v)
@inbounds y[i] = Complex(v[i], zero(T))
end
y
end
function update_hankel_elements!(he::AbstractVector, c::AbstractVector)
for j=1:length(he)
@inbounds he[j] = c[j]
end
for j=1:2:length(he)
@inbounds he[j] -= c[1]
end
he
end
function update_toeplitz_elements!(te::AbstractVector, c::AbstractVector)
for j=1:2:length(te)
@inbounds te[j] += c[1]
end
te
end
function periodogram2mcep{T<:AbstractFloat}(periodogram::AbstractVector{T}, # modified periodogram
order::Int=40, # order of mel-cepstrum
α::AbstractFloat=0.41; # all-pass constant
miniter::Int=2,
maxiter::Int=30,
criteria::AbstractFloat=0.001, # stopping criteria
e::T=zero(T), # floor of periodogram
verbose::Bool=false)
logperiodogram = log.(periodogram + e)
fftlen = (size(logperiodogram, 1)-1)*2
const xh = fftlen>>1
# create FFT workspace and plan
y = Array{Complex{T},1}(xh+1)
c = Array{T,1}(fftlen)
# fplan = FFTW.Plan(c, y, 1, FFTW.ESTIMATE, FFTW.NO_TIMELIMIT)
# bplan = FFTW.Plan(y, c, 1, FFTW.ESTIMATE, FFTW.NO_TIMELIMIT)
fplan = plan_rfft(c)
bplan = plan_brfft(y, fftlen)
# Initial value of cepstrum
fill_only_real_part!(y, logperiodogram)
A_mul_B!(c, bplan, y)
# FFTW.execute(T, bplan.plan)
# FFTW.execute(bplan.plan, y, c)
scale!(c, 1. / fftlen)
# scale!(c, FFTW.normalization(c))
c[1] /= 2.0
c[xh+1] /= 2.0
# Initial value of mel-cesptrum
mc = freqt(view(c, 1:xh+1), order, α)
czero = c[1]
# Allocate memory for solving linear equation (Tm + Hm)d = b
Tm = Array{T,2}(order+1, order+1)
Hm = Array{T,2}(order+1, order+1)
Tm_plus_Hm = Array{T,2}(order+1, order+1)
he = Array{T,1}(2order+1) # elements of hankel matrix
te = Array{T,1}(order+1) # elements of toeplitz matrix
b = Array{T,1}(order+1) # right side of linear equation
al = Array{T,1}(order+1)
fill_al!(al, α)
# Newton raphson roop
ch = view(c, 1:xh+1)
ch_copy = Array{T,1}(xh+1)
c_frqtr = view(c, 1:2order+1)
for i=1:maxiter
fill!(c, zero(T))
freqt!(ch, mc, -α)
A_mul_B!(y, fplan, c)
# FFTW.execute(fplan.plan, c, y)
for i=1:length(y)
@inbounds y[i] = Complex(periodogram[i] / exp(2real(y[i])), zero(T))
end
A_mul_B!(c, bplan, y)
# FFTW.execute(bplan.plan, y, c)
# scale!(c, FFTW.normalization(c))
scale!(c, 1.0 / fftlen)
copy!(ch_copy, ch)
frqtr!(c_frqtr, ch_copy, α)
# check convergence
if i >= miniter
err = abs((c[1]-czero)/c[1])
verbose && println("czero nmse: $err")
if err < criteria
break
end
czero = c[1]
end
copy!(te, 1, c, 1, order+1)
for j=1:order+1
@inbounds b[j] = c[j] - al[j]
end
update_hankel_elements!(he, c)
update_toeplitz_elements!(te, c)
fill_hankel!(Hm, he)
fill_toeplitz!(Tm, te)
for i=1:length(Hm)
@inbounds Tm_plus_Hm[i] = Hm[i] + Tm[i]
end
# Solve Ax = b
# NOTE: both Tm_plus_Hm and b are overwritten
A_ldiv_B!(lufact!(Tm_plus_Hm), b)
# Add the solution vector to mel-cepstrum
for i=1:length(b)
@inbounds mc[i] += b[i]
end
end
mc
end
function _mcep(x::AbstractVector, # a *windowed* signal
order=25, # order of mel-cepstrum
α=0.35; # all-pass constant
kargs...)
periodgram = abs2.(rfft(x))
periodogram2mcep(periodgram, order, α; kargs...)
end
function estimate(mgc::MelCepstrum, x::AbstractArray;
use_sptk::Bool=false,
kargs...)
order = param_order(mgc)
α = allpass_alpha(mgc)
# Note that mcep in julia is more stable than SPTK.mcep
mcepfunc::Function = use_sptk ? SPTK.mcep : _mcep
data = mcepfunc(x, order, α; kargs...)
SpectralParamState(mgc, data, true, true)
end
function mcep(x::AbstractArray, order=25, α=0.35; kargs...)
estimate(MelGeneralizedCepstrum(order, α, 0.0), x; kargs...)
end
|
{"hexsha": "81fb554668ab2103205345b186e53814c9b54ad7", "size": 5309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mcep.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/MelGeneralizedCepstrums.jl-89d8d30b-2485-52b0-94e9-e2a8fdf814ee", "max_stars_repo_head_hexsha": "987ac2b16e32d206c934b139d33f7f8d790bd592", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2015-01-29T14:50:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T08:42:39.000Z", "max_issues_repo_path": "src/mcep.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/MelGeneralizedCepstrums.jl-89d8d30b-2485-52b0-94e9-e2a8fdf814ee", "max_issues_repo_head_hexsha": "987ac2b16e32d206c934b139d33f7f8d790bd592", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2015-01-04T13:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:30:29.000Z", "max_forks_repo_path": "src/mcep.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/MelGeneralizedCepstrums.jl-89d8d30b-2485-52b0-94e9-e2a8fdf814ee", "max_forks_repo_head_hexsha": "987ac2b16e32d206c934b139d33f7f8d790bd592", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-11-13T12:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:09:03.000Z", "avg_line_length": 28.8532608696, "max_line_length": 99, "alphanum_fraction": 0.5347523074, "num_tokens": 1696}
|
using aoc2019.computer: load_program, io, run
using Match
input = joinpath(@__DIR__, "input")
p = load_program(input)
function camera!(channel, view)
i, j = 0, 0
for msg in channel
if msg == 10
i = 0
j += 1
else
view[Pair(i, j)] = msg
i += 1
end
end
end
function calibrate(view)
scaffolds = collect(keys(filter(kv -> kv.second != 46, view)))
acc = 0
for kv in scaffolds
x, y = kv
up = Pair(x, y + 1)
down = Pair(x, y - 1)
right = Pair(x + 1, y)
left = Pair(x - 1, y)
if all(dir -> dir in scaffolds, [up, down, right, left])
acc += x * y
end
end
return acc
end
function display(view)
i, j = 0, 0
mx = maximum(map(kv -> kv.first, collect(keys(view))))
my = maximum(map(kv -> kv.second, collect(keys(view))))
for j in 0:my
for i in 0:mx
print(convert(Char, view[Pair(i,j)]))
i += 1
end
println()
i = 0
j += 1
end
end
function path(view)
p = []
robot = filter(kv -> kv.second != 46 && kv.second != 35, view)
position, facing = first(robot)
d = direction(facing)
while true
# must turn, try each and see if there's a scaffold in that direction
rx, ry = turn_right(d)
r = Pair(position.first + rx, position.second + ry)
lx, ly = turn_left(d)
l = Pair(position.first + lx, position.second + ly)
if haskey(view, r) && view[r] != 46
d = Pair(rx, ry)
steps = 0
while true
next = Pair(position.first + d.first, position.second + d.second)
if haskey(view, next) && view[next] != 46
steps += 1
position = next
else
break
end
end
push!(p, ("R", string(steps)))
elseif haskey(view, l) && view[l] != 46
d = Pair(lx, ly)
steps = 0
while true
next = Pair(position.first + d.first, position.second + d.second)
if haskey(view, next) && view[next] != 46
steps += 1
position = next
else
break
end
end
push!(p, ("L", string(steps)))
else
break
end
end
return p
end
function turn_right(m)
adj = Dict(
Pair(0, 1) => Pair(-1, 0),
Pair(1, 0) => Pair(0, 1),
Pair(0, -1) => Pair(1, 0),
Pair(-1, 0) => Pair(0, -1)
)
return adj[m]
end
function turn_left(m)
adj = Dict(
Pair(0, 1) => Pair(1, 0),
Pair(1, 0) => Pair(0, -1),
Pair(0, -1) => Pair(-1, 0),
Pair(-1, 0) => Pair(0, 1)
)
return adj[m]
end
function direction(char)
if char == convert(Int, '^')
return Pair(0, -1)
elseif char == convert(Int, '>')
return Pair(1, 0)
elseif char == convert(Int, 'v')
return Pair(0, 1)
elseif char == convert(Int, '<')
return Pair(-1, 0)
else
throw("unreachable?")
end
end
function send_input!(channel, instructions)
reverse!(instructions)
while true
if isempty(instructions)
put!(channel, 10)
break
else
put!(channel, pop!(instructions))
end
end
end
function how_much_dust(channel)
last = nothing
while true
v = take!(stdout)
## ignore ascii output
if v < 128
nothing
else
last = v
break
end
end
return last
end
stdin, stdout = io()
task = @async run(copy(p), stdin, stdout)
view = Dict{Pair{Int, Int}, Int}()
# let program run
while !istaskdone(task); yield() end
# close channel so it can be iterated over
close(stdout)
# populate view
camera!(stdout, view)
# display(view)
p1 = calibrate(view)
@assert p1 == 7280
# generate the path from start to end as turn-step pairs
# route = path(view)
## i compressed this by hand. no good ideas on how to do it progmatically
routine = map(c -> convert(Int, c), ['A', ',', 'B', ',', 'A', ',', 'C', ',', 'B', ',', 'C', ',', 'A', ',', 'B', ',', 'A', ',', 'C'])
a = map(c -> convert(Int, c), ['R', ',', '1', '0', ',', 'L', ',', '8', ',', 'R', ',', '1', '0', ',', 'R', ',', '4'])
b = map(c -> convert(Int, c), ['L', ',', '6', ',', 'L', ',', '6', ',', 'R', ',', '1', '0'])
c = map(c -> convert(Int, c), ['L', ',', '6', ',', 'R', ',', '1', '2', ',', 'R', ',', '1', '2', ',', 'R', ',', '1', '0'])
p[1] = 2
stdin, stdout = io()
task = @async run(copy(p), stdin, stdout)
send_input!(stdin, routine)
send_input!(stdin, a)
send_input!(stdin, b)
send_input!(stdin, c)
# no live output
send_input!(stdin, [convert(Int, 'n')])
# wait for program to run
while !istaskdone(task); yield() end
# close channel so we don't block
close(stdout)
p2 = how_much_dust(stdout)
@assert p2 == 1045393
print("-----------------------------------------------------------------------\n")
print("set and forget -- part one\n calibration : $p1\n")
print("set and forget -- part two\n dust : $p2\n")
print("-----------------------------------------------------------------------\n")
|
{"hexsha": "7fcf0c1d01ad055984c607db4a422166328948ac", "size": 5331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bin/seventeen/run.jl", "max_stars_repo_name": "talentdeficit/aoc2019", "max_stars_repo_head_hexsha": "70692f4fd61c3b640ce601bed3afdd74f93a5d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-31T05:23:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-31T05:23:10.000Z", "max_issues_repo_path": "bin/seventeen/run.jl", "max_issues_repo_name": "talentdeficit/aoc2019", "max_issues_repo_head_hexsha": "70692f4fd61c3b640ce601bed3afdd74f93a5d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/seventeen/run.jl", "max_forks_repo_name": "talentdeficit/aoc2019", "max_forks_repo_head_hexsha": "70692f4fd61c3b640ce601bed3afdd74f93a5d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1323529412, "max_line_length": 132, "alphanum_fraction": 0.4766460326, "num_tokens": 1517}
|
#!/usr/bin/env python
"""
Create new copy of MEF fits file with ImageHDU order permuted
according to command line options.
"""
import os
import sys
import argparse
from random import shuffle
from astropy.io import fits
# put parent directory into sys.path
bp = os.path.dirname(os.path.realpath(__file__)).split(os.sep)
modpath = os.sep.join(bp[:-1] + ['lib'])
sys.path.insert(0, modpath)
# local imports
try:
import mutils as mu
except ImportError as e:
logging.error('Import failed: %s', e)
exit(1)
def parse_args():
"""handle command line"""
parser = argparse.ArgumentParser(
description="Copy MEF fits file with reordered ImageHDUs "
"All other HDU types have order preserved")
parser.add_argument("ifitsfile", help="input fits file")
parser.add_argument("ofitsfile", nargs='?', help="output fits file")
parser.add_argument("--info", action='store_true',
help="print the info() table summarizing file")
group = parser.add_mutually_exclusive_group()
group.add_argument("--byname", action='store_true',
help="write out ImageHDU's sorted by name")
group.add_argument("--byindex", action='store_true',
help="write out ImageHDU's sorted by index")
group.add_argument("--randomorder", action='store_true',
help="write out ImageHDU's in random order")
group.add_argument("--aslisted", nargs='+', type=int, metavar='idx',
help="write out ImageHDU's as listed"
" (may need \"--\" to terminate list)")
return parser.parse_args()
def hdu_writer(opts):
"""print the headers according to the options
"""
seglist = {} # dict to hold segment name, index as k,v
otherlist = {} # dict to hold non-image HDU's (except for primary)
pindex = 0
hdulist = fits.open(opts.ifitsfile)
# just print the image info with indexes, names, sizes
if opts.info:
hdulist.info()
return 0
# process primary and Image headers, and other HDUs
# build dicts etc. to facilitate processing
for hdu in hdulist:
index = hdulist.index_of(hdu.name)
if isinstance(hdu, fits.ImageHDU):
seglist[hdu.name] = index
elif isinstance(hdu, fits.PrimaryHDU):
pindex = index
else:
otherlist[hdu.name] = index
# create the output file and append the primary hdu
hdulisto = fits.HDUList()
hdulisto.append(hdulist[pindex])
# process the HDU's according to command line options
if opts.byindex:
# in original index order
for hdu in hdulist:
if isinstance(hdu, fits.ImageHDU):
hdulisto.append(hdu)
if opts.byname:
# sorted by name
for name, index in sorted(seglist.items()):
hdulisto.append(hdulist[index])
if opts.randomorder:
indexlist = seglist.values()
shuffle(indexlist)
for idx in indexlist:
hdulisto.append(hdulist[idx])
if opts.aslisted:
for idx in opts.aslisted:
hdulisto.append(hdulist[idx])
ids = list(otherlist.values())
for index in sorted(ids):
hdu = hdulist[index]
hdulisto.append(hdu)
hdulisto.info()
if opts.ofitsfile:
hdulisto.writeto(opts.ofitsfile, overwrite=True)
hdulisto.close()
hdulist.close()
if __name__ == '__main__':
optlist = parse_args()
hdu_writer(optlist)
|
{"hexsha": "8a7a4461c36308160435394aa5cdc3805c8bda69", "size": 3515, "ext": "py", "lang": "Python", "max_stars_repo_path": "imutils/hduorder.py", "max_stars_repo_name": "lsst-camera-dh/mutils", "max_stars_repo_head_hexsha": "80edb76c16bb3f00f22f77cf6aa2b2a1d02d73fe", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "imutils/hduorder.py", "max_issues_repo_name": "lsst-camera-dh/mutils", "max_issues_repo_head_hexsha": "80edb76c16bb3f00f22f77cf6aa2b2a1d02d73fe", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imutils/hduorder.py", "max_forks_repo_name": "lsst-camera-dh/mutils", "max_forks_repo_head_hexsha": "80edb76c16bb3f00f22f77cf6aa2b2a1d02d73fe", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-26T20:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-26T20:29:45.000Z", "avg_line_length": 31.3839285714, "max_line_length": 73, "alphanum_fraction": 0.6295874822, "include": true, "reason": "from astropy", "num_tokens": 835}
|
from PIL import Image
import numpy as np
import os
class Operations :
def __init__(self, img1, img2 = None):
os.system("clear")
print("Processing image...")
self.Lmax = 255
if(img2 is None) :
self.img = self.openImage(img1)
else :
self.img = self.openImage(img1)
self.imgAux = self.openImage(img2)
def openImage(self, path) :
image = Image.open(path)
if(image.mode != "RGB") :
image = image.convert("RGB")
return image
def constSum(self, const = 0) :
f = np.asarray(self.img, dtype=int)
f = f + int(const)
f[f > self.Lmax] = self.Lmax
f[f < 0] = 0
return Image.fromarray(np.uint8(f))
def constMult(self, const = 1) :
f = np.asarray(self.img, dtype=float)
f = float(const)*f
f[f > self.Lmax] = self.Lmax
return Image.fromarray(np.uint8(np.round(f)))
def constNegative(self) :
f = np.asarray(self.img, dtype=int)
f = self.Lmax - f
return Image.fromarray(np.uint8(f))
def constMono(self) :
f = np.asarray(self.img, dtype=int)
f = 0.299 * f[:,:,0] + 0.587 * f[:,:,1] + 0.114 * f[:,:,2]
return Image.fromarray(np.uint8(f))
def constRot(self, rotation = 1) :
f = np.asarray(self.img, dtype=int)
return Image.fromarray(np.uint8(np.rot90(f, rotation)))
def constMirror(self, axis) :
f = np.asarray(self.img, dtype=int)
return Image.fromarray(np.uint8(np.flip(f, axis=axis)))
def imagesSum(self, w = -1) :
w = w/100
f = np.asarray(self.img, dtype=float)
g = np.asarray(self.imgAux, dtype=float)
if(w < 0 or w > 100) :
f = f + g
else :
f = w*f + (1-w)*g
f[f > self.Lmax] = self.Lmax
return Image.fromarray(np.uint8(np.round(f)))
def imagesSub(self, w = -1) :
w = w/100
f = np.asarray(self.img, dtype=float)
g = np.asarray(self.imgAux, dtype=float)
if(w < 0 or w > 100) :
f = f - g
else :
f = w*f - (1-w)*g
f[f < 0] = 0
return Image.fromarray(np.uint8(np.round(f)))
def imagesMult(self) :
f = np.asarray(self.img, dtype=float)
g = np.asarray(self.imgAux, dtype=float)/self.Lmax
f = f * g
f[f > self.Lmax] = self.Lmax
return Image.fromarray(np.uint8(np.round(f)))
def imagesDiv(self) :
f = np.asarray(self.img, dtype=float)
g = np.asarray(self.imgAux, dtype=float)/self.Lmax
f = f / g
f[np.isnan(f)] = self.Lmax
f[f > self.Lmax] = self.Lmax
return Image.fromarray(np.uint8(np.round(f)))
def images3D(self) :
f = np.asarray(self.img, dtype=int)
g = np.asarray(self.img, dtype=int)
h = np.asarray(self.img, dtype=int)
f[:,:,1] = 0
f[:,:,2] = 0
g[:,:,0] = 0
disp = f.shape[1]*0.002
f = np.roll(f, int(disp), axis=1)
g = np.roll(g, -int(disp), axis=1)
# h = f + g + 0.5*h
h = f + g
h[h > self.Lmax] = self.Lmax
return Image.fromarray(np.uint8(h))
|
{"hexsha": "3fd929b345b5a8d9e435fc615c30666fb5cc66d6", "size": 2738, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/entities/operations.py", "max_stars_repo_name": "ThiagoPereiraUFV/Image-Editor", "max_stars_repo_head_hexsha": "d542509e72b0196097935976d7ddce829049eb74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/entities/operations.py", "max_issues_repo_name": "ThiagoPereiraUFV/Image-Editor", "max_issues_repo_head_hexsha": "d542509e72b0196097935976d7ddce829049eb74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/entities/operations.py", "max_forks_repo_name": "ThiagoPereiraUFV/Image-Editor", "max_forks_repo_head_hexsha": "d542509e72b0196097935976d7ddce829049eb74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9007633588, "max_line_length": 60, "alphanum_fraction": 0.6106647188, "include": true, "reason": "import numpy", "num_tokens": 911}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module contains the class Animater to animate ddos simulations"""
__Lisence__ = "BSD"
__maintainer__ = "Justin Furuness"
__email__ = "jfuruness@gmail.com, agorbenko97@gmail.com"
__status__ = "Development"
from copy import deepcopy
from enum import Enum
import os
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch
from matplotlib import animation
import numpy as np
from tqdm import tqdm
from .anim_attacker import Anim_Attacker
from .anim_bucket import Anim_Bucket
from .anim_round_text import Anim_Round_Text
from .anim_user import Anim_User
from .bucket_states import Bucket_States as B_States
from .color_generator import Color_Generator
from ..base_grapher import Base_Grapher
from ..attackers import Attacker
from ..simulation_objects import Bucket, User, User_Status as Status
from ..managers import Manager
class Bucket_States(Enum):
USED = 1
UNUSED = 0
ATTACKED = -1
class Animater(Base_Grapher):
"""animates a DDOS attack"""
low_dpi = 60
# Anything higher than 600 and you must drastically increase bitrate
# However increasing bitrate cause crashes elsewhere
high_dpi = 120
def __init__(self,
manager,
user_cls,
attacker_cls,
**kwargs):
"""Initializes simulation"""
super(Animater, self).__init__(**kwargs)
# Validation step
assert self.tikz is False, "Can't save animation as tikz afaik"
# Graph data
self.user_cls = user_cls
self.attacker_cls = attacker_cls
self.manager = deepcopy(manager)
self.manager_copies = [deepcopy(manager)]
# DPI for plotting graph
self.dpi = self.high_dpi if self.high_res else self.low_dpi
# Number of buckets in a single row
self.frames_per_round = 100 if self.save else 50
self.color_generator = Color_Generator(self.frames_per_round)
def capture_data(self, manager: Manager):
"""Captures data for the round"""
# I know this isn't the best, but I have more important work to do
self.manager_copies.append(deepcopy(manager))
def set_up_animation(self):
# Step 1: Figure out max users in a bucket
max_users_y, good_user_ids, attacker_ids = self._get_user_data()
# Step 2: Get all the bucket ids ever made
bucket_ids = self._get_bucket_ids()
# Format graph
fig, buckets_per_row = self._format_graph(max_users_y, bucket_ids)
# Create bucket id patches
self._create_buckets(bucket_ids, buckets_per_row, max_users_y)
self._create_users(good_user_ids, attacker_ids)
for manager_copy in self.manager_copies:
self._append_bucket_data(manager_copy)
self._append_user_data(manager_copy)
self.round_text = Anim_Round_Text(self.high_res,
0,
self.ax,
self.manager.__class__.__name__,
self.frames_per_round,
self.user_cls,
self.attacker_cls)
return fig
def _get_user_data(self):
"""Gets the max number of users in a given bucket for any round ever"""
self.track_suspicions = False
# self.managers is a deep copy stored each round
good_user_ids = set()
attacker_ids = set()
max_users_y = 0
for manager in self.manager_copies:
for bucket in manager.used_buckets.values():
for user in bucket.users:
if isinstance(user, Attacker):
attacker_ids.add(user.id)
else:
good_user_ids.add(user.id)
if user.suspicion > 0:
self.track_suspicions = True
# Get the max y val for that round
temp_max_users_y = max(len(x) for x in manager.used_buckets.values())
# Set the max y value for all rounds
max_users_y = max(max_users_y, temp_max_users_y)
return max_users_y, good_user_ids, attacker_ids
def _get_bucket_ids(self):
"""Gets the number of buckets that were used, ever"""
bucket_ids = set()
for manager in self.manager_copies:
for bucket_id in manager.used_buckets:
bucket_ids.add(bucket_id)
return bucket_ids
def _format_graph(self, max_users_y, bucket_ids):
"""Formats graph properly
Basically makes graph colorful"""
if self.save:
mpl.use("Agg")
else:
mpl.use("TkAgg")
plt.style.use('dark_background')
# https://stackoverflow.com/a/48958260/8903959
mpl.rcParams.update({'text.color': "black"})
fig = plt.figure()
# NOTE: Increasing figure size makes it take way longer
fig.set_size_inches(16, 9)
# Buckets_per_row
row_cutoff = 100 if max_users_y >= 40 else 32
rows = math.ceil(len(bucket_ids) / row_cutoff)
y_max = ((max_users_y * Anim_User.patch_length()
+ Anim_Bucket.patch_padding)
* rows + 1)
ax = plt.axes(xlim=(0, min(len(bucket_ids),
row_cutoff) * (Anim_Bucket.patch_length() + Anim_Bucket.patch_padding)),
ylim=(0, y_max))
ax.set_axis_off()
ax.margins(0)
Color_Generator.gradient_image(ax,
direction=0,
extent=(0, 1, 0, 1),
transform=ax.transAxes,
cmap=plt.cm.Oranges,
cmap_range=(0.1, 0.6))
self.ax = ax
return fig, row_cutoff
def _create_buckets(self, bucket_ids, buckets_per_row, max_users_y):
self.buckets = {_id: Anim_Bucket(_id, buckets_per_row, max_users_y)
for _id in sorted(bucket_ids)}
def _create_users(self, good_user_ids, attacker_ids):
# Create user id patches
self.users = {}
for _ids, cls in zip([good_user_ids, attacker_ids],
[Anim_User, Anim_Attacker]):
for _id in _ids:
og_bucket_id = self.manager.users[_id].bucket.id
self.users[_id] = cls(_id, self.buckets[og_bucket_id])
def _append_bucket_data(self, manager_copy):
used_bucket_ids = set()
for b in manager_copy.used_buckets.values():
state = B_States.ATTACKED if b.attacked else B_States.USED
self.buckets[b.id].states.append(state)
used_bucket_ids.add(b.id)
for bucket_id, bucket in self.buckets.items():
if bucket_id not in used_bucket_ids:
bucket.states.append(B_States.UNUSED)
def _append_user_data(self, manager_copy):
user_y_pts = {}
for _id, anim_user in self.users.items():
user = manager_copy.users[_id]
if user.status == Status.DISCONNECTED:
x, y = Anim_User.disconnected_location
elif user.status == Status.ELIMINATED:
x, y = Anim_User.detected_location
elif user.status == Status.CONNECTED:
anim_bucket = self.buckets[user.bucket.id]
x = anim_bucket.patch_center()
y = Anim_User.patch_padding + anim_bucket.patch.get_y() + Anim_User.patch_radius
# Move the user higher if other user in that spot
while y in user_y_pts.get(user.bucket.id, set()):
# * 2 for diameter
y += Anim_User.patch_radius * 2
y += Anim_User.patch_padding * 2
if user_y_pts.get(user.bucket.id) is None:
user_y_pts[user.bucket.id] = set()
user_y_pts[user.bucket.id].add(y)
anim_user.points.append([x, y])
anim_user.suspicions.append(user.suspicion)
def run_animation(self, total_rounds):
"""Graphs data
Saves all data to an mp4 file. Note, you can increase or
decrease total number of frames in this function"""
fig = self.set_up_animation()
frames = total_rounds * self.frames_per_round
anim = animation.FuncAnimation(fig, self.animate,
init_func=self.init,
frames=frames,
interval=40,
blit=True if self.save else False)
self.save_graph(anim, total_rounds)
def save_graph(self, anim, total_rounds):
"""Saves animation, overwrites Base_Grapher method"""
# self.save is an attr of Base_Grapher
if self.save:
# graph_dir comes from inherited class
path = os.path.join(self.graph_dir, f'{self.round_text._get_round_text(0).replace("Round 0 ", "")}.mp4')
pbar = tqdm(desc=f"Saving {path}",
total=self.frames_per_round * total_rounds)
# https://stackoverflow.com/a/14666461/8903959
anim.save(path,
progress_callback=lambda *_: pbar.update(),
dpi=self.dpi,
# NOTE: bitrate barely impacts saving speed
bitrate=12000)
pbar.close()
else:
plt.show()
def init(self):
"""inits the animation
Sets z order: bucket->horns->attacker/user->text"""
zorder = 0
for obj in self.animation_instances:
zorder = obj.add_to_anim(self.ax, zorder)
return self.animation_objects
@property
def animation_instances(self):
"""instances being animated"""
return (list(self.buckets.values())
+ list(self.users.values())
+ [self.round_text])
@property
def animation_objects(self):
"""objects used by matplotlib"""
objs = []
for instance in self.animation_instances:
objs.extend(instance.anim_objects)
return objs
def animate(self, frame):
"""Animates the frame
moves all objects partway to the next point. Basically,
determines the final destination, and moves 1/frames_per_round
of the way there. It only moves users, and so must move horns
and text of the user as well
"""
for instance in self.animation_instances:
instance.animate(frame,
self.frames_per_round,
self.track_suspicions,
self.color_generator)
return self.animation_objects
def set_matplotlib_args(self):
self.set_dpi()
self.set_font_size()
def set_dpi(self):
# https://stackoverflow.com/a/51955985/8903959
mpl.rcParams['figure.dpi'] = self.dpi
mpl.rcParams['figure.dpi'] = self.dpi
def set_font_size(self):
fontsize = 12
if self.manager.max_buckets > 10:
fontsize -= 3
if self.manager.max_users_y > 10:
fontsize -= 3
mpl.rcParams.update({'font.size': 5})
if self.manager.max_buckets > 20:
fontsize -= 2
if self.manager.max_buckets >= 100:
fontsize -= 4
if ("dose" in self.manager.__class__.__name__.lower()
or "sieve" in self.manager.__class__.__name__.lower()):
fontsize -= 2.5
if self.high_res:
# 3 is difference between low res and high res dpi
fontsize = fontsize / 1
mpl.rcParams.update({'font.size': fontsize})
|
{"hexsha": "50b6d27bf5f1b76cd572e670b24348e219b5bff7", "size": 12015, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib_ddos_simulator/animations/animater.py", "max_stars_repo_name": "jfuruness/lib_ddos_simulator", "max_stars_repo_head_hexsha": "2d860fd3f35f4c25262f5269251eed89975f95e8", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-01T22:42:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T22:42:36.000Z", "max_issues_repo_path": "lib_ddos_simulator/animations/animater.py", "max_issues_repo_name": "jfuruness/lib_ddos_simulator", "max_issues_repo_head_hexsha": "2d860fd3f35f4c25262f5269251eed89975f95e8", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib_ddos_simulator/animations/animater.py", "max_forks_repo_name": "jfuruness/lib_ddos_simulator", "max_forks_repo_head_hexsha": "2d860fd3f35f4c25262f5269251eed89975f95e8", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-16T17:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-16T17:55:46.000Z", "avg_line_length": 34.8260869565, "max_line_length": 120, "alphanum_fraction": 0.5812734082, "include": true, "reason": "import numpy", "num_tokens": 2557}
|
import numpy as np
def k_fold(n_samples, n_folds, randomize = False):
"""
计算K-fold交叉验证产生的样本索引值
Input:
n_samples, 样本的数量
n_folds, 分包的数量, 如果n_folds=n_samples,对应留一法交叉验证
if randomize = True(default,False), 首先对所有样本的索引值打乱,这对于那些样本按照一定
顺序排列的情况特别适用,比如所有的正样本都在前,负样本都在后。
例子:
k_fold(100, 3)
Output:
testfolds[0]=np.arange(33), trainfolds[0]=np.arange(33,100)
testfolds[1]=np.arange(33,66), trainfolds[1]=np.array(set(np.arange(N))-set(testfolds[1]))
testfolds[2]=np.arange(66,100),trainfolds[2]=np.arange(66)
"""
if randomize: # 如果randomize != 0,对原样本索引值进行打乱
np.random.seed(0) # 确保每次打乱的顺序是一样的
perm = np.random.permutation(n_samples) # 打乱后的索引值
else:
perm = np.arange(n_samples)
index = 0
number_in_test = n_samples//n_folds # 每一个test中样本的数目
test_folds = [] # 初始化测试集索引值列表
train_folds = [] # 初始化训练集索引值列表
for i in np.arange(n_folds):
low_index = index # 索引的下限值
if i == n_folds-1: # 当 当前fold为最后一个fold时
high_index = n_samples # 测试集索引的上限值为所有样本的长度,即一直取到最后一个元素
else:
high_index = low_index + number_in_test
test_folds.append(range(low_index, high_index))
train_folds.append(list(set(range(n_samples))-set(test_folds[-1])))
test_folds[i] = perm[test_folds[-1]]
# print(len(test_folds[i]))
train_folds[i] = perm[train_folds[-1]]
index = index + number_in_test
return train_folds, test_folds
if __name__ == '__main__':
print(k_fold(100, 3, 1))
|
{"hexsha": "4b0c5ad3486ff4c6153acdc15fc9363c6e2af96f", "size": 1596, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlapp/MLAPP_CODE/MLAPP-C7-Code/Kfold.py", "max_stars_repo_name": "xishansnow/MLAPP", "max_stars_repo_head_hexsha": "2f30cd94fd852a3f66fe92a124f65722bd2af509", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mlapp/MLAPP_CODE/MLAPP-C7-Code/Kfold.py", "max_issues_repo_name": "xishansnow/MLAPP", "max_issues_repo_head_hexsha": "2f30cd94fd852a3f66fe92a124f65722bd2af509", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlapp/MLAPP_CODE/MLAPP-C7-Code/Kfold.py", "max_forks_repo_name": "xishansnow/MLAPP", "max_forks_repo_head_hexsha": "2f30cd94fd852a3f66fe92a124f65722bd2af509", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6956521739, "max_line_length": 94, "alphanum_fraction": 0.626566416, "include": true, "reason": "import numpy", "num_tokens": 620}
|
#=##############################################################################
# # DESCRIPTION
# Examples of VTK formatting and usage of VTKtools
# # AUTHORSHIP
# * Author : Eduardo J Alvarez
# * Email : Edo.AlvarezR@gmail.com
# * Created : Nov 2017
# * License : MIT License
# * Modified : Kevin Moore moorekevin711@gmail.com
=###############################################################################
function save_vtk_opt(p_stress,p_strain,p_stresslayer,p_c_bucklingplot,p_xloc,p_yloc,p_zloc,numprops,w_stress,w_strain,w_stresslayer,w_c_bucklingplot,w_xloc,w_yloc,w_zloc;
file_name="./VTK_output/temp_kevin00",
p_radii = [0.0,0.2,0.4,0.6,0.8,1.0],
chord = [1.619, 1.473, 1.456, 0.789, 0.789, 0.789],
p_twist_d = [1.619, 1.473, 1.456, 0.789, 0.789, 0.789], #twist includes pitch
p_dihedral_d = pi/180*vcat([0 for i in 1:5], [23.20]),
p_sweep_d = pi/180*vcat([23.20 for i in 1:6], []),
Rtip = 1.25,
p_airfoilx = 0.0, #TODO, input default
p_airfoily = 0.0,
p_strainx = 0.0,
p_strainy = 0.0,
w_twist_d = [1.619, 1.473, 1.456, 0.789, 0.789, 0.789],
w_dihedral_d = pi/180*vcat([0 for i in 1:5], [23.20]),
w_sweep_d = pi/180*vcat([23.20 for i in 1:6], []),
w_strainx = 0.0,
w_strainy = 0.0,
spanloc = [0.0,1.0],
halfspan = 10.0,
printiter = 1,
proploc = 0.0,
numblades = 2,
plots = false )
numblades = Int(round(numblades))
# GEOMETRY DEFINITION
# dihedral = p_dihedral_d * pi/180
# sweep = p_sweep_d * pi/180
forward_offset = Rtip/10.0
y_pos = copy(p_yloc)#Rtip*p_radii # span position of each section
x_pos = zeros(p_yloc)-forward_offset#[y*tan(sweep[i]) for (i,y) in enumerate(y_pos)] #Already translated
z_pos = zeros(p_yloc)#[y*tan(dihedral[i]) for (i,y) in enumerate(y_pos)]
# PARAMETERS
r = fill(1.0,length(p_radii)) # Expansion ratio in both surfaces of each airfoil
azimuth_deg_spacing = round(Int, 360/numblades)
azimuth_deg = 0.0
for i = 1#:numprops
for j = 1:numblades
generateprop!(p_strainx,p_strainy,p_strain,p_stresslayer,p_stress,p_c_bucklingplot,p_airfoilx,p_airfoily,x_pos,y_pos,z_pos,proploc[i,:],p_sweep_d,p_twist_d,i,j,p_radii,azimuth_deg,file_name;plots=plots)
azimuth_deg = azimuth_deg_spacing + azimuth_deg
end
end
# ############################################
# ######## Generate Wing #################
# ############################################
#
# y_pos = copy(w_yloc)#Rtip*w_radii # span position of each section
# x_pos = zeros(w_yloc)#[y*tan(sweep[i]) for (i,y) in enumerate(y_pos)] #Already translated
# z_pos = zeros(w_yloc)#[y*tan(dihedral[i]) for (i,y) in enumerate(y_pos)]
# # PARAMETERS
# r = fill(1.0,length(spanloc)) # Expansion ratio in both surfaces of each airfoil
#
# sections = fill(Tuple{Float64,Int64,Float64,Bool}[(1.0, 10, 1.0, false)],(length(spanloc)-1))
#
# # Leading edge position of each airfoil
# Os = [ [x_pos[i], y_pos[i], z_pos[i]] for i in 1:size(w_strainx)[1]]
# # Orientation of chord of each airfoil (yaw, pitch, roll)
# orien = zeros(length(w_twist_d),3) #twist already included
# for i = 1:length(orien[:,1])
# orien[i,:] = [0.0,w_sweep_d[i],270.0]
# if i == 1
# orien[i,:] = [0.0,0.0,270.0]
# end
# end
#
# crosssections = [] # It will store here the cross sections for lofting
# strains = []
# stress1 = []
# stress2 = []
# stressplot = []
# buckle = []
# point_datas = []
#
# # Processes each airfoil geometry - STRESS/STRAIN CALCS
# for i = 1:length(w_strainx[:,1])
#
# # Read airfoil file
# x = w_strainx[i,:]
# y = w_strainy[i,:]
#
# # Scales the airfoil acording to its chord length
# new_x = x#new_x #already scaled
# new_y = y#new_y
#
# # plot_airfoil(new_x, new_y; style=styles[i], label="airfoil")
# if plots
# figure("wing_airfoil")
# plot(new_x,new_y)
# end
#
# # Reformats into points
# npoints = size(new_x)[1]
# airfoil = Array{Float64, 1}[[new_x[j], new_y[j], 0] for j in 1:npoints]
#
# # Positions the airfoil along the blade in the right p_orientation
# Oaxis = VTKtools.rotation_matrix(orien[i,1], orien[i,2], orien[i,3])
# invOaxis = inv(Oaxis)
# airfoil = VTKtools.countertransform(airfoil, invOaxis, Os[i])
#
# push!(crosssections, airfoil)
#
# push!(strains, w_strain[i,:])
# push!(stress1, w_stresslayer[1,i,:])
# push!(stress2, w_stresslayer[2,i,:])
# push!(stressplot, w_stress[i,:])
# push!(buckle, w_c_bucklingplot[i,:])
# push!(point_datas, [j for j in npoints*(i-1)+1:npoints*i])
# end
#
# # Generates cells in VTK Legacy format
# points, vtk_cells, strain = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=strains)
# _, _, stresses1 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stress1)
# _, _, stresses2 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stress2)
# _, _, stresses6 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stressplot)
# _, _, bucklecon = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=buckle)
# points, vtk_cells, point_datas = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=point_datas)
#
# # Formats the point data for generateVTK
# data = []
# push!(data, Dict(
# "field_name" => "Strain",
# "field_type" => "scalar",
# "field_data" => strain))
#
# push!(data, Dict(
# "field_name" => "uni_stress",
# "field_type" => "scalar",
# "field_data" => stresses1))
#
# push!(data, Dict(
# "field_name" => "weave_stress",
# "field_type" => "scalar",
# "field_data" => stresses2))
#
# push!(data, Dict(
# "field_name" => "stress",
# "field_type" => "scalar",
# "field_data" => stresses6))
#
# push!(data, Dict(
# "field_name" => "Buckling_Constraint",
# "field_type" => "scalar",
# "field_data" => bucklecon))
#
# push!(data, Dict(
# "field_name" => "PointIndex",
# "field_type" => "scalar",
# "field_data" => point_datas))
#
# # Generates the vtk file
# VTKtools.generateVTK("$(file_name)wingR.$printiter", points; cells=vtk_cells, point_data=data, keep_points=false)
#
#
# #generate other wing
# Os = [ [x_pos[i], -y_pos[i], z_pos[i]] for i in 1:size(w_strainx)[1]]
# # Orientation of chord of each airfoil (yaw, pitch, roll)
# orien = zeros(length(w_twist_d),3) #twist already included
# for i = 1:length(orien[:,1])
# orien[i,:] = [0.0,-w_sweep_d[i],270.0]
# if i == 1
# orien[i,:] = [0.0,0.0,270.0]
# end
# end
#
# crosssections = [] # It will store here the cross sections for lofting
# strains = []
# stress1 = []
# stress2 = []
# stressplot = []
# buckle = []
# point_datas = []
# for i = length(w_strainx[:,1]):-1:1
#
# # Read airfoil file
# x = w_strainx[i,:]
# y = w_strainy[i,:]
#
# # Scales the airfoil acording to its chord length
# new_x = x#new_x #already scaled
# new_y = y#new_y
#
# # plot_airfoil(new_x, new_y; style=styles[i], label="airfoil")
# if plots
# figure("wing_airfoil")
# plot(new_x,new_y)
# end
#
# # Reformats into points
# npoints = size(new_x)[1]
# airfoil = Array{Float64, 1}[[new_x[j], new_y[j], 0] for j in 1:npoints]
#
# # Positions the airfoil along the blade in the right p_orientation
# Oaxis = VTKtools.rotation_matrix(orien[i,1], orien[i,2], orien[i,3])
# invOaxis = inv(Oaxis)
# airfoil = VTKtools.countertransform(airfoil, invOaxis, Os[i])
#
# push!(crosssections, airfoil)
#
# push!(strains, w_strain[i,:])
# push!(stress1, w_stresslayer[1,i,:])
# push!(stress2, w_stresslayer[2,i,:])
# push!(stressplot, w_stress[i,:])
# push!(buckle, w_c_bucklingplot[i,:])
# push!(point_datas, [j for j in npoints*(i-1)+1:npoints*i])
# end
#
# # Generates cells in VTK Legacy format
# points, vtk_cells, strain = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=strains)
# _, _, stresses1 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stress1)
# _, _, stresses2 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stress2)
# _, _, stresses6 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stressplot)
# _, _, bucklecon = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=buckle)
# points, vtk_cells, point_datas = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=point_datas)
#
# # Formats the point data for generateVTK
# data = []
# push!(data, Dict(
# "field_name" => "Strain",
# "field_type" => "scalar",
# "field_data" => strain))
#
# push!(data, Dict(
# "field_name" => "uni_stress",
# "field_type" => "scalar",
# "field_data" => stresses1))
#
# push!(data, Dict(
# "field_name" => "weave_stress",
# "field_type" => "scalar",
# "field_data" => stresses2))
#
# push!(data, Dict(
# "field_name" => "stress",
# "field_type" => "scalar",
# "field_data" => stresses6))
#
# push!(data, Dict(
# "field_name" => "Buckling_Constraint",
# "field_type" => "scalar",
# "field_data" => bucklecon))
#
# push!(data, Dict(
# "field_name" => "PointIndex",
# "field_type" => "scalar",
# "field_data" => point_datas))
#
# # Generates the vtk file
# VTKtools.generateVTK("$(file_name)wingL.$printiter", points; cells=vtk_cells, point_data=data, keep_points=false)
#
#
# # #TEST vector output
# # p0 = [0,0,0.0]
# # p1 = [0,1,0.0]
# # c0 = [p0,p1,p1,p0]
# # d0 = [1.0,1.0,1.0,1.0]
# # points, vtk_cells, lift = VTKtools.lines2vtk([c0];
# # values=[d0])
# # data = []
# # push!(data, Dict(
# # "field_name" => "Strain",
# # "field_type" => "vector",
# # "field_data" => lift))
# #
# # VTKtools.generateVTK("$(file_name)lift.$printiter", points;
# # cells=vtk_cells, point_data=data)
println("VTK Saved")
end
function generateprop!(p_strainx,p_strainy,p_strain,stresslayer,stress,p_c_bucklingplot,p_airfoilx,p_airfoily,x_pos,y_pos,z_pos,proploc,p_sweep_d,p_twist_d,propnum,bladenum,p_radii,azimuth_deg,file_name;plots = false)
sections = fill(Tuple{Float64,Int64,Float64,Bool}[(1.0, 10, 1.0, false)],((length(p_radii)-1)))#*2+1))
crosssections = [] # It will store here the cross sections for lofting
strains = []
stress1 = []
stress2 = []
stressplot = []
buckle = []
point_datas = []
# Leading edge position of each airfoil
Os = [ [x_pos[i]+proploc[1], y_pos[i]+proploc[2], z_pos[i]]+proploc[3] for i in 1:size(p_airfoilx)[1]]
# Orientation of chord of each airfoil (yaw, pitch, roll)
orien = zeros(length(p_twist_d),3) #twist already included
for i = 1:length(orien[:,1])
orien[i,:] = [-90.0,0.0,270.0]
end
# Processes each airfoil geometry - STRESS/STRAIN CALCS
for i = 1:length(p_strainx[:,1])
# Read airfoil file
x = p_strainx[i,:]
y = p_strainy[i,:]
# Scales the airfoil acording to its chord length
new_x = x#new_x #already scaled
new_y = y#new_y
# plot_airfoil(new_x, new_y; style=styles[i], label="airfoil")
if plots
figure("prop_airfoil")
plot(new_x,new_y)
end
# Reformats into points
npoints = size(new_x)[1]
airfoil = Array{Float64, 1}[[new_x[j], new_y[j], 0] for j in 1:npoints]
# Positions the airfoil along the blade in the right p_orientation
Oaxis = VTKtools.rotation_matrix(orien[i,1], orien[i,2], orien[i,3])
invOaxis = inv(Oaxis)
airfoil = VTKtools.countertransform(airfoil, invOaxis, Os[i])
spinaxis = VTKtools.rotation_matrix(0.0, 0.0, azimuth_deg)
# invspinaxis = inv(spinaxis)
airfoil = transform(airfoil, spinaxis, [proploc[1],proploc[2],proploc[3]])
push!(crosssections, airfoil)
push!(strains, p_strain[i,:])
push!(stress1, stresslayer[1,i,:])
push!(stress2, stresslayer[2,i,:])
push!(stressplot, stress[i,:])
push!(buckle, p_c_bucklingplot[i,:])
push!(point_datas, [j for j in npoints*(i-1)+1:npoints*i])
end
# #generate other blade
# Os = [ [x_pos[i]+proploc[1], -y_pos[i]+proploc[2], z_pos[i]]+proploc[3] for i in 1:size(p_airfoilx)[1]]
# for i = length(p_strainx[:,1]):-1:1
#
# # Read airfoil file
# x = p_strainx[i,:]
# y = p_strainy[i,:]
#
# # Scales the airfoil acording to its chord length
# new_x = x#new_x #already scaled
# new_y = y#new_y
#
# # plot_airfoil(new_x, new_y; style=styles[i], label="airfoil")
# if plots
# figure("prop_airfoil")
# plot(new_x,new_y)
# end
#
# # Reformats into points
# npoints = size(new_x)[1]
# airfoil = Array{Float64, 1}[[-new_x[j], new_y[j], 0] for j in 1:npoints]
#
# # Positions the airfoil along the blade in the right p_orientation
# Oaxis = VTKtools.rotation_matrix(orien[i,1], orien[i,2], orien[i,3])
# invOaxis = inv(Oaxis)
# airfoil = VTKtools.countertransform(airfoil, invOaxis, Os[i])
#
# spinaxis = VTKtools.rotation_matrix(0.0, 0.0, 90.0)
# # invspinaxis = inv(spinaxis)
# airfoil = transform(airfoil, spinaxis, [proploc[1],proploc[2],proploc[3]])
#
#
# push!(crosssections, airfoil)
#
# push!(strains, p_strain[i,:])
# push!(stress1, stresslayer[1,i,:])
# push!(stress2, stresslayer[2,i,:])
# push!(stressplot, stress[i,:])
# push!(buckle, p_c_bucklingplot[i,:])
# push!(point_datas, [j for j in npoints*(i-1)+1:npoints*i])
# end
# Generates cells in VTK Legacy format
points, vtk_cells, strain = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=strains)
_, _, stresses1 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stress1)
_, _, stresses2 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stress2)
_, _, stresses6 = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=stressplot)
_, _, bucklecon = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=buckle)
_, _, point_datas = VTKtools.multilines2vtkmulticells(crosssections, sections;point_datas=point_datas)
# Formats the point data for generateVTK
data = []
push!(data, Dict(
"field_name" => "Strain",
"field_type" => "scalar",
"field_data" => strain))
push!(data, Dict(
"field_name" => "uni_stress",
"field_type" => "scalar",
"field_data" => stresses1))
push!(data, Dict(
"field_name" => "weave_stress",
"field_type" => "scalar",
"field_data" => stresses2))
push!(data, Dict(
"field_name" => "stress",
"field_type" => "scalar",
"field_data" => stresses6))
push!(data, Dict(
"field_name" => "Buckling_Constraint",
"field_type" => "scalar",
"field_data" => bucklecon))
push!(data, Dict(
"field_name" => "PointIndex",
"field_type" => "scalar",
"field_data" => point_datas))
# Generates the vtk file
VTKtools.generateVTK("$(file_name)prop$(propnum)bladenum$(bladenum).$printiter", points; cells=vtk_cells, point_data=data, keep_points=false)
end
function transform(V::Array{Float64,1},
M::Array{Float64,2}, T::Array{Float64,1})
return M*(V-T)+T
end
function transform(Vs::Array{Array{Float64,1},1},
M::Array{Float64,2}, T::Array{Float64,1})
out = Array{Float64,1}[]
for V in Vs
push!(out, transform(V, M, T))
end
return out
end
#Generate prop with all airfoil points
# y_pos = p_yloc#Rtip*p_radii # span position of each section
# x_pos = p_xloc#[y*tan(sweep[i]) for (i,y) in enumerate(y_pos)]
# z_pos = p_zloc#[y*tan(dihedral[i]) for (i,y) in enumerate(y_pos)]
# # PARAMETERS
# r = fill(1.0,length(p_radii)) # Expansion ratio in both surfaces of each airfoil
#
# sections = fill(Tuple{Float64,Int64,Float64,Bool}[(1.0, 10, 1.0, false)],length(p_radii)-1)
#
# # Leading edge position of each airfoil
# Os = [ [x_pos[i], y_pos[i], z_pos[i]] for i in 1:size(p_airfoilx)[1]]
# # Orientation of chord of each airfoil (yaw, pitch, roll)
# orien = zeros(length(p_twist_d),3) #twist already included
# for i = 1:length(orien[:,1])
# orien[i,:] = [p_twist_d[i],p_sweep_d[i],270.0]
# end
#
#
# crosssections = [] # It will store here the cross sections for lofting
# point_datas = []
#
# # Processes each airfoil geometry
# for i = 1:length(p_airfoilx[:,1])
#
# # Read airfoil file
# x = p_airfoilx[i,:]
# y = p_airfoily[i,:]
#
# # Scales the airfoil acording to its chord length
# new_x = chord[i]*x#new_x
# new_y = chord[i]*y#new_y
#
# # plot_airfoil(new_x, new_y; style=styles[i], label="airfoil")
# if plots
# figure("wing_airfoil")
# plot(new_x,new_y)
# end
#
# # Reformats into points
# npoints = size(new_x)[1]
# airfoil = Array{Float64, 1}[[new_x[j], new_y[j], 0] for j in 1:npoints]
#
# # Positions the airfoil along the blade in the right p_orientation
# Oaxis = VTKtools.rotation_matrix(orien[i,1], orien[i,2], orien[i,3])
# invOaxis = inv(Oaxis)
# airfoil = VTKtools.countertransform(airfoil, invOaxis, Os[i])
#
# push!(crosssections, airfoil)
# push!(point_datas, [j for j in npoints*(i-1)+1:npoints*i])
#
# end
#
# # Generates cells in VTK Legacy format
# points, vtk_cells, pt_idx = VTKtools.multilines2vtkmulticells(crosssections, sections;
# point_datas=point_datas)
#
# data = []
# push!(data, Dict(
# "field_name" => "Point_index",
# "field_type" => "scalar",
# "field_data" => pt_idx
# )
# )
#
# # Generates the vtk file for geometry
# VTKtools.generateVTK("$(file_name)_geom$printiter", points; cells=vtk_cells, point_data=data, keep_points=false)
|
{"hexsha": "4acbef55b4d631a456eb4827054ebb249af0097d", "size": 18783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/save_vtk.jl", "max_stars_repo_name": "byuflowlab/moore2019multipropopt", "max_stars_repo_head_hexsha": "116e2ec2ec7885285b8865ef571864874dfa4574", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-17T14:22:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T14:30:49.000Z", "max_issues_repo_path": "src/save_vtk.jl", "max_issues_repo_name": "byuflowlab/moore2019multipropopt", "max_issues_repo_head_hexsha": "116e2ec2ec7885285b8865ef571864874dfa4574", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/save_vtk.jl", "max_forks_repo_name": "byuflowlab/moore2019multipropopt", "max_forks_repo_head_hexsha": "116e2ec2ec7885285b8865ef571864874dfa4574", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9827586207, "max_line_length": 217, "alphanum_fraction": 0.5995314912, "num_tokens": 6038}
|
from os.path import dirname, join
from pliers.stimuli import ImageStim
from pliers.extractors.base import Extractor, ExtractorResult
import numpy as np
from copy import deepcopy
def get_test_data_path():
"""Returns the path to test datasets """
return join(dirname(__file__), 'data')
class DummyExtractor(Extractor):
''' A dummy Extractor class that always returns random values when
extract() is called. Can set the extractor name inside _extract() to
facilitate testing of results merging etc. '''
_input_type = ImageStim
_log_attributes = ('param_A', 'param_B')
def __init__(self, param_A=None, param_B='pie'):
super(DummyExtractor, self).__init__()
self.param_A = param_A
self.param_B = param_B
def _extract(self, stim, name=None, n_rows=100, n_cols=3, max_time=1000):
data = np.random.randint(0, 1000, (n_rows, n_cols))
onsets = np.random.choice(n_rows*2, n_rows, False)
if name is not None:
self.name = name
return ExtractorResult(data, stim, deepcopy(self), onsets=onsets)
|
{"hexsha": "0e17c4250704b7d253e3aca6d15f159d0b6525e6", "size": 1091, "ext": "py", "lang": "Python", "max_stars_repo_path": "pliers/tests/utils.py", "max_stars_repo_name": "rafiahmed40/media-workflow", "max_stars_repo_head_hexsha": "32411d1214302176b0a3d15e6f68a3071a5e3762", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pliers/tests/utils.py", "max_issues_repo_name": "rafiahmed40/media-workflow", "max_issues_repo_head_hexsha": "32411d1214302176b0a3d15e6f68a3071a5e3762", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pliers/tests/utils.py", "max_forks_repo_name": "rafiahmed40/media-workflow", "max_forks_repo_head_hexsha": "32411d1214302176b0a3d15e6f68a3071a5e3762", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-14T13:48:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-14T13:48:37.000Z", "avg_line_length": 34.09375, "max_line_length": 77, "alphanum_fraction": 0.6956920257, "include": true, "reason": "import numpy", "num_tokens": 273}
|
import numpy as np
import sys
from timeit import default_timer as timer
sys.path.append("../../")
from core import wnn
from encoding import thermometer
from encoding import util
#Load Diabetes data
base_path = "../../dataset/diabetes/"
#2/3 Test
bits_encoding = 20
train_data, train_label, test_data, test_label, data_min, data_max = util.load_3data(base_path)
ths = []
for i in range(len(data_max)):
ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding))
train_bin = []
test_bin = []
i = 0
for data in train_data:
train_bin.append(np.array([], dtype=bool))
t = 0
for v in data:
binarr = ths[t].binarize(v)
train_bin[i] = np.append(train_bin[i], binarr)
t += 1
i += 1
i = 0
for data in test_data:
test_bin.append(np.array([], dtype=bool))
t = 0
for v in data:
binarr = ths[t].binarize(v)
test_bin[i] = np.append(test_bin[i], binarr)
t += 1
i += 1
#print test_label
#Wisard
num_classes = 2
tuple_list = [2, 4, 8, 14, 16, 18, 20, 22, 24, 26, 28, 30]
acc_list = []
test_length = len(test_label)
entry_size = len(train_bin[0])
#print entry_size
for t in tuple_list:
wisard = wnn.Wisard(entry_size, t, num_classes)
wisard.train(train_bin, train_label)
rank_result = wisard.rank(test_bin)
num_hits = 0
for i in range(test_length):
if rank_result[i] == test_label[i]:
num_hits += 1
acc_list.append(float(num_hits)/float(test_length))
#Bloom Wisard
btuple_list = [2, 4, 8, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 40, 56]
bacc_list = []
#capacity = len(train_bin)
capacity = 10
print capacity
for t in btuple_list:
bwisard = wnn.BloomWisard(entry_size, t, num_classes, capacity)
bwisard.train(train_bin, train_label)
rank_result = bwisard.rank(test_bin)
num_hits = 0
for i in range(test_length):
if rank_result[i] == test_label[i]:
num_hits += 1
bacc_list.append(float(num_hits)/float(test_length))
print "Tuples=", tuple_list
print "Wisard Accuracy=", acc_list
print "Tuples=", btuple_list
print "BloomWisard Accuracy=",bacc_list
|
{"hexsha": "6ad3007b95e5d17415b05151d343ee3326e45e1d", "size": 2157, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiment/diabetes/accuracy_info.py", "max_stars_repo_name": "leandro-santiago/bloomwisard", "max_stars_repo_head_hexsha": "4c02610c4ef2d2cf8424797c8a815da182ca2383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-25T17:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T14:26:26.000Z", "max_issues_repo_path": "experiment/diabetes/accuracy_info.py", "max_issues_repo_name": "leandro-santiago/bloomwisard", "max_issues_repo_head_hexsha": "4c02610c4ef2d2cf8424797c8a815da182ca2383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiment/diabetes/accuracy_info.py", "max_forks_repo_name": "leandro-santiago/bloomwisard", "max_forks_repo_head_hexsha": "4c02610c4ef2d2cf8424797c8a815da182ca2383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4456521739, "max_line_length": 95, "alphanum_fraction": 0.65878535, "include": true, "reason": "import numpy", "num_tokens": 657}
|
import csv
import os
import numpy as np
working_dir = os.getcwd()
clf1_out = os.path.join(working_dir, "classifier1.tsv")
clf2_out = os.path.join(working_dir, "classifier2.tsv")
clf3_out = os.path.join(working_dir, "classifier3.tsv")
weights = [1.0,1.0,1.0]
def return_prob(classifier_path):
all_prob = []
with open(classifier_path) as tsvfile:
tsvreader = csv.reader(tsvfile, delimiter="\t")
for line in tsvreader:
line = np.asarray([float(val) for val in line], dtype=np.float32)
all_prob.append(line)
return all_prob
def create_ensemble(clf1_file, clf2_file, clf3_file):
prob1 = return_prob(clf1_file)
prob2 = return_prob(clf2_file)
prob3 = return_prob(clf3_file)
results = []
for i in range(0,len(prob1)):
weighted_sum = weights[0] * prob1[i] + weights[1] * prob2[i] + weights[2] * prob3[i]
results.append(np.argmax(weighted_sum))
return results
result = create_ensemble(clf1_out, clf2_out, clf3_out)
predictions_file = os.path.join(working_dir, "ensemble_predictions.txt")
with open(predictions_file, "w") as out_file:
for line in result:
out_file.write("{}\n".format(line))
out_file.close()
|
{"hexsha": "fc551479c4c1dea7c9e41306ffb93cc6e3b23cf4", "size": 1130, "ext": "py", "lang": "Python", "max_stars_repo_path": "terra/ensemble.py", "max_stars_repo_name": "siddharthvaria/GI-DL", "max_stars_repo_head_hexsha": "715b5fe4426d737ed1b23ffbb812058a90433682", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-20T02:37:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T19:46:46.000Z", "max_issues_repo_path": "terra/ensemble.py", "max_issues_repo_name": "siddharthvaria/GI-DL", "max_issues_repo_head_hexsha": "715b5fe4426d737ed1b23ffbb812058a90433682", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "terra/ensemble.py", "max_forks_repo_name": "siddharthvaria/GI-DL", "max_forks_repo_head_hexsha": "715b5fe4426d737ed1b23ffbb812058a90433682", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9743589744, "max_line_length": 86, "alphanum_fraction": 0.7371681416, "include": true, "reason": "import numpy", "num_tokens": 328}
|
# Shared Memory (part of B.2)
export @cuStaticSharedMem, @cuDynamicSharedMem, CuStaticSharedArray, CuDynamicSharedArray
"""
CuStaticSharedArray(T::Type, dims) -> CuDeviceArray{T,AS.Shared}
Get an array of type `T` and dimensions `dims` (either an integer length or tuple shape)
pointing to a statically-allocated piece of shared memory. The type should be statically
inferable and the dimensions should be constant, or an error will be thrown and the
generator function will be called dynamically.
"""
@inline function CuStaticSharedArray(::Type{T}, dims) where {T}
len = prod(dims)
# NOTE: this relies on const-prop to forward the literal length to the generator.
# maybe we should include the size in the type, like StaticArrays does?
ptr = emit_shmem(T, Val(len))
CuDeviceArray(dims, ptr)
end
macro cuStaticSharedMem(T, dims)
Base.depwarn("@cuStaticSharedMem is deprecated, please use the CuStaticSharedArray function", :CuStaticSharedArray)
quote
CuStaticSharedArray($(esc(T)), $(esc(dims)))
end
end
"""
CuDynamicSharedArray(T::Type, dims, offset::Integer=0) -> CuDeviceArray{T,AS.Shared}
Get an array of type `T` and dimensions `dims` (either an integer length or tuple shape)
pointing to a dynamically-allocated piece of shared memory. The type should be statically
inferable or an error will be thrown and the generator function will be called dynamically.
Note that the amount of dynamic shared memory needs to specified when launching the kernel.
Optionally, an offset parameter indicating how many bytes to add to the base shared memory
pointer can be specified. This is useful when dealing with a heterogeneous buffer of dynamic
shared memory; in the case of a homogeneous multi-part buffer it is preferred to use `view`.
"""
@inline function CuDynamicSharedArray(::Type{T}, dims, offset=0) where {T}
len = prod(dims)
@boundscheck if offset+len > dynamic_smem_size()
throw(BoundsError())
end
ptr = emit_shmem(T) + offset
CuDeviceArray(dims, ptr)
end
macro cuDynamicSharedMem(T, dims, offset=0)
Base.depwarn("@cuDynamicSharedMem is deprecated, please use the CuDynamicSharedArray function", :CuStaticSharedArray)
quote
CuDynamicSharedArray($(esc(T)), $(esc(dims)), $(esc(offset)))
end
end
dynamic_smem_size() = @asmcall("mov.u32 \$0, %dynamic_smem_size;", "=r", true, UInt32, Tuple{})
# get a pointer to shared memory, with known (static) or zero length (dynamic shared memory)
@generated function emit_shmem(::Type{T}, ::Val{len}=Val(0)) where {T,len}
Context() do ctx
eltyp = convert(LLVMType, T; ctx)
T_ptr = convert(LLVMType, LLVMPtr{T,AS.Shared}; ctx)
# create a function
llvm_f, _ = create_function(T_ptr)
# create the global variable
mod = LLVM.parent(llvm_f)
gv_typ = LLVM.ArrayType(eltyp, len)
gv = GlobalVariable(mod, gv_typ, "shmem", AS.Shared)
if len > 0
# static shared memory should be demoted to local variables, whenever possible.
# this is done by the NVPTX ASM printer:
# > Find out if a global variable can be demoted to local scope.
# > Currently, this is valid for CUDA shared variables, which have local
# > scope and global lifetime. So the conditions to check are :
# > 1. Is the global variable in shared address space?
# > 2. Does it have internal linkage?
# > 3. Is the global variable referenced only in one function?
linkage!(gv, LLVM.API.LLVMInternalLinkage)
initializer!(gv, null(gv_typ))
end
# by requesting a larger-than-datatype alignment, we might be able to vectorize.
# we pick 32 bytes here, since WMMA instructions require 32-byte alignment.
# TODO: Make the alignment configurable
alignment!(gv, max(32, Base.datatype_alignment(T)))
# generate IR
Builder(ctx) do builder
entry = BasicBlock(llvm_f, "entry"; ctx)
position!(builder, entry)
ptr = gep!(builder, gv, [ConstantInt(0; ctx), ConstantInt(0; ctx)])
untyped_ptr = bitcast!(builder, ptr, T_ptr)
ret!(builder, untyped_ptr)
end
call_function(llvm_f, LLVMPtr{T,AS.Shared})
end
end
|
{"hexsha": "68faab27d2241959de561f11b013b31cfe19326f", "size": 4335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/device/intrinsics/memory_shared.jl", "max_stars_repo_name": "ovanvincq/CUDA.jl", "max_stars_repo_head_hexsha": "33aa453f30d6f70bd318fa480522a2a993220d7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/device/intrinsics/memory_shared.jl", "max_issues_repo_name": "ovanvincq/CUDA.jl", "max_issues_repo_head_hexsha": "33aa453f30d6f70bd318fa480522a2a993220d7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/device/intrinsics/memory_shared.jl", "max_forks_repo_name": "ovanvincq/CUDA.jl", "max_forks_repo_head_hexsha": "33aa453f30d6f70bd318fa480522a2a993220d7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6826923077, "max_line_length": 121, "alphanum_fraction": 0.6865051903, "num_tokens": 1053}
|
import cv2
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
from .commons import sample_frames_metafunc, sample_clips_metafunc, preprocess_frame_metafunc, preprocess_clip_metafunc
class VideoDataset(object):
def __init__(self, stride, mean, std, resize_to, crop_to, type='frame'):
self.sample_func = sample_frames_metafunc(stride)
self.preprocess_func = preprocess_frame_metafunc(mean, std, resize_to, crop_to)
"""
self.preprocess_func2 = transforms.Compose([
transforms.Resize(resize_to),
#transforms.CenterCrop(crop_to),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
"""
if type == 'clip':
self.sample_func = sample_clips_metafunc(stride)
self.preprocess_func = preprocess_clip_metafunc(mean, std, resize_to, crop_to)
def __call__(self, video_fpath):
X = self.sample_func(video_fpath)
if X.shape[0] == 0:
return None
self.samples = X
return self
def __getitem__(self, idx):
sample = self.samples[idx]
#sample = Image.fromarray(sample, mode='RGB')
sample = self.preprocess_func(sample)
if len(sample.shape) == 3: # HxWxC --> CxHxW
sample = sample.transpose((2, 0, 1))
elif len(sample.shape) == 4: # NxHxWxC --> CxNxHxW
sample = sample.transpose((3, 0, 1, 2))
else:
raise NotImplementedError("Unknown sample of shape {}".format(sample.shape))
return torch.from_numpy(sample).float()
def __len__(self):
return self.samples.shape[0]
|
{"hexsha": "1eb453b98d54f80451ef5e934d3d9c8309f17c23", "size": 1684, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/video_loader.py", "max_stars_repo_name": "Tramac/awesome-video-feature-extractor", "max_stars_repo_head_hexsha": "d160f71cfe4405592442902b867633f2cdccdad6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-05T03:21:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-26T08:45:51.000Z", "max_issues_repo_path": "utils/video_loader.py", "max_issues_repo_name": "Tramac/awesome-video-feature-extractor", "max_issues_repo_head_hexsha": "d160f71cfe4405592442902b867633f2cdccdad6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/video_loader.py", "max_forks_repo_name": "Tramac/awesome-video-feature-extractor", "max_forks_repo_head_hexsha": "d160f71cfe4405592442902b867633f2cdccdad6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-26T08:45:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T08:45:53.000Z", "avg_line_length": 31.7735849057, "max_line_length": 119, "alphanum_fraction": 0.6371733967, "include": true, "reason": "import numpy", "num_tokens": 392}
|
using Markdown
using Pkg
using Blink
# Blink.AtomShell.install()
using Interact
#%%
text = @md_str """# Title
This is a markdown test
## Subsection
and this is a subsection
"""
text2=display(text)
loadbutton = filepicker()
hellobutton = button("Hello!")
goodbyebutton = button("Good bye!")
ui = vbox( # put things one on top of the other
loadbutton,
hbox( # put things one next to the other
pad(1em, hellobutton), # to allow some white space around the widget
pad(1em, goodbyebutton),
),
text
)
display(ui)
#%%
w = Window()
body!(w, ui);
|
{"hexsha": "2b129a7354ab36eccb732481704d78828f9313bd", "size": 590, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lezione15/test_interact.jl", "max_stars_repo_name": "aurelio-amerio/corso-cpp", "max_stars_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:54:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T20:36:39.000Z", "max_issues_repo_path": "lezione15/test_interact.jl", "max_issues_repo_name": "rydeen2045/corso-cpp", "max_issues_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lezione15/test_interact.jl", "max_forks_repo_name": "rydeen2045/corso-cpp", "max_forks_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-08T08:29:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T20:37:12.000Z", "avg_line_length": 18.4375, "max_line_length": 76, "alphanum_fraction": 0.6525423729, "num_tokens": 162}
|
//==================================================================================================
/*!
@file
Defines the type hierarchies for IEEE-754 like types
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_DETAIL_DISPATCH_HIERARCHY_INTEGER_TYPES_HPP_INCLUDED
#define BOOST_SIMD_DETAIL_DISPATCH_HIERARCHY_INTEGER_TYPES_HPP_INCLUDED
#include <boost/simd/detail/dispatch/hierarchy/sized_types.hpp>
#include <cstddef>
namespace boost { namespace dispatch
{
/*!
@ingroup group-tag
@brief Sized integral hierarchy tag
Types are classified as ints_ if they are integral types of sizeof Size.
@tparam T Base hierarchy
@tparam Size Size in bits
**/
template<typename T,std::size_t Size> struct ints_ : sized_type_<T,Size>
{
using parent = sized_type_<T,Size>;
};
/*!
@ingroup group-tag
@brief 8 bits integers hierarchy tag
Types are classified as ints8_ if they are any kind - signed or not - of 8 bits integrals.
@tparam T Base hierarchy
**/
template<typename T> using ints8_ = ints_<T,8>;
/*!
@ingroup group-tag
@brief 16 bits integers hierarchy tag
Types are classified as ints16_ if they are any kind - signed or not - of 16 bits integrals.
@tparam T Base hierarchy
**/
template<typename T> using ints16_ = ints_<T,16>;
/*!
@ingroup group-tag
@brief 32 bits integers hierarchy tag
Types are classified as ints32_ if they are any kind - signed or not - of 32 bits integrals.
@tparam T Base hierarchy
**/
template<typename T> using ints32_ = ints_<T,32>;
/*!
@ingroup group-tag
@brief 64 bits integers hierarchy tag
Types are classified as ints64_ if they are any kind - signed or not - of 64 bits integrals.
@tparam T Base hierarchy
**/
template<typename T> using ints64_ = ints_<T,64>;
/*!
@ingroup group-tag
@brief Integer hierarchy tag
Types are classified as integral_ if they have the proper sizeof and sign.
@tparam T Base hierarchy
@tparam N Size in bits
@tparam Sign Sign encoded as @c signed or @c unsigned
**/
template<typename T, std::size_t N, typename Sign>
struct integral_ : ints_<T,N>
{
using parent = ints_<T,N>;
};
/*!
@ingroup group-tag
@brief 8 bits signed integer hierarchy tag
Types are classified as int8_ if they are signed 8 bits integral types.
@tparam T Base hierarchy
**/
template<typename T> using int8_ = integral_<T,8,signed>;
/*!
@ingroup group-tag
@brief 16 bits signed integer hierarchy tag
Types are classified as int16_ if they are signed 16 bits integral types.
@tparam T Base hierarchy
**/
template<typename T> using int16_ = integral_<T,16,signed>;
/*!
@ingroup group-tag
@brief 32 bits signed integer hierarchy tag
Types are classified as int32_ if they are signed 32 bits integral types.
@tparam T Base hierarchy
**/
template<typename T> using int32_ = integral_<T,32,signed>;
/*!
@ingroup group-tag
@brief 64 bits signed integer hierarchy tag
Types are classified as int64_ if they are signed 64 bits integral types.
@tparam T Base hierarchy
**/
template<typename T> using int64_ = integral_<T,64,signed>;
/*!
@ingroup group-tag
@brief 8 bits signed integer hierarchy tag
Types are classified as int8_ if they are unsigned 8 bits integral types.
@tparam T Base hierarchy
**/
template<typename T> using uint8_ = integral_<T,8,unsigned>;
/*!
@ingroup group-tag
@brief 16 bits signed integer hierarchy tag
Types are classified as int16_ if they are unsigned 16 bits integral types.
@tparam T Base hierarchy
**/
template<typename T> using uint16_ = integral_<T,16,unsigned>;
/*!
@ingroup group-tag
@brief 32 bits signed integer hierarchy tag
Types are classified as int32_ if they are unsigned 32 bits integral types.
@tparam T Base hierarchy
**/
template<typename T> using uint32_ = integral_<T,32,unsigned>;
/*!
@ingroup group-tag
@brief 64 bits signed integer hierarchy tag
Types are classified as int64_ if they are unsigned 64 bits integral types.
@tparam T Base hierarchy
**/
template<typename T> using uint64_ = integral_<T,64,unsigned>;
} }
#endif
|
{"hexsha": "9abdae760bd6264d2fa25de86d306102861ec110", "size": 4557, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/detail/dispatch/hierarchy/integer_types.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/detail/dispatch/hierarchy/integer_types.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/detail/dispatch/hierarchy/integer_types.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 26.1896551724, "max_line_length": 100, "alphanum_fraction": 0.6638139127, "num_tokens": 1107}
|
module Invincy.Parsing
import Data.Vect
import Invincy.Core
%access public export
mutual
data Result : (i, r : Type) -> Type where
Done : Stream t s => s -> r -> Result s r
Partial : Stream t s => Inf (Parser s r) -> Result s r
Failure : Stream t s => String -> Result s r
data Parser : (i, r : Type) -> Type where
MkParser : Stream t s => (s -> Result s r) -> Parser s r
runParser : Parser s r -> s -> Result s r
runParser (MkParser f) = f
implementation Stream t s => Functor (Result s) where
map f (Done i r) = Done i (f r)
map f (Partial k) = assert_total (Partial (MkParser $ map f . runParser k))
map _ f@(Failure s) = f
implementation Functor (Parser s) where
map f (MkParser k) = MkParser $ (\x => map f $ k x)
implementation Stream t s => Applicative (Parser s) where
pure x = MkParser (\i => Done i x)
(MkParser f) <*> g = MkParser $ \i => case f i of
Done i' f' => case runParser g i' of
Done i'' r => Done i'' (f' r)
Partial k => Partial (MkParser $ map f' . runParser k)
Failure f => Failure f
Partial k => Partial $ k <*> g
Failure f => Failure f
infixl 2 <*>|
(<*>|) : Stream t s => Parser s (a -> b) -> Lazy (Parser s a) -> Parser s b
(<*>|) f g = f <*> g
implementation Stream t s => Monad (Parser s) where
f >>= g = MkParser $ \i => case runParser f i of
Done i' f' => runParser (g f') i'
Partial k => Partial $ k >>= g
f@(Failure s) => f
interface Applicative f => LazyAlternative (f : Type -> Type) where
empty : f a
(<|>) : f a -> Lazy (f a) -> f a
implementation Stream t s => LazyAlternative (Parser s) where
empty = MkParser . const $ Failure "an alternative is empty"
f <|> g = MkParser $ \i => case (runParser f i) of
Failure _ => runParser g i
-- this could probably be improved
Partial k => Partial $
let cont = MkParser (\i' => runParser k i');
next = MkParser (\i' => runParser g (i <+> i'))
in cont <|> next
done => done
fail : Stream t s => String -> Parser s r
fail = MkParser . const . Failure
infixl 3 <?>
(<?>) : Stream t s => Parser s a -> String -> Parser s a
(<?>) p s = p <|> fail s
item : Stream t s => Parser s t
item = MkParser $ \i => case uncons i of
Nothing => Partial item
Just (x, xs) => Done xs x
sat : Stream t s => (t -> Bool) -> Parser s t
sat p = do
i <- item
if p i then pure i else fail "sat"
ignore : Stream t s => Parser s a -> Parser s ()
ignore p = p *> pure ()
val : (Eq t, Stream t s) => t -> Parser s ()
val x = ignore (sat (== x))
raw : (Eq t, Stream t s) => s -> Parser s ()
raw l = case uncons l of
Nothing => pure ()
Just (x, xs) => do
sat (== x)
raw xs
pure ()
oneOf : (Eq t, Stream t s) => List t -> Parser s t
oneOf l = sat (flip elem l)
option : Stream t s => Parser s a -> Parser s (Maybe a)
option p = (Just <$> p) <|> (pure Nothing)
manyTill : Stream t s => Parser s a -> Parser s b -> Parser s (List a)
manyTill p t = option t >>= maybe ((<+>) . pure <$> p <*>| manyTill p t) (const $ pure neutral)
many : Stream t s => Parser s a -> Parser s (List a)
many p = option p >>= maybe (pure neutral) (\x => (<+>) . pure <$> pure x <*>| many p)
some : Stream t s => Parser s a -> Parser s (x:List a ** NonEmpty x)
some p = do
first <- p
rest <- many p
pure $ (first :: rest ** IsNonEmpty)
sepBy1 : Stream t s => Parser s a -> Parser s () -> Parser s (x:List a ** NonEmpty x)
sepBy1 x s = do
first <- x
rest <- many (s *> x)
pure $ (first :: rest ** IsNonEmpty)
sepBy : Stream t s => Parser s a -> Parser s () -> Parser s (List a)
sepBy x s = maybe [] getWitness <$> option (sepBy1 x s)
match : Stream t s => Parser s a -> Parser s (s, a)
match p = MkParser $ \i => match' i $ runParser p i
where
match' : s -> Result s a -> Result s (s, a)
match' raw (Done i r) =
let il = toList i
rawl = toList raw
in Done i (fromList (take (minus (length rawl) (length il)) rawl), r)
match' raw (Failure e) = Failure e
match' raw (Partial k) = Partial $ (\(raw', x) => (raw <+> raw', x)) <$> match k
feed : Stream t s => Result s r -> s -> Result s r
feed (Partial k) i = runParser k i
feed (Done i r) i' = Done (i <+> i') r
feed (Failure s) _ = Failure s
digit : Stream Char s => Parser s Char
digit = oneOf ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
integer : Stream Char s => Parser s Integer
integer = cast . pack . getWitness <$> some digit
-- feed (feed (runParser ((list ['f', 'o', 'o'] *> pure False) <|> (list ['f', 'o', 'r'] *> pure True)) ['f']) ['o']) ['o']
-- feed (feed (runParser ((list ['f', 'o', 'o'] *> pure False) <|> (list ['f', 'o', 'r'] *> pure True)) ['f']) ['o']) ['r']
parseWith : Monad m => Parser s r -> m s -> m (Result s r)
parseWith p r = do
v <- r
case runParser p v of
Partial k => parseWith k r
other => pure other
|
{"hexsha": "f904ad3c53373055f895229826ea131bb7d4f88b", "size": 4856, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "Invincy/Parsing.idr", "max_stars_repo_name": "defanor/invincy", "max_stars_repo_head_hexsha": "a8f47b1f249ecbaeb1eac31e3873e85e9e1c634b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-05-24T19:18:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-09T05:49:58.000Z", "max_issues_repo_path": "Invincy/Parsing.idr", "max_issues_repo_name": "defanor/invincy", "max_issues_repo_head_hexsha": "a8f47b1f249ecbaeb1eac31e3873e85e9e1c634b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Invincy/Parsing.idr", "max_forks_repo_name": "defanor/invincy", "max_forks_repo_head_hexsha": "a8f47b1f249ecbaeb1eac31e3873e85e9e1c634b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3290322581, "max_line_length": 123, "alphanum_fraction": 0.5632207578, "num_tokens": 1583}
|
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, \
RidgeRegression
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def select_polynomial_degree(n_samples: int = 100, noise: float = 5):
"""
Simulate data from a polynomial model and use cross-validation to select the best fitting degree
Parameters
----------
n_samples: int, default=100
Number of samples to generate
noise: float, default = 5
Noise level to simulate in responses
"""
# Question 1 - Generate dataset for model f(x)=(x+3)(x+2)(x+1)(x-1)(x-2) + eps for eps Gaussian noise
# and split into training- and testing portions
f = lambda x: (x + 3) * (x + 2) * (x + 1) * (x - 1) * (x - 2)
noise_vector = np.random.normal(0, noise, n_samples)
X = np.linspace(-1.2, 2, n_samples)
y = f(X) + noise_vector
noiseless_y = f(X)
train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=2 / 3)
fig = go.Figure([go.Scatter(x=X, y=noiseless_y, mode="lines+markers",
name="True model"),
go.Scatter(x=train_X, y=train_y,
mode="markers",
name="Train samples"),
go.Scatter(x=test_X, y=test_y, mode="markers",
name="Test samples")], layout=go.Layout(
title=rf"$\text{{True polynomial and noisy samples. noise = {noise},"
rf" m = {n_samples} samples}}$"))
fig.show()
# Question 2 - Perform CV for polynomial fitting with degrees 0,1,...,10
errors = np.ndarray([11, 2], float)
degree_range = range(11)
for degree in degree_range:
errors[degree] = cross_validate(PolynomialFitting(degree), train_X,
train_y, mean_square_error)
minimizer = np.argmin(errors[:, 1])
fig = go.Figure(
[go.Scatter(x=list(degree_range), y=errors[:, 0], mode="lines+markers",
name="train error"),
go.Scatter(x=list(degree_range), y=errors[:, 1], mode="lines+markers",
name="validation error"),
go.Scatter(x=[minimizer], y=[errors[minimizer, 1]], mode="markers",
name="validation error minimizer")
], layout=go.Layout(
title=rf"$\text{{Mean Train and Validation Errors Using 5-fold"
rf" Cross Validation. noise = {noise}, m = {n_samples} "
rf"samples}}$"))
fig.show()
# Question 3 - Using best value of k, fit a k-degree polynomial model and report test error
model = PolynomialFitting(int(minimizer)).fit(train_X, train_y)
print(f"with noise {noise} and {n_samples} samples, k* was {minimizer} and"
f" got a {model.loss(test_X, test_y)} test error.")
def select_regularization_parameter(n_samples: int = 50,
n_evaluations: int = 500):
"""
Using sklearn's diabetes dataset use cross-validation to select the best fitting regularization parameter
values for Ridge and Lasso regressions
Parameters
----------
n_samples: int, default=50
Number of samples to generate
n_evaluations: int, default = 500
Number of regularization parameter values to evaluate for each of the algorithms
"""
# Question 6 - Load diabetes dataset and split into training and testing portions
X, y = datasets.load_diabetes(return_X_y=True)
train_X, test_X, train_y, test_y = train_test_split(X, y,
test_size=n_samples)
minimizers=[1,1]
# Question 7 - Perform CV for different values of the regularization parameter for Ridge and Lasso regressions
for model, min, max, name, minimizer_i in [
(RidgeRegression, 0.0001, 20, "ridge", 0),
(Lasso, 0.0001, 4, "lasso", 1)]:
errors = np.ndarray([n_evaluations, 2], float)
evaluation_range = np.linspace(min, max, n_evaluations)
for i, lam in enumerate(evaluation_range):
errors[i] = cross_validate(model(lam), train_X, train_y,
mean_square_error)
minimizers[minimizer_i] = evaluation_range[np.argmin(errors[:, 1])]
fig = go.Figure(
[go.Scatter(x=evaluation_range, y=errors[:, 0],
mode="lines+markers",
name="train error"),
go.Scatter(x=evaluation_range, y=errors[:, 1],
mode="lines+markers",
name="validation error")
], layout=go.Layout(
title=rf"$\text{{Mean Train and Validation Errors Using 5-fold"
rf" Cross Validation on {name} regressor over the "
rf"diabetes dataset.}}$"))
fig.show()
# Question 8 - Compare best Ridge model, best Lasso model and Least Squares model
ridge_error = RidgeRegression(minimizers[0]).fit(train_X, train_y).loss(
test_X, test_y)
lasso_error = mean_square_error(test_y, Lasso(minimizers[1]).fit(train_X,
train_y).
predict(test_X))
ls_error = LinearRegression().fit(train_X, train_y).loss(test_X, test_y)
print(
f"ridge using lambda = {minimizers[0]} gave a test error of {ridge_error}")
print(
f"lasso using lambda = {minimizers[1]} gave a test error of {lasso_error}")
print(f"least squares gave a test error of {ls_error}")
if __name__ == '__main__':
np.random.seed(0)
select_polynomial_degree()
select_polynomial_degree(noise=0)
select_polynomial_degree(n_samples=1500, noise=10)
select_regularization_parameter()
|
{"hexsha": "4f73d9b9cdbd9dc97c2a7deadaa71a9277b111fa", "size": 5650, "ext": "py", "lang": "Python", "max_stars_repo_path": "exercises/perform_model_selection.py", "max_stars_repo_name": "ereldebel/IML.HUJI", "max_stars_repo_head_hexsha": "1c3d7042071a74ed60f92c013ef6051e2341304c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/perform_model_selection.py", "max_issues_repo_name": "ereldebel/IML.HUJI", "max_issues_repo_head_hexsha": "1c3d7042071a74ed60f92c013ef6051e2341304c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/perform_model_selection.py", "max_forks_repo_name": "ereldebel/IML.HUJI", "max_forks_repo_head_hexsha": "1c3d7042071a74ed60f92c013ef6051e2341304c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5441176471, "max_line_length": 111, "alphanum_fraction": 0.6592920354, "include": true, "reason": "import numpy", "num_tokens": 1458}
|
""" An example of a wide resnet network with Nestorov-momentum back-prop on CIFAR10 data. (details in Zagoruyko and Komodakis, 2017)
"""
import deepnodal as dn
from time import time
import datetime
import numpy as np
# PARAMETERS
n_epochs = 200
batch_size = 128
test_split = 50
max_lr = 0.1
learning_rates = {0:max_lr, 60:max_lr*0.2, 120:max_lr*0.04, 160:max_lr*0.008}
devs = None # set to None if using only one device or N to use N GPUs
input_dims = [32, 32, 3]
k, N = 10, 4
k16, k32, k64, N2 = k*16, k*32, k*64, N*2
arch = [ [ 16, [3, 3], [1, 1]] ] +\
[([k16, [3, 3], [1, 1]], None)] +\
[([k16, [3, 3], [1, 1]], [k16, [1, 1], [1, 1]])] +\
[ [k16, [3, 3], [1, 1]] ] * (N2 - 2) +\
[ [] ] +\
[([k32, [3, 3], [2, 2]], None)] +\
[([k32, [3, 3], [1, 1]], [k32, [1, 1], [2, 2]])] +\
[ [k32, [3, 3], [1, 1]] ] * (N2 - 2) +\
[ [] ] +\
[([k64, [3, 3], [2, 2]], None)] +\
[([k64, [3, 3], [1, 1]], [k64, [1, 1], [2, 2]])] +\
[ [k64, [3, 3], [1, 1]] ] * (N2 - 2) +\
[ [[8, 8], [1, 1]],
"10"]
opverge = [None] +\
[None, True] +\
[None] * (N2 - 2) +\
[None, None, True] +\
[None] * (N2 - 2) +\
[None, None, True] +\
[None] * (N2 - 2) +\
[None, None]
skipcv = [None] +\
[None, None] +\
[None, -1] * (N - 1) +\
[None, None, None] +\
[None, -1] * (N - 1) +\
[None, None, None] +\
[None, -1] * (N - 1) +\
[None, None]
order = ['ant'] +\
['ant', 'a'] +\
['nta', 'dnta'] * (N - 1) +\
['nt', 'ant', 'a'] +\
['nta', 'dnta'] * (N - 1) +\
['nt', 'ant', 'a'] +\
['nta', 'dnta'] * (N - 1) +\
['nta', 'at']
transfn = ['relu'] * (len(arch)-1) + ['softmax']
kernfn = ['xcorr'] * (len(arch)-2) + ['avg', None]
dropout = 0.3
normal = 'batch_norm'
normal_kwds = {'epsilon':1e-5}
window = 'same'
weights = 'vsi'
reguln = "weight_decay"
reguln_kwds = {'scale': 5e-4}
opverge_kwds = {'vergence_fn': 'sum'}
skipcv_kwds = {'vergence_fn': 'sum', 'skip_end': 'inp'}
optimiser = 'mom'
optimiser_kwds = {'momentum': 0.9, 'use_nesterov': True}
gcn, zca, gcn_within_depth = True, False, False
rand_flip, rand_crop = [True, False], 4
net_name = 'wide_resnet_N' + str(N) + '_k' + str(k)
write_dir = '/tmp/dn_logs/'
save_interval = 10
def main(seed=42):
# INPUT DATA
source = dn.loaders.cifar10()
source.read_data(gcn=gcn, zca=zca, gcn_within_depth=gcn_within_depth)
source.partition(seed=seed)
# SPECIFY ARCHITECTURE
mod = dn.stack()
mod.set_arch(arch)
mod.set_order(order)
mod.set_skipcv(skipcv, **skipcv_kwds)
mod.set_opverge(opverge, **opverge_kwds)
mod.set_transfn(transfn)
mod.set_kernfn(kernfn)
mod.set_window(window)
mod.set_dropout(dropout)
mod.set_normal(normal, **normal_kwds)
mod.set_weights(weights)
mod.set_reguln(reguln, **reguln_kwds)
# SPECIFY NETWORK
net = dn.network(net_name)
net.set_subnets(mod)
net.set_inputs(input_dims)
# SPECIFY SUPERVISOR AND TRAINING
sup = dn.hypervisor(devs = devs)
sup.set_optimiser(optimiser, **optimiser_kwds)
sup.set_work(net)
for epoch in sorted(list(learning_rates.keys())):
index = sup.add_schedule(learning_rates[epoch])
# CHECK FOR RESTOREPOINT
modfiler = dn.helpers.model_filer(write_dir, net_name)
restore_point = modfiler.interview()
if restore_point is not None:
seed = restore_point
# TRAIN AND TEST
now = datetime.datetime.utcnow().strftime("%Y%m%d%H%M%S")
log_out = None if write_dir is None else write_dir+net_name+"_"+now
mod_out = None if write_dir is None else log_out + "/" + net_name
schedule = -1
epoch_0 = 0
t0 = time()
with sup.call_session(log_out, seed):
if restore_point is not None:
epoch_0 = int(np.ceil(float(sup.progress[1])/float(source.sets['train']['support'])))
for i in range(epoch_0):
if i in learning_rates:
schedule += 1
sup.use_schedule(schedule)
for i in range(epoch_0, n_epochs):
if i in learning_rates:
schedule += 1
sup.use_schedule(schedule)
while True:
data = source.next_batch('train', batch_size, \
rand_flip=rand_flip, rand_crop=rand_crop)
if not data:
break
sup.train(*data)
data = source.next_batch('test')
summary_str = sup.test(*data, split=test_split)
print("".join(["Epoch {} ({} s): ", summary_str]).format(str(i), str(round(time()-t0))))
if i and mod_out is not None:
if not(i % save_interval) or i == n_epochs -1:
sup.save(mod_out)
if __name__ == '__main__':
main()
|
{"hexsha": "130a86e0cbedefed1f212db6a2237e8022b1d310", "size": 5114, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/cifar10_wide_resnet.py", "max_stars_repo_name": "Bhumbra/DeepNodal", "max_stars_repo_head_hexsha": "33afb2efa5e78ae6558ce60a36bb87c186c1f448", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-06T09:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-06T09:49:42.000Z", "max_issues_repo_path": "examples/cifar10_wide_resnet.py", "max_issues_repo_name": "Bhumbra/DeepNodal", "max_issues_repo_head_hexsha": "33afb2efa5e78ae6558ce60a36bb87c186c1f448", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-14T14:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:46:40.000Z", "max_forks_repo_path": "examples/cifar10_wide_resnet.py", "max_forks_repo_name": "Bhumbra/DeepNodal", "max_forks_repo_head_hexsha": "33afb2efa5e78ae6558ce60a36bb87c186c1f448", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1635220126, "max_line_length": 133, "alphanum_fraction": 0.5146656238, "include": true, "reason": "import numpy", "num_tokens": 1684}
|
from __future__ import print_function, division
import scipy
from keras.datasets import mnist
from keras_contrib.layers.normalization.instancenormalization import InstanceNormalization
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.layers import BatchNormalization, Activation, Embedding, ZeroPadding2D
from keras.models import Sequential, Model
from keras.optimizers import Adam
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, multiply
from keras.layers import Reshape
from keras.layers.merge import concatenate
import datetime
import matplotlib.pyplot as plt
import sys
from data_loader import DataLoader
import numpy as np
import os
import random
from sklearn.metrics import accuracy_score, log_loss, roc_auc_score
from keras.applications.resnet50 import ResNet50
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K
class CCycleGAN():
def __init__(self,img_rows = 48,img_cols = 48,channels = 1, num_classes=7, latent_dim=99):
# Input shape
self.img_rows = img_rows
self.img_cols = img_cols
self.channels = channels
self.img_shape = (self.img_rows, self.img_cols, self.channels)
self.num_classes = num_classes
self.latent_dim = latent_dim
## dict
self.lab_dict = {0: "Angry", 1: "Disgust" , 2: "Fear" , 3: "Happy" , 4: "Sad" , 5: "Surprise" , 6: "Neutral"}
# Configure data loader
self.dataset_name = 'fer2013'
self.data_loader = DataLoader(dataset_name=self.dataset_name,img_res=self.img_shape)
# Calculate output shape of D (PatchGAN)
patch = int(self.img_rows / 2**4)
self.disc_patch = (patch, patch, 1)
# Number of filters in the first layer of G and D
self.gf = 32
self.df = 64
# Loss weights
self.lambda_cycle = 10.0 # Cycle-consistency loss
self.lambda_id = 0.1 * self.lambda_cycle # Identity loss
optimizer = Adam(0.0002, 0.5)
# Build and compile the discriminators
self.d = self.build_discriminator2()
print("******** Discriminator ********")
self.d.summary()
self.d.compile(loss='binary_crossentropy',
optimizer=optimizer,
metrics=['accuracy'])
#-------------------------
# Construct Computational
# Graph of Generators
#-------------------------
def build_discriminator(self):
def d_layer(layer_input, filters, f_size=4, normalization=True):
"""Discriminator layer"""
d = Conv2D(filters, kernel_size=f_size, strides=2, padding='same')(layer_input)
d = LeakyReLU(alpha=0.2)(d)
if normalization:
d = InstanceNormalization()(d)
return d
img = Input(shape=self.img_shape)
label = Input(shape=(1,), dtype='int32')
label_embedding = Flatten()(Embedding(self.num_classes, np.prod(self.img_shape))(label))
flat_img = Flatten()(img)
model_input = multiply([flat_img, label_embedding])
d0 = Reshape(self.img_shape)(model_input)
d1 = d_layer(d0, self.df, normalization=False)
d2 = d_layer(d1, self.df*2)
d3 = d_layer(d2, self.df*4)
d4 = d_layer(d3, self.df*8)
validity = Conv2D(1, kernel_size=4, strides=1, padding='same')(d4)
d5 = Dense(128)(validity)
d6 = LeakyReLU(alpha=0.2)(d5)
d7 = Dropout(0.4)(d6)
d77 = Flatten()(d7)
d8 = Dense(1, activation='sigmoid')(d77)
return Model([label,img], d8)
def build_discriminator2(self):
#img = Input(shape=self.img_shape)
label = Input(shape=(1,), dtype='int32')
label_embedding = Flatten()(Embedding(self.num_classes, 100)(label))
#flat_img = Flatten()(img)
#model_input = multiply([flat_img, label_embedding])
base_model = ResNet50(weights= 'imagenet', include_top=False, input_shape= (48,48,3))
# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
#latent_vect = Flatten()(x)
latent_concat = concatenate([x, label_embedding])
# let's add a fully-connected layer
f = Dense(1024, activation='relu')(latent_concat)
# and a logistic layer -- let's say we have 200 classes
predictions = Dense(1, activation='sigmoid')(f)
return Model([label,base_model.input], predictions)
def generate_new_labels(self,labels0):
labels1 = []
for i in range(len(labels0)):
allowed_values = list(range(0, self.num_classes))
allowed_values.remove(labels0[i])
labels1.append(random.choice(allowed_values))
return np.array(labels1,'int32')
def train(self, epochs, batch_size=1, sample_interval=50):
start_time = datetime.datetime.now()
# Adversarial loss ground truths
valid = np.ones((batch_size,1))
fake = np.zeros((batch_size,1))
for epoch in range(epochs):
for batch_i, (labels0 , imgs) in enumerate(self.data_loader.load_batch(batch_size=batch_size,convertRGB=True)):
labels1 = self.generate_new_labels(labels0)
#labels01 = self.generate_new_labels(labels0)
idx = np.random.permutation(2*labels1.shape[0])
_labels = np.concatenate((labels0,labels1))
_imgs = np.concatenate((imgs,imgs))
_vf = np.concatenate((valid,fake))
_labels = _labels[idx]
_imgs = _imgs[idx]
_vf = _vf[idx]
# ----------------------
# Train Discriminators
# ----------------------
# Train the discriminators (original images = real / translated = Fake)
d_loss = self.d.train_on_batch([_labels,_imgs], _vf)
#d_loss_real = self.d.train_on_batch([labels0,imgs], valid)
#d_loss_real_fake = self.d.train_on_batch([labels01,imgs], fake)
#d_loss = (1/2) * np.add(d_loss_real, d_loss_real_fake)
elapsed_time = datetime.datetime.now() - start_time
# Plot the progress
print ("[Epoch %d/%d] [Batch %d/%d] [D loss: %f, acc: %3d%%] time: %s " \
% ( epoch, epochs,
batch_i, self.data_loader.n_batches,
d_loss[0], 100*d_loss[1],
elapsed_time))
# If at save interval => save generated image samples
if batch_i % sample_interval == 0:
self.sample_images(epoch, batch_i)
def sample_images(self, epoch, batch_i):
t1 = np.ones(self.data_loader.lab_vect_test.shape[0])
t0 = np.zeros(self.data_loader.lab_vect_test.shape[0])
t = np.concatenate((t0,t1))
print("t:",t.shape)
print("t:",t)
labels1_ = self.generate_new_labels(self.data_loader.lab_vect_test)
test_imgs = self.data_loader.img_vect_test_RGB
pred_prob_fake = self.d.predict([labels1_,test_imgs])
pred_prob_valid_ = self.d.predict([self.data_loader.lab_vect_test,test_imgs])
pred_probs = np.concatenate((pred_prob_fake.squeeze(),pred_prob_valid_.squeeze()))
preds = (pred_probs > 0.5)*1
print("preds:",preds.shape)
print("preds:",preds)
print("pred_probs:",pred_probs.shape)
print("pred_probs:",pred_probs)
print("acc[perfect]:",accuracy_score(t,t))
print("log_loss[perfect]:",log_loss(t,t))
print("roc_auc_score[perfect]:",roc_auc_score(t,t))
print("acc[perfect]:",accuracy_score(preds,preds))
#print("log_loss[perfect]:",log_loss(pred_probs,pred_probs))
#print("roc_auc_score[perfect]:",roc_auc_score(pred_probs,pred_probs))
acc = accuracy_score(t,preds)
ll = log_loss(t,pred_probs)
auc = roc_auc_score(t,pred_probs)
print("Accuracy[test:"+str(self.data_loader.lab_vect_test.shape[0])+"]:",acc)
print("LogLoss[test:"+str(self.data_loader.lab_vect_test.shape[0])+"]:",ll)
print("AUC[test:"+str(self.data_loader.lab_vect_test.shape[0])+"]:",auc)
if __name__ == '__main__':
gan = CCycleGAN()
gan.train(epochs=200, batch_size=64, sample_interval=200)
|
{"hexsha": "6cfc93338e0162cf6e5a5b8626c27e083c789def", "size": 9243, "ext": "py", "lang": "Python", "max_stars_repo_path": "ccyclegan/classifier.py", "max_stars_repo_name": "gtesei/Keras-GAN", "max_stars_repo_head_hexsha": "8f57901fb637d8d179e780a191683da347af30b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-15T10:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T09:27:47.000Z", "max_issues_repo_path": "ccyclegan/classifier.py", "max_issues_repo_name": "gtesei/Keras-GAN", "max_issues_repo_head_hexsha": "8f57901fb637d8d179e780a191683da347af30b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ccyclegan/classifier.py", "max_forks_repo_name": "gtesei/Keras-GAN", "max_forks_repo_head_hexsha": "8f57901fb637d8d179e780a191683da347af30b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-11-21T12:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T16:40:32.000Z", "avg_line_length": 38.037037037, "max_line_length": 123, "alphanum_fraction": 0.5916910094, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2107}
|
/**
* @file start.cpp
* @author Noah Witt <nawitt18@ole.augie.edu>
* @brief tests for the start system
* @version 0.1
* @date 2021-10-18
*
* @copyright Copyright (c) 2021
*
*/
#include <boost/test/unit_test.hpp>
#include <boost/log/trivial.hpp>
#include "../start.hpp"
BOOST_AUTO_TEST_SUITE(start_test)
BOOST_AUTO_TEST_CASE(basic_start_test) {
std::string a_input_data = "";
std::stringstream a_input(a_input_data);
std::stringstream a_output;
start("./test_files/test_start_a.S", 10000, a_input, a_output);
std::string result = a_output.str();
BOOST_LOG_TRIVIAL(debug) <<"test:"<< result;
BOOST_ASSERT(result=="105 775 ABC 3 976 3 ");
}
BOOST_AUTO_TEST_SUITE_END()
|
{"hexsha": "4a9bb5af40b716d302c2466e7d2cd8d27b9832e1", "size": 708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/start.cpp", "max_stars_repo_name": "noah-witt/riscv-engine", "max_stars_repo_head_hexsha": "4caf55da2d8e5d473ac7e0634bef6a1d5ddc728b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/start.cpp", "max_issues_repo_name": "noah-witt/riscv-engine", "max_issues_repo_head_hexsha": "4caf55da2d8e5d473ac7e0634bef6a1d5ddc728b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/start.cpp", "max_forks_repo_name": "noah-witt/riscv-engine", "max_forks_repo_head_hexsha": "4caf55da2d8e5d473ac7e0634bef6a1d5ddc728b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2857142857, "max_line_length": 67, "alphanum_fraction": 0.6949152542, "num_tokens": 198}
|
import os
import re
import numpy as np
from monty.io import zopen
from monty.serialization import loadfn, dumpfn
hf = re.compile(r"\s+SCF energy\s+=\s+([\-\.0-9]+)")
mp2 = re.compile(r"\s+MP2 energy\s+=\s+([\-\.0-9]+)")
ccsd_corr = re.compile(r"\s+CCSD correlation energy\s+=\s+([\-\.0-9]+)")
ccsd_total = re.compile(r"\s+CCSD total energy\s+=\s+([\-\.0-9]+)")
ccsdt_corr = re.compile(r"\s+CCSD\(T\) correlation energy\s+=\s+([\-\.0-9]+)")
ccsdt_total = re.compile(r"\s+CCSD\(T\) total energy\s+=\s+([\-\.0-9]+)")
alpha_svp_tzvp = 10.390
alpha_tzvpp_qzvpp = 7.880
beta_svp_tzvp = 2.400
beta_tzvpp_qzvpp = 2.970
def correct_hf(e1, e2, n1, n2, alpha=7.880):
return e2 + (e2 - e1) / (np.exp(alpha * (np.sqrt(n2) - np.sqrt(n1))) - 1)
def correct_wft(e1, e2, n1, n2, beta=2.970):
return (n1 ** beta * e1 - n2 ** beta * e2) / (n1 ** beta - n2 ** beta)
all_data = loadfn("/Users/ewcss/data/ssbt/20211023_cc/all_cc_data.json")
groups = dict()
for name, data in all_data.items():
contents = name.split("_")
groupname = "_".join([contents[0], contents[1], contents[-1]])
meth_basis = "_".join([contents[3], contents[4]])
if groupname not in groups:
groups[groupname] = {meth_basis: data}
else:
groups[groupname][meth_basis] = data
dumpfn(groups, "/Users/ewcss/data/ssbt/20220201_cc/grouped_cc_data.json")
full_corrected_data = dict()
for groupname, groupdata in groups.items():
try:
hf = correct_hf(groupdata["CCSD_def2-TZVPP"]["hf"],
groupdata["CCSD_def2-QZVPP"]["hf"],
3,
4,
alpha=alpha_tzvpp_qzvpp)
ccsd = correct_wft(groupdata["CCSD_def2-TZVPP"]["ccsd_corr"],
groupdata["CCSD_def2-QZVPP"]["ccsd_corr"],
3,
4,
beta=beta_tzvpp_qzvpp)
paren_t = correct_wft(groupdata["CCSD(T)_def2-SVP"]["ccsdt_corr"],
groupdata["CCSD(T)_def2-TZVP"]["ccsdt_corr"],
2,
3,
beta=beta_svp_tzvp)
total_e = hf + ccsd + paren_t
full_corrected_data[groupname] = total_e
except KeyError:
continue
dumpfn(full_corrected_data, "/Users/ewcss/data/ssbt/20220201_cc/full_corrected_cc_data.json")
# Not currently correcting HF or CCSD
# Only applying an extrapolation to (T), due to issues with QZVPP calculations
corrected_data = dict()
for groupname, groupdata in groups.items():
try:
hf_ccsd = groupdata["CCSD_def2-TZVPP"]["ccsd_total"]
paren_t = correct_wft(groupdata["CCSD(T)_def2-SVP"]["ccsdt_corr"],
groupdata["CCSD(T)_def2-TZVP"]["ccsdt_corr"],
2,
3,
beta=beta_svp_tzvp)
total_e = hf_ccsd + paren_t
corrected_data[groupname] = total_e
except KeyError:
continue
dumpfn(corrected_data, "/Users/ewcss/data/ssbt/20220201_cc/corrected_t_cc_data.json")
corrected_small_data = dict()
for groupname, groupdata in groups.items():
try:
hf = correct_hf(groupdata["CCSD(T)_def2-SVP"]["hf"],
groupdata["CCSD(T)_def2-TZVP"]["hf"],
3,
4,
alpha=alpha_svp_tzvp)
ccsd = correct_wft(groupdata["CCSD(T)_def2-SVP"]["ccsd_corr"],
groupdata["CCSD(T)_def2-TZVP"]["ccsd_corr"],
3,
4,
beta=beta_svp_tzvp)
paren_t = correct_wft(groupdata["CCSD(T)_def2-SVP"]["ccsdt_corr"],
groupdata["CCSD(T)_def2-TZVP"]["ccsdt_corr"],
2,
3,
beta=beta_svp_tzvp)
total_e = hf + ccsd + paren_t
corrected_small_data[groupname] = total_e
except KeyError:
continue
dumpfn(corrected_small_data, "/Users/ewcss/data/ssbt/20220201_cc/corrected_small_cc_data.json")
uncorrected_data = dict()
for groupname, groupdata in groups.items():
try:
total_ccsd_e = groupdata["CCSD_def2-TZVPP"]["ccsd_total"]
uncorrected_data[groupname] = total_ccsd_e
except KeyError:
continue
dumpfn(uncorrected_data, "/Users/ewcss/data/ssbt/20220201_cc/uncorrected_cc_data.json")
|
{"hexsha": "cbe6ab9014dfa56fd379b30cf03fbad26de7d3d3", "size": 4498, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/calc/parsing_cc.py", "max_stars_repo_name": "espottesmith/hydrobench", "max_stars_repo_head_hexsha": "e117774c94cff11debd764d231757174ec211e99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-16T19:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T19:19:15.000Z", "max_issues_repo_path": "src/calc/parsing_cc.py", "max_issues_repo_name": "espottesmith/hydrobench", "max_issues_repo_head_hexsha": "e117774c94cff11debd764d231757174ec211e99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calc/parsing_cc.py", "max_forks_repo_name": "espottesmith/hydrobench", "max_forks_repo_head_hexsha": "e117774c94cff11debd764d231757174ec211e99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6984126984, "max_line_length": 95, "alphanum_fraction": 0.5640284571, "include": true, "reason": "import numpy", "num_tokens": 1283}
|
# _*_ coding: utf-8 _*_
from __future__ import absolute_import, division, print_function
import os
import sys
module_path = os.path.abspath(os.path.join('..'))
sys.path.append(module_path)
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import auc, roc_curve
from model.get_datasets import load_datasets
from optparse import OptionParser
# 构建模型输入
def pre_train():
train_all, test = load_datasets()
# train_all.fillna(-1,inplace=True)
# test.fillna(-1,inplace=True)
y_train_all = train_all['orderType']
id_train = train_all['userid']
train_all.drop(['orderType', 'userid'], axis=1, inplace=True)
id_test = test['userid']
test.drop(['userid'], axis=1, inplace=True)
print("train_all: ({}), test: ({})".format(train_all.shape, test.shape))
return train_all, y_train_all, id_train, test, id_test
# 评估函数
def evaluate_score(predict, y_true):
false_positive_rate, true_positive_rate, thresholds = roc_curve(y_true, predict, pos_label=1)
auc_score = auc(false_positive_rate, true_positive_rate)
return auc_score
def main(options):
print("load train test datasets")
train_all, y_train_all, id_train, test, id_test = pre_train()
model_params = {
'boosting_type': 'gbdt',
'objective': 'binary',
'metric': 'auc',
'learning_rate': options.learning_rate,
'num_leaves': options.num_leaves,
'min_child_weight': options.min_child_weight,
'feature_fraction': options.feature_fraction,
'bagging_fraction': options.bagging_fraction,
'lambda_l1': options.lambda_l1,
'lambda_l2': options.lambda_l2,
'bagging_seed': 10,
'feature_fraction_seed': 10,
'nthread': -1,
'verbose': 0
}
predict_feature = 'lgbm_roof_fold{}_lr{}_numleaves{}_minchildweight{}_featurefraction{}_baggingfraction{}_l1-{}_l2-{}seed{}'.format(
options.roof_flod, options.learning_rate, options.num_leaves, options.min_child_weight, options.feature_fraction,
options.bagging_fraction, options.lambda_l1, options.lambda_l2, options.seed
)
roof_flod = options.roof_flod
kf = StratifiedKFold(n_splits=roof_flod, shuffle=True, random_state=10)
pred_train_full = np.zeros(train_all.shape[0])
pred_test_full = 0
cv_scores = []
for i, (dev_index, val_index) in enumerate(kf.split(train_all, y_train_all)):
print('========== perform fold {}, train size: {}, validate size: {} =========='.format(i, len(dev_index),
len(val_index)))
train_x, val_x = train_all.ix[dev_index], train_all.ix[val_index]
train_y, val_y = y_train_all[dev_index], y_train_all[val_index]
lgb_train = lgb.Dataset(train_x, train_y)
lgb_eval = lgb.Dataset(val_x, val_y, reference=lgb_train)
model = lgb.train(model_params, lgb_train, num_boost_round=5000, valid_sets=[lgb_train, lgb_eval],
valid_names=['train', 'eval'], early_stopping_rounds=100, verbose_eval=200)
# predict validate
predict_valid = model.predict(val_x, num_iteration=model.best_iteration)
valid_auc = evaluate_score(predict_valid, val_y)
# predict test
predict_test = model.predict(test, num_iteration=model.best_iteration)
print('valid_auc = {}'.format(valid_auc))
cv_scores.append(valid_auc)
# run-out-of-fold predict
pred_train_full[val_index] = predict_valid
pred_test_full += predict_test
mean_cv_scores = np.mean(cv_scores)
print('Mean cv auc:', mean_cv_scores)
print("saving train predictions for ensemble")
train_pred_df = pd.DataFrame({'userid': id_train})
train_pred_df[predict_feature] = pred_train_full
train_pred_df.to_csv("./ensemble/train/lq_lgbm_roof{}_predict_train_cv{}_{}.csv".format(roof_flod, mean_cv_scores, predict_feature),
index=False, columns=['userid', predict_feature])
print("saving test predictions for ensemble")
pred_test_full = pred_test_full / float(roof_flod)
test_pred_df = pd.DataFrame({'userid': id_test})
test_pred_df[predict_feature] = pred_test_full
test_pred_df.to_csv("./ensemble/test/lq_lgbm_roof{}_predict_test_cv{}_{}.csv".format(roof_flod, mean_cv_scores, predict_feature),
index=False, columns=['userid', predict_feature])
if __name__ == "__main__":
print("========== lq lightgbm run out of fold ==========")
parser = OptionParser()
parser.add_option(
"--fl", "--roof_flod",
dest="roof_flod",
default=5,
type='int'
)
parser.add_option(
"--lr", "--learning_rate",
dest="learning_rate",
default=0.01,
type='float'
)
parser.add_option(
"--mw", "--min_child_weight",
dest="min_child_weight",
default=1,
type='int'
)
parser.add_option(
"--ff", "--feature_fraction",
dest="feature_fraction",
default=0.9,
type='float'
)
parser.add_option(
"--nl", "--num_leaves",
dest="num_leaves",
default=64,
type='int'
)
parser.add_option(
"--bf", "--bagging_fraction",
dest="bagging_fraction",
default=0.7,
type='float'
)
parser.add_option(
"--l1", "--lambda_l1",
dest="lambda_l1",
default=0.5,
type='float'
)
parser.add_option(
"--l2", "--lambda_l2",
dest="lambda_l2",
default=0.5,
type='float'
)
parser.add_option(
"--sd", "--seed",
dest="seed",
default=0,
type='int'
)
ops, _ = parser.parse_args()
main(ops)
|
{"hexsha": "ed5b007c8fcbc77a80c7b56bd6089f1a3ba09d0e", "size": 5876, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/model_roof/lq_lightgbm_roof.py", "max_stars_repo_name": "SunnyMarkLiu/Datacastle_Travel_Services_Predict", "max_stars_repo_head_hexsha": "0823a8aaab4e42a7ee5067171901c6f597bc5d7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2018-02-08T09:38:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-14T00:11:04.000Z", "max_issues_repo_path": "model/model_roof/lq_lightgbm_roof.py", "max_issues_repo_name": "QianguoSun/Datacastle_Travel_Services_Predict", "max_issues_repo_head_hexsha": "0823a8aaab4e42a7ee5067171901c6f597bc5d7e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/model_roof/lq_lightgbm_roof.py", "max_forks_repo_name": "QianguoSun/Datacastle_Travel_Services_Predict", "max_forks_repo_head_hexsha": "0823a8aaab4e42a7ee5067171901c6f597bc5d7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2018-02-08T15:32:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-20T08:52:26.000Z", "avg_line_length": 33.197740113, "max_line_length": 136, "alphanum_fraction": 0.6349557522, "include": true, "reason": "import numpy", "num_tokens": 1437}
|
Require Import Crypto.Specific.Framework.RawCurveParameters.
Require Import Crypto.Util.LetIn.
(***
Modulus : 2^489 - 21
Base: 48.9
***)
Definition curve : CurveParameters :=
{|
sz := 10%nat;
base := 48 + 9/10;
bitwidth := 64;
s := 2^489;
c := [(1, 21)];
carry_chains := Some [seq 0 (pred 10); [0; 1]]%nat;
a24 := None;
coef_div_modulus := Some 2%nat;
goldilocks := None;
karatsuba := None;
montgomery := false;
freeze := Some true;
ladderstep := false;
mul_code := None;
square_code := None;
upper_bound_of_exponent_loose := None;
upper_bound_of_exponent_tight := None;
allowable_bit_widths := None;
freeze_extra_allowable_bit_widths := None;
modinv_fuel := None
|}.
Ltac extra_prove_mul_eq _ := idtac.
Ltac extra_prove_square_eq _ := idtac.
|
{"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Specific/solinas64_2e489m21_10limbs/CurveParameters.v"}
|
Set Implicit Arguments.
(*** preliminary Meta Theory assumptions ***)
Require Export Prelim.
Module Type TG.
Parameter set : Type.
(** * Axioms of set theory **)
(** Finally, we add the primitive operators and axioms of Tarski-Grothendieck Set Theory (Zermelo-Fraenkel with Grothendieck Universes). ***)
(** In is the membership relation on i. We use x :e y as notation to mean "x is a member of y" and x /:e y as notation for "x is not a member of y." **)
Parameter In : set -> set -> Prop.
Notation "x ':e' y" := (In x y) (at level 70).
Notation "x '/:e' y" := (~(In x y)) (at level 70).
(** Subq is the subset relation on set. We use X c= Y as notation to mean "X is a subset of Y" and X /c= Y as notation for "X is not a subset of Y." **)
Definition Subq : set -> set -> Prop :=
fun X Y => forall x : set, x :e X -> x :e Y.
Notation "X 'c=' Y" := (Subq X Y) (at level 70).
Notation "X '/c=' Y" := (~(Subq X Y)) (at level 70).
(** Two sets are equal if they have the same elements. Equivalently, we can always prove two sets are equal by proving they are subsets of each other. **)
Axiom set_ext : forall X Y : set, X c= Y -> Y c= X -> X = Y.
(** Sets are formed iteratively, so we can prove properties about all sets by induction on membership.
Suppose P is a property of sets. If we can prove P holds for X from the inductive hypothesis that P holds for all member of X,
then P must hold for all sets. **)
Axiom In_ind : forall P : set -> Prop, (forall X : set, (forall x, x :e X -> P x) -> P X) -> forall X : set, P X.
(** Empty is the empty set. **)
Parameter Empty : set.
Axiom EmptyE : forall x : set, x /:e Empty.
(** Given two sets y and z, (UPair y z) is {y,z}. **)
Parameter UPair : set -> set -> set.
Axiom UPairI1 :
forall y z : set, y :e (UPair y z).
Axiom UPairI2 :
forall y z : set, z :e (UPair y z).
Axiom UPairE :
forall x y z : set, x :e (UPair y z) -> x = y \/ x = z.
(** Given a set X, (Union X) is the set {x | there is some Y such that x :e Y and Y :e X}. That is, Union gives the union of a set of sets. **)
Parameter Union : set -> set.
Axiom UnionI :
forall X x Y : set, x :e Y -> Y :e X -> x :e (Union X).
Axiom UnionE :
forall X x : set, x :e (Union X) -> exists Y : set, x :e Y /\ Y :e X.
(** Given a set X and a function F, (Repl F X) is the set {F x|x :e X}. That is, Repl allows us to form a set by
replacing the elements x in a set X with corresponding elements F x. **)
Parameter Repl : (set -> set) -> set -> set.
Axiom ReplI :
forall X : set, forall F : set -> set, forall x : set, x :e X -> (F x) :e (Repl F X).
Axiom ReplE :
forall X : set, forall F : set -> set, forall y : set, y :e (Repl F X) -> exists x : set, x :e X /\ y = F x.
(** (Power X) is the set of all subsets of X. **)
Parameter Power : set -> set.
Axiom PowerI : forall X Y : set, Y c= X -> Y :e (Power X).
Axiom PowerE : forall X Y : set, Y :e (Power X) -> Y c= X.
(** Every set is a member of a Grothendieck universe. A Grothendieck universe is a transitive set closed under the previous
set theoretic operators. The assumption that Grothendieck universes exist is stronger than an axiom of infinity since (GU Empty) is infinite.
We also assume (GU X) is the least Grothendieck universe containing X. **)
Parameter GU : set -> set.
Axiom GUIn : forall N : set, N :e (GU N).
Axiom GUTrans : forall N X Y : set, X :e (GU N) -> Y :e X -> Y :e (GU N).
Axiom GUUPair : forall N X Y : set, X :e (GU N) -> Y :e (GU N) -> (UPair X Y) :e (GU N).
Axiom GUPower : forall N X : set, X :e (GU N) -> (Power X) :e (GU N).
Axiom GUUnion : forall N X : set, X :e (GU N) -> (Union X) :e (GU N).
Axiom GURepl : forall N X : set, forall F : set -> set, X :e (GU N) -> (forall x : set, x :e X -> (F x) :e (GU N)) -> (Repl F X) :e (GU N).
Axiom GUMin : forall N U : set, N :e U
-> (forall X Y : set, X :e U -> Y :e X -> Y :e U)
-> (forall X Y : set, X :e U -> Y :e U -> (UPair X Y) :e U)
-> (forall X : set, X :e U -> (Power X) :e U)
-> (forall X : set, X :e U -> (Union X) :e U)
-> (forall X : set, forall F:set -> set, X :e U -> (forall x:set, x :e X -> (F x) :e U) -> (Repl F X) :e U)
-> (GU N) c= U.
End TG.
|
{"author": "verimath", "repo": "set", "sha": "aa4aea3a9f6c3b2ad9d8a7834d5e447c408754f4", "save_path": "github-repos/coq/verimath-set", "path": "github-repos/coq/verimath-set/set-aa4aea3a9f6c3b2ad9d8a7834d5e447c408754f4/src/TG0.v"}
|
#!/usr/bin/env python3
# Requires python 3.5+
import importlib.util
import logging
import os
import numpy as np
import pylab as plt
import torch
from omegaconf import OmegaConf
import swyft
DEVICE = "cuda:0"
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
def main():
# Pretty hacky way to import local model
# https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
cwd = os.getcwd()
spec = importlib.util.spec_from_file_location("defs", cwd + "/definitions.py")
defs = importlib.util.module_from_spec(spec)
spec.loader.exec_module(defs)
# Load configuration file
conf = OmegaConf.load("config.yaml")
# Set up cache
params = defs.par0.keys()
obs_shapes = {k: v.shape for k, v in defs.obs0.items()}
cache = swyft.DirectoryCache(params, obs_shapes=obs_shapes, path=conf.cache)
# Set up nested ratio estimator
s = swyft.NestedRatios(
defs.model,
defs.prior,
noise=defs.noise,
obs=defs.obs0,
device=DEVICE,
Ninit=conf.Ninit,
cache=cache,
)
# Fit!
s.run(
max_rounds=conf.max_rounds,
train_args=conf.train_args,
head=defs.CustomHead,
tail_args=conf.tail_args,
head_args=conf.head_args,
)
# Post processing and evaluation
samples = s.marginals(defs.obs0, 3000)
# Save marginals
swyft.plot.plot1d(
samples,
list(defs.prior.params()),
figsize=(20, 4),
ncol=5,
grid_interpolate=True,
truth=defs.par0,
)
plt.savefig("marginals.pdf")
# Save diagnostics
diagnostics = swyft.utils.sample_diagnostics(samples)
state_dict = {"NestedRatios": s.state_dict(), "diagnostics": diagnostics}
torch.save(state_dict, "sample_diagnostics.pt")
if __name__ == "__main__":
main()
|
{"hexsha": "39426c7795414ea9dfceef9b8df2deb868b73307", "size": 1871, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/run_swyft.py", "max_stars_repo_name": "adam-coogan/swyft", "max_stars_repo_head_hexsha": "c54bdd9f77ddf02fda857e26640df012cbe545fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/run_swyft.py", "max_issues_repo_name": "adam-coogan/swyft", "max_issues_repo_head_hexsha": "c54bdd9f77ddf02fda857e26640df012cbe545fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/run_swyft.py", "max_forks_repo_name": "adam-coogan/swyft", "max_forks_repo_head_hexsha": "c54bdd9f77ddf02fda857e26640df012cbe545fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2987012987, "max_line_length": 90, "alphanum_fraction": 0.6552645644, "include": true, "reason": "import numpy", "num_tokens": 480}
|
"""
Git(;
ignore=String[],
name=nothing,
email=nothing,
branch=nothing,
ssh=false,
jl=true,
manifest=false,
gpgsign=false,
)
Creates a Git repository and a `.gitignore` file.
## Keyword Arguments
- `ignore::Vector{<:AbstractString}`: Patterns to add to the `.gitignore`.
See also: [`gitignore`](@ref).
- `name::AbstractString`: Your real name, if you have not set `user.name` with Git.
- `email::AbstractString`: Your email address, if you have not set `user.email` with Git.
- `branch::AbstractString`: The desired name of the repository's default branch.
- `ssh::Bool`: Whether or not to use SSH for the remote.
If left unset, HTTPS is used.
- `jl::Bool`: Whether or not to add a `.jl` suffix to the remote URL.
- `manifest::Bool`: Whether or not to commit `Manifest.toml`.
- `gpgsign::Bool`: Whether or not to sign commits with your GPG key.
This option requires that the Git CLI is installed,
and for you to have a GPG key associated with your committer identity.
"""
@plugin struct Git <: Plugin
ignore::Vector{String} = String[]
name::Union{String, Nothing} = nothing
email::Union{String, Nothing} = nothing
branch::Union{String, Nothing} = nothing
ssh::Bool = false
jl::Bool = true
manifest::Bool = false
gpgsign::Bool = false
end
# Try to make sure that no files are created after we commit.
priority(::Git, ::typeof(posthook)) = 5
gitignore(p::Git) = p.ignore
function validate(p::Git, t::Template)
if p.gpgsign && !git_is_installed()
throw(ArgumentError("Git: gpgsign is set but the Git CLI is not installed"))
end
foreach((:name, :email)) do k
user_k = "user.$k"
if getproperty(p, k) === nothing && isempty(LibGit2.getconfig(user_k, ""))
throw(ArgumentError("Git: Global Git config is missing required value '$user_k'"))
end
end
end
# Set up the Git repository.
function prehook(p::Git, t::Template, pkg_dir::AbstractString)
LibGit2.with(LibGit2.init(pkg_dir)) do repo
LibGit2.with(GitConfig(repo)) do config
foreach((:name, :email)) do k
v = getproperty(p, k)
v === nothing || LibGit2.set!(config, "user.$k", v)
end
end
commit(p, repo, pkg_dir, "Initial commit")
pkg = basename(pkg_dir)
suffix = p.jl ? ".jl" : ""
url = if p.ssh
"git@$(t.host):$(t.user)/$pkg$suffix.git"
else
"https://$(t.host)/$(t.user)/$pkg$suffix"
end
default = LibGit2.branch(repo)
branch = something(p.branch, default)
if branch != default
LibGit2.branch!(repo, branch)
delete_branch(GitReference(repo, "refs/heads/$default"))
end
close(GitRemote(repo, "origin", url))
end
end
# Create the .gitignore.
function hook(p::Git, t::Template, pkg_dir::AbstractString)
ignore = mapreduce(gitignore, vcat, t.plugins)
# Only ignore manifests at the repo root.
p.manifest || "Manifest.toml" in ignore || push!(ignore, "/Manifest.toml")
unique!(sort!(ignore))
gen_file(joinpath(pkg_dir, ".gitignore"), join(ignore, "\n"))
end
# Commit the files.
function posthook(p::Git, ::Template, pkg_dir::AbstractString)
# Special case for issue 211.
if Sys.iswindows()
files = filter(f -> startswith(f, "_git2_"), readdir(pkg_dir))
foreach(f -> rm(joinpath(pkg_dir, f)), files)
end
# Ensure that the manifest exists if it's going to be committed.
manifest = joinpath(pkg_dir, "Manifest.toml")
if p.manifest && !isfile(manifest)
touch(manifest)
with_project(Pkg.update, pkg_dir)
end
LibGit2.with(GitRepo(pkg_dir)) do repo
LibGit2.add!(repo, ".")
msg = "Files generated by PkgTemplates"
v = version_of("PkgTemplates")
v === nothing || (msg *= "\n\nPkgTemplates version: $v")
# TODO: Put the template config in the message too?
commit(p, repo, pkg_dir, msg)
end
end
function commit(p::Git, repo::GitRepo, pkg_dir::AbstractString, msg::AbstractString)
if p.gpgsign
run(pipeline(`git -C $pkg_dir commit -S --allow-empty -m $msg`; stdout=devnull))
else
LibGit2.commit(repo, msg)
end
end
needs_username(::Git) = true
function git_is_installed()
return try
run(pipeline(`git --version`; stdout=devnull))
true
catch
false
end
end
if isdefined(Pkg, :dependencies)
function version_of(pkg::AbstractString)
for p in values(Pkg.dependencies())
p.name == pkg && return p.version
end
return nothing
end
else
version_of(pkg::AbstractString) = get(Pkg.installed(), pkg, nothing)
end
|
{"hexsha": "5b235d569ca31b10c24413e8b502802c76bf69a9", "size": 4778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/plugins/git.jl", "max_stars_repo_name": "sethaxen/PkgTemplates.jl", "max_stars_repo_head_hexsha": "9eea9eb8404da6e337fd13536999db2a6a7fbc80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plugins/git.jl", "max_issues_repo_name": "sethaxen/PkgTemplates.jl", "max_issues_repo_head_hexsha": "9eea9eb8404da6e337fd13536999db2a6a7fbc80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/git.jl", "max_forks_repo_name": "sethaxen/PkgTemplates.jl", "max_forks_repo_head_hexsha": "9eea9eb8404da6e337fd13536999db2a6a7fbc80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5034013605, "max_line_length": 94, "alphanum_fraction": 0.6272498954, "num_tokens": 1263}
|
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
b : α
hb : b ∈ P.parts
⊢ b ≠ ⊥
[PROOFSTEP]
intro h
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
b : α
hb : b ∈ P.parts
h : b = ⊥
⊢ False
[PROOFSTEP]
refine' P.not_bot_mem (_)
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
b : α
hb : b ∈ P.parts
h : b = ⊥
⊢ ⊥ ∈ P.parts
[PROOFSTEP]
rw [h] at hb
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
b : α
hb : ⊥ ∈ P.parts
h : b = ⊥
⊢ ⊥ ∈ P.parts
[PROOFSTEP]
exact hb
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
⊢ P.parts = ∅ ↔ a = ⊥
[PROOFSTEP]
simp_rw [← P.supParts]
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
⊢ P.parts = ∅ ↔ sup P.parts id = ⊥
[PROOFSTEP]
refine' ⟨fun h ↦ _, fun h ↦ eq_empty_iff_forall_not_mem.2 fun b hb ↦ P.not_bot_mem _⟩
[GOAL]
case refine'_1
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
h : P.parts = ∅
⊢ sup P.parts id = ⊥
[PROOFSTEP]
rw [h]
[GOAL]
case refine'_1
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
h : P.parts = ∅
⊢ sup ∅ id = ⊥
[PROOFSTEP]
exact Finset.sup_empty
[GOAL]
case refine'_2
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
h : sup P.parts id = ⊥
b : α
hb : b ∈ P.parts
⊢ ⊥ ∈ P.parts
[PROOFSTEP]
rwa [← le_bot_iff.1 ((le_sup hb).trans h.le)]
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P : Finpartition a
⊢ Finset.Nonempty P.parts ↔ a ≠ ⊥
[PROOFSTEP]
rw [nonempty_iff_ne_empty, not_iff_not, parts_eq_empty_iff]
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : Inhabited (Finpartition ⊥) := inferInstance
P : Finpartition ⊥
⊢ P = default
[PROOFSTEP]
ext a
[GOAL]
case parts.a
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a✝ : α
P✝ : Finpartition a✝
src✝ : Inhabited (Finpartition ⊥) := inferInstance
P : Finpartition ⊥
a : α
⊢ a ∈ P.parts ↔ a ∈ default.parts
[PROOFSTEP]
exact iff_of_false (fun h ↦ P.ne_bot h <| le_bot_iff.1 <| P.le h) (not_mem_empty a)
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
ha : IsAtom a
P : Finpartition a
⊢ P = default
[PROOFSTEP]
have h : ∀ b ∈ P.parts, b = a := fun _ hb ↦ (ha.le_iff.mp <| P.le hb).resolve_left (P.ne_bot hb)
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
ha : IsAtom a
P : Finpartition a
h : ∀ (b : α), b ∈ P.parts → b = a
⊢ P = default
[PROOFSTEP]
ext b
[GOAL]
case parts.a
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
ha : IsAtom a
P : Finpartition a
h : ∀ (b : α), b ∈ P.parts → b = a
b : α
⊢ b ∈ P.parts ↔ b ∈ default.parts
[PROOFSTEP]
refine' Iff.trans ⟨h b, _⟩ mem_singleton.symm
[GOAL]
case parts.a
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
ha : IsAtom a
P : Finpartition a
h : ∀ (b : α), b ∈ P.parts → b = a
b : α
⊢ b = a → b ∈ P.parts
[PROOFSTEP]
rintro rfl
[GOAL]
case parts.a
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
b : α
P✝ : Finpartition b
ha : IsAtom b
P : Finpartition b
h : ∀ (b_1 : α), b_1 ∈ P.parts → b_1 = b
⊢ b ∈ P.parts
[PROOFSTEP]
obtain ⟨c, hc⟩ := P.parts_nonempty ha.1
[GOAL]
case parts.a.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
b : α
P✝ : Finpartition b
ha : IsAtom b
P : Finpartition b
h : ∀ (b_1 : α), b_1 ∈ P.parts → b_1 = b
c : α
hc : c ∈ P.parts
⊢ b ∈ P.parts
[PROOFSTEP]
simp_rw [← h c hc]
[GOAL]
case parts.a.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
b : α
P✝ : Finpartition b
ha : IsAtom b
P : Finpartition b
h : ∀ (b_1 : α), b_1 ∈ P.parts → b_1 = b
c : α
hc : c ∈ P.parts
⊢ c ∈ P.parts
[PROOFSTEP]
exact hc
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q R : Finpartition a
hPQ : P ≤ Q
hQR : Q ≤ R
b : α
hb : b ∈ P.parts
⊢ ∃ c, c ∈ R.parts ∧ b ≤ c
[PROOFSTEP]
obtain ⟨c, hc, hbc⟩ := hPQ hb
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q R : Finpartition a
hPQ : P ≤ Q
hQR : Q ≤ R
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ Q.parts
hbc : b ≤ c
⊢ ∃ c, c ∈ R.parts ∧ b ≤ c
[PROOFSTEP]
obtain ⟨d, hd, hcd⟩ := hQR hc
[GOAL]
case intro.intro.intro.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q R : Finpartition a
hPQ : P ≤ Q
hQR : Q ≤ R
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ Q.parts
hbc : b ≤ c
d : α
hd : d ∈ R.parts
hcd : c ≤ d
⊢ ∃ c, c ∈ R.parts ∧ b ≤ c
[PROOFSTEP]
exact ⟨d, hd, hbc.trans hcd⟩
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
⊢ P = Q
[PROOFSTEP]
ext b
[GOAL]
case parts.a
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
⊢ b ∈ P.parts ↔ b ∈ Q.parts
[PROOFSTEP]
refine' ⟨fun hb ↦ _, fun hb ↦ _⟩
[GOAL]
case parts.a.refine'_1
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
hb : b ∈ P.parts
⊢ b ∈ Q.parts
[PROOFSTEP]
obtain ⟨c, hc, hbc⟩ := hPQ hb
[GOAL]
case parts.a.refine'_1.intro.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ Q.parts
hbc : b ≤ c
⊢ b ∈ Q.parts
[PROOFSTEP]
obtain ⟨d, hd, hcd⟩ := hQP hc
[GOAL]
case parts.a.refine'_1.intro.intro.intro.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ Q.parts
hbc : b ≤ c
d : α
hd : d ∈ P.parts
hcd : c ≤ d
⊢ b ∈ Q.parts
[PROOFSTEP]
rwa [hbc.antisymm]
[GOAL]
case parts.a.refine'_1.intro.intro.intro.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ Q.parts
hbc : b ≤ c
d : α
hd : d ∈ P.parts
hcd : c ≤ d
⊢ c ≤ b
[PROOFSTEP]
rwa [P.disjoint.eq_of_le hb hd (P.ne_bot hb) (hbc.trans hcd)]
[GOAL]
case parts.a.refine'_2
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
hb : b ∈ Q.parts
⊢ b ∈ P.parts
[PROOFSTEP]
obtain ⟨c, hc, hbc⟩ := hQP hb
[GOAL]
case parts.a.refine'_2.intro.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
hb : b ∈ Q.parts
c : α
hc : c ∈ P.parts
hbc : b ≤ c
⊢ b ∈ P.parts
[PROOFSTEP]
obtain ⟨d, hd, hcd⟩ := hPQ hc
[GOAL]
case parts.a.refine'_2.intro.intro.intro.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
hb : b ∈ Q.parts
c : α
hc : c ∈ P.parts
hbc : b ≤ c
d : α
hd : d ∈ Q.parts
hcd : c ≤ d
⊢ b ∈ P.parts
[PROOFSTEP]
rwa [hbc.antisymm]
[GOAL]
case parts.a.refine'_2.intro.intro.intro.intro
α : Type u_1
inst✝¹ : Lattice α
inst✝ : OrderBot α
a : α
P✝ : Finpartition a
src✝ : LE (Finpartition a) := inferInstance
P Q : Finpartition a
hPQ : P ≤ Q
hQP : Q ≤ P
b : α
hb : b ∈ Q.parts
c : α
hc : c ∈ P.parts
hbc : b ≤ c
d : α
hd : d ∈ Q.parts
hcd : c ≤ d
⊢ c ≤ b
[PROOFSTEP]
rwa [Q.disjoint.eq_of_le hb hd (Q.ne_bot hb) (hbc.trans hcd)]
[GOAL]
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a : α
P✝ : Finpartition a
inst✝ : Decidable (a = ⊥)
P : Finpartition a
⊢ P ≤ ⊤
[PROOFSTEP]
split_ifs with h
[GOAL]
case pos
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a : α
P✝ : Finpartition a
inst✝ : Decidable (a = ⊥)
P : Finpartition a
h : a = ⊥
⊢ P ≤ ⊤
[PROOFSTEP]
intro x hx
[GOAL]
case pos
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a : α
P✝ : Finpartition a
inst✝ : Decidable (a = ⊥)
P : Finpartition a
h : a = ⊥
x : α
hx : x ∈ P.parts
⊢ ∃ c, c ∈ ⊤.parts ∧ x ≤ c
[PROOFSTEP]
simpa [h, P.ne_bot hx] using P.le hx
[GOAL]
case neg
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a : α
P✝ : Finpartition a
inst✝ : Decidable (a = ⊥)
P : Finpartition a
h : ¬a = ⊥
⊢ P ≤ ⊤
[PROOFSTEP]
exact fun b hb ↦ ⟨a, mem_singleton_self _, P.le hb⟩
[GOAL]
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a✝ : α
P : Finpartition a✝
a : α
inst✝ : Decidable (a = ⊥)
⊢ ⊤.parts ⊆ {a}
[PROOFSTEP]
intro b hb
[GOAL]
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a✝ : α
P : Finpartition a✝
a : α
inst✝ : Decidable (a = ⊥)
b : α
hb : b ∈ ⊤.parts
⊢ b ∈ {a}
[PROOFSTEP]
have hb : b ∈ Finpartition.parts (dite _ _ _) := hb
[GOAL]
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a✝ : α
P : Finpartition a✝
a : α
inst✝ : Decidable (a = ⊥)
b : α
hb✝ : b ∈ ⊤.parts
hb : b ∈ (if ha : a = ⊥ then copy (Finpartition.empty α) (_ : ⊥ = a) else indiscrete ha).parts
⊢ b ∈ {a}
[PROOFSTEP]
split_ifs at hb
[GOAL]
case pos
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a✝ : α
P : Finpartition a✝
a : α
inst✝ : Decidable (a = ⊥)
b : α
hb✝ : b ∈ ⊤.parts
h✝ : a = ⊥
hb : b ∈ (copy (Finpartition.empty α) (_ : ⊥ = a)).parts
⊢ b ∈ {a}
[PROOFSTEP]
simp only [copy_parts, empty_parts, not_mem_empty] at hb
[GOAL]
case neg
α : Type u_1
inst✝² : Lattice α
inst✝¹ : OrderBot α
a✝ : α
P : Finpartition a✝
a : α
inst✝ : Decidable (a = ⊥)
b : α
hb✝ : b ∈ ⊤.parts
h✝ : ¬a = ⊥
hb : b ∈ (indiscrete h✝).parts
⊢ b ∈ {a}
[PROOFSTEP]
exact hb
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
⊢ SupIndep (image (fun bc => bc.fst ⊓ bc.snd) (P.parts ×ˢ Q.parts)) id
[PROOFSTEP]
rw [supIndep_iff_disjoint_erase]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
⊢ ∀ (i : α),
i ∈ image (fun bc => bc.fst ⊓ bc.snd) (P.parts ×ˢ Q.parts) →
Disjoint (id i) (sup (erase (image (fun bc => bc.fst ⊓ bc.snd) (P.parts ×ˢ Q.parts)) i) id)
[PROOFSTEP]
simp only [mem_image, and_imp, exists_prop, forall_exists_index, id.def, Prod.exists, mem_product,
Finset.disjoint_sup_right, mem_erase, Ne.def]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
⊢ ∀ (i x x_1 : α),
x ∈ P.parts →
x_1 ∈ Q.parts →
x ⊓ x_1 = i →
∀ ⦃i_1 : α⦄, ¬i_1 = i → ∀ (x x_2 : α), x ∈ P.parts → x_2 ∈ Q.parts → x ⊓ x_2 = i_1 → Disjoint i i_1
[PROOFSTEP]
rintro _ x₁ y₁ hx₁ hy₁ rfl _ h x₂ y₂ hx₂ hy₂ rfl
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
x₁ y₁ : α
hx₁ : x₁ ∈ P.parts
hy₁ : y₁ ∈ Q.parts
x₂ y₂ : α
hx₂ : x₂ ∈ P.parts
hy₂ : y₂ ∈ Q.parts
h : ¬x₂ ⊓ y₂ = x₁ ⊓ y₁
⊢ Disjoint (x₁ ⊓ y₁) (x₂ ⊓ y₂)
[PROOFSTEP]
rcases eq_or_ne x₁ x₂ with (rfl | xdiff)
[GOAL]
case inl
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
x₁ y₁ : α
hx₁ : x₁ ∈ P.parts
hy₁ : y₁ ∈ Q.parts
y₂ : α
hy₂ : y₂ ∈ Q.parts
hx₂ : x₁ ∈ P.parts
h : ¬x₁ ⊓ y₂ = x₁ ⊓ y₁
⊢ Disjoint (x₁ ⊓ y₁) (x₁ ⊓ y₂)
[PROOFSTEP]
refine' Disjoint.mono inf_le_right inf_le_right (Q.disjoint hy₁ hy₂ _)
[GOAL]
case inl
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
x₁ y₁ : α
hx₁ : x₁ ∈ P.parts
hy₁ : y₁ ∈ Q.parts
y₂ : α
hy₂ : y₂ ∈ Q.parts
hx₂ : x₁ ∈ P.parts
h : ¬x₁ ⊓ y₂ = x₁ ⊓ y₁
⊢ y₁ ≠ y₂
[PROOFSTEP]
intro t
[GOAL]
case inl
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
x₁ y₁ : α
hx₁ : x₁ ∈ P.parts
hy₁ : y₁ ∈ Q.parts
y₂ : α
hy₂ : y₂ ∈ Q.parts
hx₂ : x₁ ∈ P.parts
h : ¬x₁ ⊓ y₂ = x₁ ⊓ y₁
t : y₁ = y₂
⊢ False
[PROOFSTEP]
simp [t] at h
[GOAL]
case inr
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
x₁ y₁ : α
hx₁ : x₁ ∈ P.parts
hy₁ : y₁ ∈ Q.parts
x₂ y₂ : α
hx₂ : x₂ ∈ P.parts
hy₂ : y₂ ∈ Q.parts
h : ¬x₂ ⊓ y₂ = x₁ ⊓ y₁
xdiff : x₁ ≠ x₂
⊢ Disjoint (x₁ ⊓ y₁) (x₂ ⊓ y₂)
[PROOFSTEP]
exact Disjoint.mono inf_le_left inf_le_left (P.disjoint hx₁ hx₂ xdiff)
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
⊢ sup (image (fun bc => bc.fst ⊓ bc.snd) (P.parts ×ˢ Q.parts)) id = a
[PROOFSTEP]
rw [sup_image, comp.left_id, sup_product_left]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
⊢ (sup P.parts fun i => sup Q.parts fun i' => (i, i').fst ⊓ (i, i').snd) = a
[PROOFSTEP]
trans P.parts.sup id ⊓ Q.parts.sup id
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
⊢ (sup P.parts fun i => sup Q.parts fun i' => (i, i').fst ⊓ (i, i').snd) = sup P.parts id ⊓ sup Q.parts id
[PROOFSTEP]
simp_rw [Finset.sup_inf_distrib_right, Finset.sup_inf_distrib_left]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
⊢ (sup P.parts fun i => sup Q.parts fun i' => i ⊓ i') = sup P.parts fun i => sup Q.parts fun i_1 => id i ⊓ id i_1
[PROOFSTEP]
rfl
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P Q : Finpartition a
⊢ sup P.parts id ⊓ sup Q.parts id = a
[PROOFSTEP]
rw [P.supParts, Q.supParts, inf_idem]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q : Finpartition a
b : α
hb : b ∈ (P ⊓ Q).parts
⊢ ∃ c, c ∈ P.parts ∧ b ≤ c
[PROOFSTEP]
obtain ⟨c, hc, rfl⟩ := mem_image.1 (mem_of_mem_erase hb)
[GOAL]
case intro.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c✝ : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q : Finpartition a
c : α × α
hc : c ∈ P.parts ×ˢ Q.parts
hb : c.fst ⊓ c.snd ∈ (P ⊓ Q).parts
⊢ ∃ c_1, c_1 ∈ P.parts ∧ c.fst ⊓ c.snd ≤ c_1
[PROOFSTEP]
rw [mem_product] at hc
[GOAL]
case intro.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c✝ : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q : Finpartition a
c : α × α
hc : c.fst ∈ P.parts ∧ c.snd ∈ Q.parts
hb : c.fst ⊓ c.snd ∈ (P ⊓ Q).parts
⊢ ∃ c_1, c_1 ∈ P.parts ∧ c.fst ⊓ c.snd ≤ c_1
[PROOFSTEP]
exact ⟨c.1, hc.1, inf_le_left⟩
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q : Finpartition a
b : α
hb : b ∈ (P ⊓ Q).parts
⊢ ∃ c, c ∈ Q.parts ∧ b ≤ c
[PROOFSTEP]
obtain ⟨c, hc, rfl⟩ := mem_image.1 (mem_of_mem_erase hb)
[GOAL]
case intro.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c✝ : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q : Finpartition a
c : α × α
hc : c ∈ P.parts ×ˢ Q.parts
hb : c.fst ⊓ c.snd ∈ (P ⊓ Q).parts
⊢ ∃ c_1, c_1 ∈ Q.parts ∧ c.fst ⊓ c.snd ≤ c_1
[PROOFSTEP]
rw [mem_product] at hc
[GOAL]
case intro.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c✝ : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q : Finpartition a
c : α × α
hc : c.fst ∈ P.parts ∧ c.snd ∈ Q.parts
hb : c.fst ⊓ c.snd ∈ (P ⊓ Q).parts
⊢ ∃ c_1, c_1 ∈ Q.parts ∧ c.fst ⊓ c.snd ≤ c_1
[PROOFSTEP]
exact ⟨c.2, hc.2, inf_le_right⟩
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q R : Finpartition a
hPQ : P ≤ Q
hPR : P ≤ R
b : α
hb : b ∈ P.parts
⊢ ∃ c, c ∈ (Q ⊓ R).parts ∧ b ≤ c
[PROOFSTEP]
obtain ⟨c, hc, hbc⟩ := hPQ hb
[GOAL]
case intro.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c✝ : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q R : Finpartition a
hPQ : P ≤ Q
hPR : P ≤ R
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ Q.parts
hbc : b ≤ c
⊢ ∃ c, c ∈ (Q ⊓ R).parts ∧ b ≤ c
[PROOFSTEP]
obtain ⟨d, hd, hbd⟩ := hPR hb
[GOAL]
case intro.intro.intro.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c✝ : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q R : Finpartition a
hPQ : P ≤ Q
hPR : P ≤ R
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ Q.parts
hbc : b ≤ c
d : α
hd : d ∈ R.parts
hbd : b ≤ d
⊢ ∃ c, c ∈ (Q ⊓ R).parts ∧ b ≤ c
[PROOFSTEP]
have h := _root_.le_inf hbc hbd
[GOAL]
case intro.intro.intro.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c✝ : α
src✝¹ : PartialOrder (Finpartition a) := inferInstance
src✝ : Inf (Finpartition a) := inferInstance
P Q R : Finpartition a
hPQ : P ≤ Q
hPR : P ≤ R
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ Q.parts
hbc : b ≤ c
d : α
hd : d ∈ R.parts
hbd : b ≤ d
h : b ≤ c ⊓ d
⊢ ∃ c, c ∈ (Q ⊓ R).parts ∧ b ≤ c
[PROOFSTEP]
refine'
⟨c ⊓ d,
mem_erase_of_ne_of_mem (ne_bot_of_le_ne_bot (P.ne_bot hb) h) (mem_image.2 ⟨(c, d), mem_product.2 ⟨hc, hd⟩, rfl⟩), h⟩
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
⊢ ∃ c, c ∈ P.parts ∧ c ≤ b
[PROOFSTEP]
by_contra H
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
H : ¬∃ c, c ∈ P.parts ∧ c ≤ b
⊢ False
[PROOFSTEP]
refine' Q.ne_bot hb (disjoint_self.1 <| Disjoint.mono_right (Q.le hb) _)
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
H : ¬∃ c, c ∈ P.parts ∧ c ≤ b
⊢ Disjoint b a
[PROOFSTEP]
rw [← P.supParts, Finset.disjoint_sup_right]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
H : ¬∃ c, c ∈ P.parts ∧ c ≤ b
⊢ ∀ ⦃i : α⦄, i ∈ P.parts → Disjoint b (id i)
[PROOFSTEP]
rintro c hc
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
H : ¬∃ c, c ∈ P.parts ∧ c ≤ b
c : α
hc : c ∈ P.parts
⊢ Disjoint b (id c)
[PROOFSTEP]
obtain ⟨d, hd, hcd⟩ := h hc
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
H : ¬∃ c, c ∈ P.parts ∧ c ≤ b
c : α
hc : c ∈ P.parts
d : α
hd : d ∈ Q.parts
hcd : c ≤ d
⊢ Disjoint b (id c)
[PROOFSTEP]
refine' (Q.disjoint hb hd _).mono_right hcd
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
H : ¬∃ c, c ∈ P.parts ∧ c ≤ b
c : α
hc : c ∈ P.parts
d : α
hd : d ∈ Q.parts
hcd : c ≤ d
⊢ b ≠ d
[PROOFSTEP]
rintro rfl
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
H : ¬∃ c, c ∈ P.parts ∧ c ≤ b
c : α
hc : c ∈ P.parts
hd : b ∈ Q.parts
hcd : c ≤ b
⊢ False
[PROOFSTEP]
simp only [not_exists, not_and] at H
[GOAL]
case intro.intro
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b : α
P Q : Finpartition a
h : P ≤ Q
hb : b ∈ Q.parts
c : α
hc : c ∈ P.parts
hd : b ∈ Q.parts
hcd : c ≤ b
H : ∀ (x : α), x ∈ P.parts → ¬x ≤ b
⊢ False
[PROOFSTEP]
exact H _ hc hcd
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a : α
P Q : Finpartition a
h : P ≤ Q
⊢ card Q.parts ≤ card P.parts
[PROOFSTEP]
classical
have : ∀ b ∈ Q.parts, ∃ c ∈ P.parts, c ≤ b := fun b ↦ exists_le_of_le h
choose f hP hf using this
rw [← card_attach]
refine' card_le_card_of_inj_on (fun b ↦ f _ b.2) (fun b _ ↦ hP _ b.2) fun b _ c _ h ↦ _
exact
Subtype.coe_injective
(Q.disjoint.elim b.2 c.2 fun H ↦
P.ne_bot (hP _ b.2) <| disjoint_self.1 <| H.mono (hf _ b.2) <| h.le.trans <| hf _ c.2)
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a : α
P Q : Finpartition a
h : P ≤ Q
⊢ card Q.parts ≤ card P.parts
[PROOFSTEP]
have : ∀ b ∈ Q.parts, ∃ c ∈ P.parts, c ≤ b := fun b ↦ exists_le_of_le h
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a : α
P Q : Finpartition a
h : P ≤ Q
this : ∀ (b : α), b ∈ Q.parts → ∃ c, c ∈ P.parts ∧ c ≤ b
⊢ card Q.parts ≤ card P.parts
[PROOFSTEP]
choose f hP hf using this
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a : α
P Q : Finpartition a
h : P ≤ Q
f : (b : α) → b ∈ Q.parts → α
hP : ∀ (b : α) (a_1 : b ∈ Q.parts), f b a_1 ∈ P.parts
hf : ∀ (b : α) (a : b ∈ Q.parts), f b a ≤ b
⊢ card Q.parts ≤ card P.parts
[PROOFSTEP]
rw [← card_attach]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a : α
P Q : Finpartition a
h : P ≤ Q
f : (b : α) → b ∈ Q.parts → α
hP : ∀ (b : α) (a_1 : b ∈ Q.parts), f b a_1 ∈ P.parts
hf : ∀ (b : α) (a : b ∈ Q.parts), f b a ≤ b
⊢ card (attach Q.parts) ≤ card P.parts
[PROOFSTEP]
refine' card_le_card_of_inj_on (fun b ↦ f _ b.2) (fun b _ ↦ hP _ b.2) fun b _ c _ h ↦ _
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a : α
P Q : Finpartition a
h✝ : P ≤ Q
f : (b : α) → b ∈ Q.parts → α
hP : ∀ (b : α) (a_1 : b ∈ Q.parts), f b a_1 ∈ P.parts
hf : ∀ (b : α) (a : b ∈ Q.parts), f b a ≤ b
b : { x // x ∈ Q.parts }
x✝¹ : b ∈ attach Q.parts
c : { x // x ∈ Q.parts }
x✝ : c ∈ attach Q.parts
h : (fun b => f ↑b (_ : ↑b ∈ Q.parts)) b = (fun b => f ↑b (_ : ↑b ∈ Q.parts)) c
⊢ b = c
[PROOFSTEP]
exact
Subtype.coe_injective
(Q.disjoint.elim b.2 c.2 fun H ↦
P.ne_bot (hP _ b.2) <| disjoint_self.1 <| H.mono (hf _ b.2) <| h.le.trans <| hf _ c.2)
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ SupIndep (Finset.biUnion (attach P.parts) fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) id
[PROOFSTEP]
rw [supIndep_iff_pairwiseDisjoint]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ Set.PairwiseDisjoint (↑(Finset.biUnion (attach P.parts) fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts)) id
[PROOFSTEP]
rintro a ha b hb h
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a✝ b✝ c : α
P✝ : Finpartition a✝
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a✝
Q : (i : α) → i ∈ P.parts → Finpartition i
a : α
ha : a ∈ ↑(Finset.biUnion (attach P.parts) fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts)
b : α
hb : b ∈ ↑(Finset.biUnion (attach P.parts) fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts)
h : a ≠ b
⊢ (Disjoint on id) a b
[PROOFSTEP]
rw [Finset.mem_coe, Finset.mem_biUnion] at ha hb
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a✝ b✝ c : α
P✝ : Finpartition a✝
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a✝
Q : (i : α) → i ∈ P.parts → Finpartition i
a : α
ha : ∃ a_1, a_1 ∈ attach P.parts ∧ a ∈ (Q ↑a_1 (_ : ↑a_1 ∈ P.parts)).parts
b : α
hb : ∃ a, a ∈ attach P.parts ∧ b ∈ (Q ↑a (_ : ↑a ∈ P.parts)).parts
h : a ≠ b
⊢ (Disjoint on id) a b
[PROOFSTEP]
obtain ⟨⟨A, hA⟩, -, ha⟩ := ha
[GOAL]
case intro.mk.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a✝ b✝ c : α
P✝ : Finpartition a✝
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a✝
Q : (i : α) → i ∈ P.parts → Finpartition i
a b : α
hb : ∃ a, a ∈ attach P.parts ∧ b ∈ (Q ↑a (_ : ↑a ∈ P.parts)).parts
h : a ≠ b
A : α
hA : A ∈ P.parts
ha : a ∈ (Q ↑{ val := A, property := hA } (_ : ↑{ val := A, property := hA } ∈ P.parts)).parts
⊢ (Disjoint on id) a b
[PROOFSTEP]
obtain ⟨⟨B, hB⟩, -, hb⟩ := hb
[GOAL]
case intro.mk.intro.intro.mk.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a✝ b✝ c : α
P✝ : Finpartition a✝
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a✝
Q : (i : α) → i ∈ P.parts → Finpartition i
a b : α
h : a ≠ b
A : α
hA : A ∈ P.parts
ha : a ∈ (Q ↑{ val := A, property := hA } (_ : ↑{ val := A, property := hA } ∈ P.parts)).parts
B : α
hB : B ∈ P.parts
hb : b ∈ (Q ↑{ val := B, property := hB } (_ : ↑{ val := B, property := hB } ∈ P.parts)).parts
⊢ (Disjoint on id) a b
[PROOFSTEP]
obtain rfl | hAB := eq_or_ne A B
[GOAL]
case intro.mk.intro.intro.mk.intro.inl
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a✝ b✝ c : α
P✝ : Finpartition a✝
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a✝
Q : (i : α) → i ∈ P.parts → Finpartition i
a b : α
h : a ≠ b
A : α
hA : A ∈ P.parts
ha : a ∈ (Q ↑{ val := A, property := hA } (_ : ↑{ val := A, property := hA } ∈ P.parts)).parts
hB : A ∈ P.parts
hb : b ∈ (Q ↑{ val := A, property := hB } (_ : ↑{ val := A, property := hB } ∈ P.parts)).parts
⊢ (Disjoint on id) a b
[PROOFSTEP]
exact (Q A hA).disjoint ha hb h
[GOAL]
case intro.mk.intro.intro.mk.intro.inr
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a✝ b✝ c : α
P✝ : Finpartition a✝
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a✝
Q : (i : α) → i ∈ P.parts → Finpartition i
a b : α
h : a ≠ b
A : α
hA : A ∈ P.parts
ha : a ∈ (Q ↑{ val := A, property := hA } (_ : ↑{ val := A, property := hA } ∈ P.parts)).parts
B : α
hB : B ∈ P.parts
hb : b ∈ (Q ↑{ val := B, property := hB } (_ : ↑{ val := B, property := hB } ∈ P.parts)).parts
hAB : A ≠ B
⊢ (Disjoint on id) a b
[PROOFSTEP]
exact (P.disjoint hA hB hAB).mono ((Q A hA).le ha) ((Q B hB).le hb)
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ sup (Finset.biUnion (attach P.parts) fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) id = a
[PROOFSTEP]
simp_rw [sup_biUnion]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ (sup (attach P.parts) fun x => sup (Q ↑x (_ : ↑x ∈ P.parts)).parts id) = a
[PROOFSTEP]
trans (sup P.parts id)
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ (sup (attach P.parts) fun x => sup (Q ↑x (_ : ↑x ∈ P.parts)).parts id) = sup P.parts id
[PROOFSTEP]
rw [eq_comm, ← Finset.sup_attach]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ (sup (attach P.parts) fun x => id ↑x) = sup (attach P.parts) fun x => sup (Q ↑x (_ : ↑x ∈ P.parts)).parts id
[PROOFSTEP]
exact sup_congr rfl fun b _hb ↦ (Q b.1 b.2).supParts.symm
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ sup P.parts id = a
[PROOFSTEP]
exact P.supParts
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
h : ⊥ ∈ Finset.biUnion (attach P.parts) fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts
⊢ False
[PROOFSTEP]
rw [Finset.mem_biUnion] at h
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
h : ∃ a_1, a_1 ∈ attach P.parts ∧ ⊥ ∈ (Q ↑a_1 (_ : ↑a_1 ∈ P.parts)).parts
⊢ False
[PROOFSTEP]
obtain ⟨⟨A, hA⟩, -, h⟩ := h
[GOAL]
case intro.mk.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P✝ : Finpartition a
Q✝ : (i : α) → i ∈ P✝.parts → Finpartition i
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
A : α
hA : A ∈ P.parts
h : ⊥ ∈ (Q ↑{ val := A, property := hA } (_ : ↑{ val := A, property := hA } ∈ P.parts)).parts
⊢ False
[PROOFSTEP]
exact (Q A hA).not_bot_mem h
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ b ∈ (bind P Q).parts ↔ ∃ A hA, b ∈ (Q A hA).parts
[PROOFSTEP]
rw [bind, mem_biUnion]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ (∃ a_1, a_1 ∈ attach P.parts ∧ b ∈ (Q ↑a_1 (_ : ↑a_1 ∈ P.parts)).parts) ↔ ∃ A hA, b ∈ (Q A hA).parts
[PROOFSTEP]
constructor
[GOAL]
case mp
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ (∃ a_1, a_1 ∈ attach P.parts ∧ b ∈ (Q ↑a_1 (_ : ↑a_1 ∈ P.parts)).parts) → ∃ A hA, b ∈ (Q A hA).parts
[PROOFSTEP]
rintro ⟨⟨A, hA⟩, -, h⟩
[GOAL]
case mp.intro.mk.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
A : α
hA : A ∈ P.parts
h : b ∈ (Q ↑{ val := A, property := hA } (_ : ↑{ val := A, property := hA } ∈ P.parts)).parts
⊢ ∃ A hA, b ∈ (Q A hA).parts
[PROOFSTEP]
exact ⟨A, hA, h⟩
[GOAL]
case mpr
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ (∃ A hA, b ∈ (Q A hA).parts) → ∃ a_2, a_2 ∈ attach P.parts ∧ b ∈ (Q ↑a_2 (_ : ↑a_2 ∈ P.parts)).parts
[PROOFSTEP]
rintro ⟨A, hA, h⟩
[GOAL]
case mpr.intro.intro
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
Q : (i : α) → i ∈ P.parts → Finpartition i
A : α
hA : A ∈ P.parts
h : b ∈ (Q A hA).parts
⊢ ∃ a_1, a_1 ∈ attach P.parts ∧ b ∈ (Q ↑a_1 (_ : ↑a_1 ∈ P.parts)).parts
[PROOFSTEP]
exact ⟨⟨A, hA⟩, mem_attach _ ⟨A, hA⟩, h⟩
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
Q✝ Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ card (bind P Q).parts = ∑ A in attach P.parts, card (Q ↑A (_ : ↑A ∈ P.parts)).parts
[PROOFSTEP]
apply card_biUnion
[GOAL]
case h
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
Q✝ Q : (i : α) → i ∈ P.parts → Finpartition i
⊢ ∀ (x : { x // x ∈ P.parts }),
x ∈ attach P.parts →
∀ (y : { x // x ∈ P.parts }),
y ∈ attach P.parts →
x ≠ y → Disjoint ((fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) x) ((fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) y)
[PROOFSTEP]
rintro ⟨b, hb⟩ - ⟨c, hc⟩ - hbc
[GOAL]
case h.mk.mk
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c✝ : α
P : Finpartition a
Q✝ Q : (i : α) → i ∈ P.parts → Finpartition i
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ P.parts
hbc : { val := b, property := hb } ≠ { val := c, property := hc }
⊢ Disjoint ((fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) { val := b, property := hb })
((fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) { val := c, property := hc })
[PROOFSTEP]
rw [Finset.disjoint_left]
[GOAL]
case h.mk.mk
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c✝ : α
P : Finpartition a
Q✝ Q : (i : α) → i ∈ P.parts → Finpartition i
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ P.parts
hbc : { val := b, property := hb } ≠ { val := c, property := hc }
⊢ ∀ ⦃a_1 : α⦄,
a_1 ∈ (fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) { val := b, property := hb } →
¬a_1 ∈ (fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) { val := c, property := hc }
[PROOFSTEP]
rintro d hdb hdc
[GOAL]
case h.mk.mk
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c✝ : α
P : Finpartition a
Q✝ Q : (i : α) → i ∈ P.parts → Finpartition i
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ P.parts
hbc : { val := b, property := hb } ≠ { val := c, property := hc }
d : α
hdb : d ∈ (fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) { val := b, property := hb }
hdc : d ∈ (fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) { val := c, property := hc }
⊢ False
[PROOFSTEP]
rw [Ne.def, Subtype.mk_eq_mk] at hbc
[GOAL]
case h.mk.mk
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b✝ c✝ : α
P : Finpartition a
Q✝ Q : (i : α) → i ∈ P.parts → Finpartition i
b : α
hb : b ∈ P.parts
c : α
hc : c ∈ P.parts
hbc : ¬b = c
d : α
hdb : d ∈ (fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) { val := b, property := hb }
hdc : d ∈ (fun i => (Q ↑i (_ : ↑i ∈ P.parts)).parts) { val := c, property := hc }
⊢ False
[PROOFSTEP]
exact
(Q b hb).ne_bot hdb
(eq_bot_iff.2 <| (le_inf ((Q b hb).le hdb) <| (Q c hc).le hdc).trans <| (P.disjoint hb hc hbc).le_bot)
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
hb : b ≠ ⊥
hab : Disjoint a b
hc : a ⊔ b = c
⊢ SupIndep (insert b P.parts) id
[PROOFSTEP]
rw [supIndep_iff_pairwiseDisjoint, coe_insert]
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
hb : b ≠ ⊥
hab : Disjoint a b
hc : a ⊔ b = c
⊢ Set.PairwiseDisjoint (insert b ↑P.parts) id
[PROOFSTEP]
exact P.disjoint.insert fun d hd _ ↦ hab.symm.mono_right <| P.le hd
[GOAL]
α : Type u_1
inst✝² : DistribLattice α
inst✝¹ : OrderBot α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
hb : b ≠ ⊥
hab : Disjoint a b
hc : a ⊔ b = c
⊢ sup (insert b P.parts) id = c
[PROOFSTEP]
rwa [sup_insert, P.supParts, id, _root_.sup_comm]
[GOAL]
α : Type u_1
inst✝¹ : GeneralizedBooleanAlgebra α
inst✝ : DecidableEq α
a b✝ c : α
P : Finpartition a
b : α
⊢ sup (image (fun x => x \ b) P.parts) id = a \ b
[PROOFSTEP]
rw [sup_image, comp.left_id, Finset.sup_sdiff_right, ← id_def, P.supParts]
[GOAL]
α : Type u_1
inst✝¹ : GeneralizedBooleanAlgebra α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
⊢ c ∈ (avoid P b).parts ↔ ∃ d, d ∈ P.parts ∧ ¬d ≤ b ∧ d \ b = c
[PROOFSTEP]
simp only [avoid, ofErase, mem_erase, Ne.def, mem_image, exists_prop, ← exists_and_left, @and_left_comm (c ≠ ⊥)]
[GOAL]
α : Type u_1
inst✝¹ : GeneralizedBooleanAlgebra α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
⊢ (∃ x, x ∈ P.parts ∧ ¬c = ⊥ ∧ x \ b = c) ↔ ∃ d, d ∈ P.parts ∧ ¬d ≤ b ∧ d \ b = c
[PROOFSTEP]
refine' exists_congr fun d ↦ and_congr_right' <| and_congr_left _
[GOAL]
α : Type u_1
inst✝¹ : GeneralizedBooleanAlgebra α
inst✝ : DecidableEq α
a b c : α
P : Finpartition a
d : α
⊢ d \ b = c → (¬c = ⊥ ↔ ¬d ≤ b)
[PROOFSTEP]
rintro rfl
[GOAL]
α : Type u_1
inst✝¹ : GeneralizedBooleanAlgebra α
inst✝ : DecidableEq α
a b : α
P : Finpartition a
d : α
⊢ ¬d \ b = ⊥ ↔ ¬d ≤ b
[PROOFSTEP]
rw [sdiff_eq_bot_iff]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
a : α
ha : a ∈ s
⊢ ∃ t, t ∈ P.parts ∧ a ∈ t
[PROOFSTEP]
simp_rw [← P.supParts] at ha
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
a : α
ha : a ∈ sup P.parts id
⊢ ∃ t, t ∈ P.parts ∧ a ∈ t
[PROOFSTEP]
exact mem_sup.1 ha
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
⊢ ∑ i in P.parts, card i = card s
[PROOFSTEP]
convert congr_arg Finset.card P.biUnion_parts
[GOAL]
case h.e'_2
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
⊢ ∑ i in P.parts, card i = card (Finset.biUnion P.parts id)
[PROOFSTEP]
rw [card_biUnion P.supIndep.pairwiseDisjoint]
[GOAL]
case h.e'_2
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
⊢ ∑ i in P.parts, card i = ∑ u in P.parts, card (id u)
[PROOFSTEP]
rfl
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
⊢ Set.PairwiseDisjoint (↑(map { toFun := singleton, inj' := (_ : Injective singleton) } s)) id
[PROOFSTEP]
rw [Finset.coe_map]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
⊢ Set.PairwiseDisjoint (↑{ toFun := singleton, inj' := (_ : Injective singleton) } '' ↑s) id
[PROOFSTEP]
exact Finset.pairwiseDisjoint_range_singleton.subset (Set.image_subset_range _ _)
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
⊢ sup (map { toFun := singleton, inj' := (_ : Injective singleton) } s) id = s
[PROOFSTEP]
rw [sup_map, comp.left_id, Embedding.coeFn_mk, Finset.sup_singleton']
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
⊢ ¬⊥ ∈ map { toFun := singleton, inj' := (_ : Injective singleton) } s
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
P✝ : Finpartition s✝
s : Finset α
src✝ : Bot (Finpartition s) := inferInstance
P : Finpartition s
t : Finset α
ht : t ∈ ⊥.parts
⊢ ∃ c, c ∈ P.parts ∧ t ≤ c
[PROOFSTEP]
rw [mem_bot_iff] at ht
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
P✝ : Finpartition s✝
s : Finset α
src✝ : Bot (Finpartition s) := inferInstance
P : Finpartition s
t : Finset α
ht : ∃ a, a ∈ s ∧ {a} = t
⊢ ∃ c, c ∈ P.parts ∧ t ≤ c
[PROOFSTEP]
obtain ⟨a, ha, rfl⟩ := ht
[GOAL]
case intro.intro
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P✝ : Finpartition s✝
s : Finset α
src✝ : Bot (Finpartition s) := inferInstance
P : Finpartition s
a : α
ha : a ∈ s
⊢ ∃ c, c ∈ P.parts ∧ {a} ≤ c
[PROOFSTEP]
obtain ⟨t, ht, hat⟩ := P.exists_mem ha
[GOAL]
case intro.intro.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
P✝ : Finpartition s✝
s : Finset α
src✝ : Bot (Finpartition s) := inferInstance
P : Finpartition s
a : α
ha : a ∈ s
t : Finset α
ht : t ∈ P.parts
hat : a ∈ t
⊢ ∃ c, c ∈ P.parts ∧ {a} ≤ c
[PROOFSTEP]
exact ⟨t, ht, singleton_subset_iff.2 hat⟩
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P✝ P : Finpartition s
⊢ card P.parts ≤ card s
[PROOFSTEP]
rw [← card_bot s]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P✝ P : Finpartition s
⊢ card P.parts ≤ card ⊥.parts
[PROOFSTEP]
exact card_mono bot_le
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
x : Finset α
hx : x ∈ ↑(image (fun Q => filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s) (powerset F))
y : Finset α
hy : y ∈ ↑(image (fun Q => filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s) (powerset F))
h : x ≠ y
z : α
hz1 : z ∈ id x
hz2 : z ∈ id y
⊢ x = y
[PROOFSTEP]
rw [mem_coe, mem_image] at hx hy
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
x : Finset α
hx : ∃ a, a ∈ powerset F ∧ filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ a ↔ i ∈ t)) s = x
y : Finset α
hy : ∃ a, a ∈ powerset F ∧ filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ a ↔ i ∈ t)) s = y
h : x ≠ y
z : α
hz1 : z ∈ id x
hz2 : z ∈ id y
⊢ x = y
[PROOFSTEP]
obtain ⟨Q, hQ, rfl⟩ := hx
[GOAL]
case intro.intro
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
y : Finset α
hy : ∃ a, a ∈ powerset F ∧ filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ a ↔ i ∈ t)) s = y
z : α
hz2 : z ∈ id y
Q : Finset (Finset α)
hQ : Q ∈ powerset F
h : filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠ y
hz1 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s)
⊢ filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s = y
[PROOFSTEP]
obtain ⟨R, hR, rfl⟩ := hy
[GOAL]
case intro.intro.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ∈ powerset F
hz1 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s)
R : Finset (Finset α)
hR : R ∈ powerset F
hz2 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
⊢ filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s =
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
[PROOFSTEP]
suffices h' : Q = R
[GOAL]
case intro.intro.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ∈ powerset F
hz1 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s)
R : Finset (Finset α)
hR : R ∈ powerset F
hz2 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
h' : Q = R
⊢ filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s =
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
[PROOFSTEP]
subst h'
[GOAL]
case intro.intro.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ∈ powerset F
hz1 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s)
hR : Q ∈ powerset F
hz2 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s
⊢ filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s =
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s
[PROOFSTEP]
exact of_eq_true (eq_self (filter (fun i ↦ ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s))
[GOAL]
case h'
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ∈ powerset F
hz1 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s)
R : Finset (Finset α)
hR : R ∈ powerset F
hz2 : z ∈ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
⊢ Q = R
[PROOFSTEP]
rw [id, mem_filter] at hz1 hz2
[GOAL]
case h'
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ∈ powerset F
hz1 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ z ∈ t)
R : Finset (Finset α)
hR : R ∈ powerset F
hz2 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ z ∈ t)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
⊢ Q = R
[PROOFSTEP]
rw [mem_powerset] at hQ hR
[GOAL]
case h'
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ⊆ F
hz1 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ z ∈ t)
R : Finset (Finset α)
hR : R ⊆ F
hz2 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ z ∈ t)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
⊢ Q = R
[PROOFSTEP]
ext i
[GOAL]
case h'.a
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ⊆ F
hz1 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ z ∈ t)
R : Finset (Finset α)
hR : R ⊆ F
hz2 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ z ∈ t)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
i : Finset α
⊢ i ∈ Q ↔ i ∈ R
[PROOFSTEP]
refine' ⟨fun hi ↦ _, fun hi ↦ _⟩
[GOAL]
case h'.a.refine'_1
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ⊆ F
hz1 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ z ∈ t)
R : Finset (Finset α)
hR : R ⊆ F
hz2 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ z ∈ t)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
i : Finset α
hi : i ∈ Q
⊢ i ∈ R
[PROOFSTEP]
rwa [hz2.2 _ (hQ hi), ← hz1.2 _ (hQ hi)]
[GOAL]
case h'.a.refine'_2
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
z : α
Q : Finset (Finset α)
hQ : Q ⊆ F
hz1 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ z ∈ t)
R : Finset (Finset α)
hR : R ⊆ F
hz2 : z ∈ s ∧ ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ z ∈ t)
h :
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s ≠
filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ R ↔ i ∈ t)) s
i : Finset α
hi : i ∈ R
⊢ i ∈ Q
[PROOFSTEP]
rwa [hz1.2 _ (hR hi), ← hz2.2 _ (hR hi)]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
⊢ sup (image (fun Q => filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s) (powerset F)) id = s
[PROOFSTEP]
refine' (Finset.sup_le fun t ht ↦ _).antisymm fun a ha ↦ _
[GOAL]
case refine'_1
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
t : Finset α
ht : t ∈ image (fun Q => filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s) (powerset F)
⊢ id t ≤ s
[PROOFSTEP]
rw [mem_image] at ht
[GOAL]
case refine'_1
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
t : Finset α
ht : ∃ a, a ∈ powerset F ∧ filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ a ↔ i ∈ t)) s = t
⊢ id t ≤ s
[PROOFSTEP]
obtain ⟨A, _, rfl⟩ := ht
[GOAL]
case refine'_1.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F A : Finset (Finset α)
left✝ : A ∈ powerset F
⊢ id (filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ A ↔ i ∈ t)) s) ≤ s
[PROOFSTEP]
exact s.filter_subset _
[GOAL]
case refine'_2
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
a : α
ha : a ∈ s
⊢ a ∈ sup (image (fun Q => filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s) (powerset F)) id
[PROOFSTEP]
rw [mem_sup]
[GOAL]
case refine'_2
α : Type u_1
inst✝ : DecidableEq α
s✝ t : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
a : α
ha : a ∈ s
⊢ ∃ v, v ∈ image (fun Q => filter (fun i => ∀ (t : Finset α), t ∈ F → (t ∈ Q ↔ i ∈ t)) s) (powerset F) ∧ a ∈ id v
[PROOFSTEP]
refine'
⟨s.filter fun i ↦ ∀ t, t ∈ F → ((t ∈ F.filter fun u ↦ a ∈ u) ↔ i ∈ t),
mem_image_of_mem _ (mem_powerset.2 <| filter_subset _ _), mem_filter.2 ⟨ha, fun t ht ↦ _⟩⟩
[GOAL]
case refine'_2
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
a : α
ha : a ∈ s
t : Finset α
ht : t ∈ F
⊢ t ∈ filter (fun u => a ∈ u) F ↔ a ∈ t
[PROOFSTEP]
rw [mem_filter]
[GOAL]
case refine'_2
α : Type u_1
inst✝ : DecidableEq α
s✝ t✝ : Finset α
P : Finpartition s✝
s : Finset α
F : Finset (Finset α)
a : α
ha : a ∈ s
t : Finset α
ht : t ∈ F
⊢ t ∈ F ∧ a ∈ t ↔ a ∈ t
[PROOFSTEP]
exact and_iff_right ht
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
⊢ t ∈ (atomise s F).parts ↔ Finset.Nonempty t ∧ ∃ Q x, filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ Q ↔ i ∈ u)) s = t
[PROOFSTEP]
simp only [atomise, ofErase, bot_eq_empty, mem_erase, mem_image, nonempty_iff_ne_empty, mem_singleton, and_comm,
mem_powerset, exists_prop]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
hs : Finset.Nonempty s
⊢ (atomise s ∅).parts = {s}
[PROOFSTEP]
simp only [atomise, powerset_empty, image_singleton, not_mem_empty, IsEmpty.forall_iff, imp_true_iff, filter_True]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
hs : Finset.Nonempty s
⊢ (ofErase {s} (_ : SupIndep {s} id) (_ : sup {s} id = s)).parts = {s}
[PROOFSTEP]
exact erase_eq_of_not_mem (not_mem_singleton.2 hs.ne_empty.symm)
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
hts : t ⊆ s
⊢ Finset.biUnion (filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts) id = t
[PROOFSTEP]
ext a
[GOAL]
case a
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
hts : t ⊆ s
a : α
⊢ a ∈ Finset.biUnion (filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts) id ↔ a ∈ t
[PROOFSTEP]
refine' mem_biUnion.trans ⟨fun ⟨u, hu, ha⟩ ↦ (mem_filter.1 hu).2.1 ha, fun ha ↦ _⟩
[GOAL]
case a
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
hts : t ⊆ s
a : α
ha : a ∈ t
⊢ ∃ a_1, a_1 ∈ filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts ∧ a ∈ id a_1
[PROOFSTEP]
obtain ⟨u, hu, hau⟩ := (atomise s F).exists_mem (hts ha)
[GOAL]
case a.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
hts : t ⊆ s
a : α
ha : a ∈ t
u : Finset α
hu : u ∈ (atomise s F).parts
hau : a ∈ u
⊢ ∃ a_1, a_1 ∈ filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts ∧ a ∈ id a_1
[PROOFSTEP]
refine' ⟨u, mem_filter.2 ⟨hu, fun b hb ↦ _, _, hau⟩, hau⟩
[GOAL]
case a.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
hts : t ⊆ s
a : α
ha : a ∈ t
u : Finset α
hu : u ∈ (atomise s F).parts
hau : a ∈ u
b : α
hb : b ∈ u
⊢ b ∈ t
[PROOFSTEP]
obtain ⟨Q, _hQ, rfl⟩ := (mem_atomise.1 hu).2
[GOAL]
case a.intro.intro.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
hts : t ⊆ s
a : α
ha : a ∈ t
b : α
Q : Finset (Finset α)
_hQ : Q ⊆ F
hu : filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ Q ↔ i ∈ u)) s ∈ (atomise s F).parts
hau : a ∈ filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ Q ↔ i ∈ u)) s
hb : b ∈ filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ Q ↔ i ∈ u)) s
⊢ b ∈ t
[PROOFSTEP]
rw [mem_filter] at hau hb
[GOAL]
case a.intro.intro.intro.intro
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
hts : t ⊆ s
a : α
ha : a ∈ t
b : α
Q : Finset (Finset α)
_hQ : Q ⊆ F
hu : filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ Q ↔ i ∈ u)) s ∈ (atomise s F).parts
hau : a ∈ s ∧ ∀ (u : Finset α), u ∈ F → (u ∈ Q ↔ a ∈ u)
hb : b ∈ s ∧ ∀ (u : Finset α), u ∈ F → (u ∈ Q ↔ b ∈ u)
⊢ b ∈ t
[PROOFSTEP]
rwa [← hb.2 _ ht, hau.2 _ ht]
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
⊢ card (filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts) ≤ 2 ^ (card F - 1)
[PROOFSTEP]
suffices h :
((atomise s F).parts.filter fun u ↦ u ⊆ t ∧ u.Nonempty) ⊆
(F.erase t).powerset.image fun P ↦ s.filter fun i ↦ ∀ x ∈ F, x ∈ insert t P ↔ i ∈ x
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
h :
filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts ⊆
image (fun P => filter (fun i => ∀ (x : Finset α), x ∈ F → (x ∈ insert t P ↔ i ∈ x)) s) (powerset (erase F t))
⊢ card (filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts) ≤ 2 ^ (card F - 1)
[PROOFSTEP]
refine' (card_le_of_subset h).trans (card_image_le.trans _)
[GOAL]
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
h :
filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts ⊆
image (fun P => filter (fun i => ∀ (x : Finset α), x ∈ F → (x ∈ insert t P ↔ i ∈ x)) s) (powerset (erase F t))
⊢ card (powerset (erase F t)) ≤ 2 ^ (card F - 1)
[PROOFSTEP]
rw [card_powerset, card_erase_of_mem ht]
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
⊢ filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts ⊆
image (fun P => filter (fun i => ∀ (x : Finset α), x ∈ F → (x ∈ insert t P ↔ i ∈ x)) s) (powerset (erase F t))
[PROOFSTEP]
rw [subset_iff]
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
⊢ ∀ ⦃x : Finset α⦄,
x ∈ filter (fun u => u ⊆ t ∧ Finset.Nonempty u) (atomise s F).parts →
x ∈ image (fun P => filter (fun i => ∀ (x : Finset α), x ∈ F → (x ∈ insert t P ↔ i ∈ x)) s) (powerset (erase F t))
[PROOFSTEP]
simp_rw [mem_image, mem_powerset, mem_filter, and_imp, Finset.Nonempty, exists_imp, mem_atomise, and_imp,
Finset.Nonempty, exists_imp]
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
⊢ ∀ ⦃x : Finset α⦄ (x_1 : α),
x_1 ∈ x →
∀ (x_2 : Finset (Finset α)),
x_2 ⊆ F →
filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ x_2 ↔ i ∈ u)) s = x →
x ⊆ t →
∀ (x_4 : α),
x_4 ∈ x →
∃ a, a ⊆ erase F t ∧ filter (fun i => ∀ (x : Finset α), x ∈ F → (x ∈ insert t a ↔ i ∈ x)) s = x
[PROOFSTEP]
rintro P' i hi P PQ rfl hy₂ j _hj
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P✝ : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
i : α
P : Finset (Finset α)
PQ : P ⊆ F
hi : i ∈ filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ P ↔ i ∈ u)) s
hy₂ : filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ P ↔ i ∈ u)) s ⊆ t
j : α
_hj : j ∈ filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ P ↔ i ∈ u)) s
⊢ ∃ a,
a ⊆ erase F t ∧
filter (fun i => ∀ (x : Finset α), x ∈ F → (x ∈ insert t a ↔ i ∈ x)) s =
filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ P ↔ i ∈ u)) s
[PROOFSTEP]
refine' ⟨P.erase t, erase_subset_erase _ PQ, _⟩
[GOAL]
case h
α : Type u_1
inst✝ : DecidableEq α
s t : Finset α
P✝ : Finpartition s
F : Finset (Finset α)
ht : t ∈ F
i : α
P : Finset (Finset α)
PQ : P ⊆ F
hi : i ∈ filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ P ↔ i ∈ u)) s
hy₂ : filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ P ↔ i ∈ u)) s ⊆ t
j : α
_hj : j ∈ filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ P ↔ i ∈ u)) s
⊢ filter (fun i => ∀ (x : Finset α), x ∈ F → (x ∈ insert t (erase P t) ↔ i ∈ x)) s =
filter (fun i => ∀ (u : Finset α), u ∈ F → (u ∈ P ↔ i ∈ u)) s
[PROOFSTEP]
simp only [insert_erase (((mem_filter.1 hi).2 _ ht).2 <| hy₂ hi)]
|
{"mathlib_filename": "Mathlib.Order.Partition.Finpartition", "llama_tokens": 28454}
|
STATIC_PROPERTIES = [:n, :num_steps, :dt, :seed, :randomize, :nmac]
function initialize(log::Dict{String,Any}, sim::Simulator)
sim.logging || return
for p in STATIC_PROPERTIES
log["$p"] = getproperty(sim, p)
end
log["t"] = [sim.step * sim.dt]
for i in 1:sim.n
log["ac_$i"] = [vec(sim.acs[i])]
log["cas_$i"] = [vec(sim.cass[i])]
end
for (k, v) in sim.metrics.d
log[k] = [v]
end
end
function update(log::Dict{String,Any}, sim::Simulator)
sim.logging || return
push!(log["t"], sim.step * sim.dt)
for i in 1:sim.n
push!(log["ac_$i"], vec(sim.acs[i]))
push!(log["cas_$i"], vec(sim.cass[i]))
end
for (k, v) in sim.metrics.d
push!(log[k], v)
end
end
|
{"hexsha": "6b1ec967958a4d2eb883ad29b3b8b0505d7883a1", "size": 752, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/cas/src/logging.jl", "max_stars_repo_name": "NASA-SW-VnV/AdaStress.jl", "max_stars_repo_head_hexsha": "a8802eeb2c7890a100ff87470853b7d1acda03fb", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/cas/src/logging.jl", "max_issues_repo_name": "NASA-SW-VnV/AdaStress.jl", "max_issues_repo_head_hexsha": "a8802eeb2c7890a100ff87470853b7d1acda03fb", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-14T08:13:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T08:13:03.000Z", "max_forks_repo_path": "examples/cas/src/logging.jl", "max_forks_repo_name": "NASA-SW-VnV/AdaStress.jl", "max_forks_repo_head_hexsha": "a8802eeb2c7890a100ff87470853b7d1acda03fb", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8888888889, "max_line_length": 67, "alphanum_fraction": 0.5545212766, "num_tokens": 251}
|
import numpy as np
import tensorflow as tf
from .bbox import *
class BBoxesLayer(object):
def __init__(self, mod_tra=True, box_cls_num=None, img_shp=None):
self.img_shp = img_shp
self.mod_tra = mod_tra
self.box_cls_num = box_cls_num
self.box_pol_num = 300
self.box_siz_min = 16
self.box_prb_min = 0.5
self.box_nms_pre = None
self.box_nms_pst = 100 #200
self.box_nms_max = 0.3 #0.2
self.box_msk_min = 0.4
self.box_msk_siz = [21, 21]
self.meg_ovp_min = 0.5
def generate_boxs_img(self, elems=None):
#奇葩!和以前一点不一样!!! 这里看成是对ROI的分类、打分、mask预测,而不是对由ROI产生的BOX的,因此不对ROI做剔除!!!
#按道理说,这么做比之前的做法合理!!!
#(M, 4) #(M, C) #(M, 4) #(M, C, 21, 21, 2)
rois, roi_prbs_pst, roi_prds_pst, roi_msks_pst, roi_num = elems
rois = rois [0:roi_num]
roi_prbs_pst = roi_prbs_pst[0:roi_num]
roi_prds_pst = roi_prds_pst[0:roi_num]
roi_msks_pst = roi_msks_pst[0:roi_num]
roi_clss = tf.argmax(roi_prbs_pst, axis=-1)
roi_clss = tf.cast(roi_clss, tf.int32)
roi_prbs = tf.reduce_max(roi_prbs_pst, axis=-1)
idxs = tf.range(roi_num)
idxs = tf.stack([idxs, roi_clss], axis=-1)
roi_msks = tf.gather_nd(roi_msks_pst, idxs) #(M, 21, 21, 2)
roi_msks = roi_msks[..., 1] #(M, 21, 21)
#roi_prds_pst = tf.gather_nd(roi_prds_pst, idxs) #如果roi的预测是定类的话要换上这段
boxs = bbox_transform_inv(rois, roi_prds_pst)
boxs = bbox_clip(boxs, [0.0, 0.0, self.img_shp[0]-1.0, self.img_shp[1]-1.0])
#剔除过小的box
idxs = bbox_filter(boxs, self.box_siz_min)
boxs = tf.gather_nd(boxs, idxs)
box_num = tf.shape(boxs)[0]
#padding
paddings = [[0, self.box_pol_num-box_num], [0, 0]]
boxs = tf.pad(boxs, paddings, "CONSTANT")
paddings = [[0, self.box_pol_num-roi_num]]
roi_clss = tf.pad(roi_clss, paddings, "CONSTANT")
roi_prbs = tf.pad(roi_prbs, paddings, "CONSTANT")
paddings = [[0, self.box_pol_num-roi_num], [0, 0], [0, 0]]
roi_msks = tf.pad(roi_msks, paddings, "CONSTANT")
return boxs, box_num, roi_clss, roi_prbs, roi_msks
def generate_boxs(self, rois=None, roi_prbs_pst=None, roi_prds_pst=None, roi_msks_pst=None, roi_nums=None):
elems = [rois, roi_prbs_pst, roi_prds_pst, roi_msks_pst, roi_nums]
boxs, box_nums, roi_clss, roi_prbs, roi_msks = \
tf.map_fn(self.generate_boxs_img, elems, dtype=(tf.float32, tf.int32, tf.int32, tf.float32, tf.float32),
parallel_iterations=10, back_prop=False, swap_memory=True, infer_shape=True)
return boxs, box_nums, roi_clss, roi_prbs, roi_msks
def concat_boxs_img(self, elems=None):
rois, roi_clss, roi_prbs, roi_msks, roi_num, boxs, box_clss, box_prbs, box_msks, box_num = elems
rois = rois [0:roi_num] #(M0, 4)
roi_clss = roi_clss[0:roi_num] #(M0)
roi_prbs = roi_prbs[0:roi_num] #(M0)
roi_msks = roi_msks[0:roi_num] #(M0, 21, 21)
boxs = boxs [0:box_num] #(M1, 4)
box_clss = box_clss[0:box_num] #(M1)
box_prbs = box_prbs[0:box_num] #(M1)
box_msks = box_msks[0:box_num] #(M1, 21, 21)
box_num = roi_num + box_num
boxs = tf.concat([boxs, rois], axis=0) #(M, 4)
box_clss = tf.concat([box_clss, roi_clss], axis=0) #(M)
box_prbs = tf.concat([box_prbs, roi_prbs], axis=0) #(M)
box_msks = tf.concat([box_msks, roi_msks], axis=0) #(M, 21, 21)
paddings = [[0, self.box_pol_num*2-box_num], [0, 0]]
boxs = tf.pad(boxs, paddings, "CONSTANT")
paddings = [[0, self.box_pol_num*2-box_num]]
box_clss = tf.pad(box_clss, paddings, "CONSTANT")
box_prbs = tf.pad(box_prbs, paddings, "CONSTANT")
paddings = [[0, self.box_pol_num*2-box_num], [0, 0], [0, 0]]
box_msks = tf.pad(box_msks, paddings, "CONSTANT")
return boxs, box_clss, box_prbs, box_msks, box_num
def concat_boxs(self, rois, roi_clss, roi_prbs, roi_msks, roi_nums, boxs, box_clss, box_prbs, box_msks, box_nums):
elems = [rois, roi_clss, roi_prbs, roi_msks, roi_nums, boxs, box_clss, box_prbs, box_msks, box_nums]
boxs, box_clss, box_prbs, box_msks, box_nums = \
tf.map_fn(self.concat_boxs_img, elems, dtype=(tf.float32, tf.int32, tf.float32, tf.float32, tf.int32),
parallel_iterations=10, back_prop=False, swap_memory=True, infer_shape=True)
return boxs, box_clss, box_prbs, box_msks, box_nums
def merge_boxs_img(self, elems=None):
boxs, box_clss, box_prbs, box_msks, box_num = elems
boxs = boxs [0:box_num] #(M, 4)
box_clss = box_clss[0:box_num] #(M)
box_prbs = box_prbs[0:box_num] #(M)
box_msks = box_msks[0:box_num] #(M, 21, 21)
#设置一个box索引,避免大量的gather操作(prds、msks),节省内存,提升速度
kep_idxs = tf.range(box_num)
#剔除背景box
idxs = tf.where(box_clss>0)
kep_idxs = tf.gather_nd(kep_idxs, idxs)
box_clss = tf.gather_nd(box_clss, idxs)
box_prbs = tf.gather_nd(box_prbs, idxs)
#剔除得分较低的box
if self.box_prb_min is not None:
idxs = tf.where(box_prbs>=self.box_prb_min)
kep_idxs = tf.gather_nd(kep_idxs, idxs)
box_clss = tf.gather_nd(box_clss, idxs)
box_prbs = tf.gather_nd(box_prbs, idxs)
#进一步剔除过多的box
if self.box_nms_pre is not None:
box_nms_pre = tf.minimum(self.box_nms_pre, tf.shape(kep_idxs)[0])
box_prbs, idxs = tf.nn.top_k(box_prbs, k=box_nms_pre, sorted=True)
kep_idxs = tf.gather(kep_idxs, idxs)
box_clss = tf.gather(box_clss, idxs)
#根据kep_idxs进行剩余的gather操作
boxs = tf.gather(boxs, kep_idxs)
box_msks = tf.gather(box_msks, kep_idxs)
#做逐类的nms
boxs_tmp = tf.zeros(dtype=tf.float32, shape=[0, 4])
box_clss_kep = tf.zeros(dtype=tf.int32, shape=[0])
box_prbs_kep = tf.zeros(dtype=tf.float32, shape=[0])
def cond0(i, boxs, box_clss, box_prbs, boxs_tmp, box_clss_kep, box_prbs_kep):
c = tf.less(i, self.box_cls_num)
return c
def body0(i, boxs, box_clss, box_prbs, boxs_tmp, box_clss_kep, box_prbs_kep):
#选出对应类的rois
idxs = tf.where(tf.equal(box_clss, i))
boxs_cls = tf.gather_nd(boxs, idxs)
box_clss_cls = tf.gather_nd(box_clss, idxs)
box_prbs_cls = tf.gather_nd(box_prbs, idxs)
#进行非极大值抑制操作
idxs = tf.image.non_max_suppression(boxs_cls, box_prbs_cls, self.box_nms_pst, self.box_nms_max)
boxs_cls = tf.gather(boxs_cls, idxs)
box_clss_cls = tf.gather(box_clss_cls, idxs)
box_prbs_cls = tf.gather(box_prbs_cls, idxs)
#保存结果
boxs_tmp = tf.concat([boxs_tmp, boxs_cls ], axis=0)
box_clss_kep = tf.concat([box_clss_kep, box_clss_cls], axis=0)
box_prbs_kep = tf.concat([box_prbs_kep, box_prbs_cls], axis=0)
return [i+1, boxs, box_clss, box_prbs, boxs_tmp, box_clss_kep, box_prbs_kep]
i = tf.constant(1) #要剔除背景类
[i, boxs, box_clss, box_prbs, boxs_tmp, box_clss_kep, box_prbs_kep] = \
tf.while_loop(cond0, body0, \
loop_vars=[i, boxs, box_clss, box_prbs, boxs_tmp, box_clss_kep, box_prbs_kep], \
shape_invariants=[i.get_shape(), boxs.get_shape(), box_clss.get_shape(), box_prbs.get_shape(), \
tf.TensorShape([None, 4]), tf.TensorShape([None]), tf.TensorShape([None])], \
parallel_iterations=10, back_prop=False, swap_memory=True)
box_num = tf.minimum(self.box_nms_pst, tf.shape(boxs_tmp)[0])
box_prbs_kep, idxs = tf.nn.top_k(box_prbs_kep, k=box_num, sorted=False)
boxs_tmp = tf.gather(boxs_tmp, idxs)
box_clss_kep = tf.gather(box_clss_kep, idxs)
#融合mask
boxs_kep = tf.zeros(dtype=tf.float32, shape=[0, 4])
box_msks_kep = tf.zeros(dtype=tf.float32, shape=[0]+self.box_msk_siz)
box_idxs_kep = tf.zeros(dtype=tf.int64, shape=[0, 1]) #并行计算要保证对应关系
def cond1(i, boxs, box_clss, box_prbs, box_msks, boxs_tmp, box_clss_kep, boxs_kep, box_msks_kep, box_idxs_kep):
c = tf.less(i, self.box_cls_num)
return c
def body1(i, boxs, box_clss, box_prbs, box_msks, boxs_tmp, box_clss_kep, boxs_kep, box_msks_kep, box_idxs_kep):
#选出对应类的boxs
idxs = tf.where(tf.equal(box_clss, i))
boxs_cls = tf.gather_nd(boxs, idxs)
box_prbs_cls = tf.gather_nd(box_prbs, idxs)
box_msks_cls = tf.gather_nd(box_msks, idxs)
box_idxs_cls = tf.where(tf.equal(box_clss_kep, i)) #选出对应类别的box和其相应的idxs
boxs_run = tf.gather_nd(boxs_tmp, box_idxs_cls)
boxs_hld = tf.zeros(dtype=tf.float32, shape=[0, 4])
box_msks_hld = tf.zeros(dtype=tf.float32, shape=[0]+self.box_msk_siz)
box_idxs_hld = tf.zeros(dtype=tf.int32, shape=[0]) #并行计算要保证对应关系
def cond(j, boxs_run, boxs_cls, box_prbs_cls, box_msks_cls, boxs_hld, box_msks_hld, box_idxs_hld):
c = tf.less(j, tf.shape(boxs_run)[0])
return c
def body(j, boxs_run, boxs_cls, box_prbs_cls, box_msks_cls, boxs_hld, box_msks_hld, box_idxs_hld):
box_run = boxs_run[j][tf.newaxis, :]
box_ovps = bbox_overlaps(boxs_cls, box_run) #(M0, 1)
box_ovps = tf.squeeze(box_ovps, axis=[1]) #(M0)
idxs = tf.where(box_ovps>=self.meg_ovp_min)
boxs_meg = tf.gather_nd(boxs_cls, idxs) #(M1, 4)
box_prbs_meg = tf.gather_nd(box_prbs_cls, idxs) #(M1)
box_msks_meg = tf.gather_nd(box_msks_cls, idxs) #(M1, 21, 21)
'''
assert_op = tf.Assert(tf.size(box_msks_meg)>0, [j, tf.shape(boxs_run)[0], box_ovps, box_run, boxs_cls, \
idxs, boxs_meg, box_prbs_meg, box_msks_meg], summarize=100)
with tf.control_dependencies([assert_op]):
box_msks_meg = tf.identity(box_msks_meg)
'''
box_wgts = box_prbs_meg / tf.reduce_sum(box_prbs_meg)
#boxs_meg = bbox_clip(boxs_meg, [0, 0, self.img_shp[0]-1.0, self.img_shp[1]-1.0]) #之前还原出boxs时已经clip了
boxs_meg = tf.cast(tf.round(boxs_meg), dtype=tf.int32)
box_ymns, box_xmns, box_ymxs, box_xmxs = tf.split(boxs_meg, 4, axis=-1)
box_hgts = box_ymxs - box_ymns + 1
box_wdhs = box_xmxs - box_xmns + 1
box_lehs = tf.concat([box_hgts, box_wdhs], axis=-1)
box_ymn = tf.reduce_min(box_ymns)
box_xmn = tf.reduce_min(box_xmns)
box_ymx = tf.reduce_max(box_ymxs)
box_xmx = tf.reduce_max(box_xmxs)
pads_hgt_fnt = box_ymns - box_ymn
pads_wdh_fnt = box_xmns - box_xmn
pads_hgt_bak = box_ymx - box_ymxs
pads_wdh_bak = box_xmx - box_xmxs
pads_hgt = tf.concat([pads_hgt_fnt, pads_hgt_bak], axis=-1) #(M1, 2)
pads_wdh = tf.concat([pads_wdh_fnt, pads_wdh_bak], axis=-1) #(M1, 2)
box_pads = tf.stack([pads_hgt, pads_wdh], axis=1) #(M1, 2, 2)
def resize_mask(elems=None):
box_msk_meg, box_wgt, box_leh, box_pad = elems
box_msk_meg = tf.expand_dims(box_msk_meg, axis=-1)
box_msk_meg = tf.image.resize_images(box_msk_meg, box_leh, \
method=tf.image.ResizeMethod.BILINEAR, align_corners=False)
box_msk_meg = tf.squeeze(box_msk_meg, axis=[-1])
box_msk_meg = tf.cast(box_msk_meg>=self.box_msk_min, dtype=tf.float32)
box_msk_meg = box_msk_meg * box_wgt
box_msk_meg = tf.pad(box_msk_meg, box_pad, "CONSTANT")
return box_msk_meg
#当没有box时,tf.map_fn不会拆开,所以tf.image.resize_images是安全的
elems = [box_msks_meg, box_wgts, box_lehs, box_pads]
box_msks_meg = tf.map_fn(resize_mask, elems, dtype=tf.float32,
parallel_iterations=10, back_prop=False, swap_memory=True, infer_shape=True)
box_msk_meg = tf.reduce_sum(box_msks_meg, axis=0)
box_msk_idxs = tf.where(box_msk_meg>=self.box_msk_min)
box_crd_min = tf.maximum(tf.cast(tf.reduce_min(box_msk_idxs, axis=0), dtype=tf.int32), 0)
box_crd_max = tf.cast(tf.reduce_max(box_msk_idxs, axis=0), dtype=tf.int32)
box_msk_meg = box_msk_meg[box_crd_min[0]:box_crd_max[0]+1, box_crd_min[1]:box_crd_max[1]+1]
box_msk_meg = tf.expand_dims(box_msk_meg, axis=-1)
box_msk_meg = tf.image.resize_images(box_msk_meg, self.box_msk_siz, \
method=tf.image.ResizeMethod.BILINEAR, align_corners=False)
box_msk_meg = tf.squeeze(box_msk_meg, axis=[-1])
box_msk_meg = tf.expand_dims(box_msk_meg, axis=0)
box_meg = tf.concat([box_crd_min, box_crd_max], axis=0) + \
tf.stack([box_ymn, box_xmn, box_ymn, box_xmn], axis=0)
box_meg = tf.cast(box_meg, dtype=tf.float32)
box_meg = tf.expand_dims(box_meg, axis=0)
box_idx_meg = tf.expand_dims(j, axis=0)
#保存结果
boxs_hld = tf.concat([boxs_hld, box_meg ], axis=0)
box_msks_hld = tf.concat([box_msks_hld, box_msk_meg], axis=0)
box_idxs_hld = tf.concat([box_idxs_hld, box_idx_meg], axis=0)
return [j+1, boxs_run, boxs_cls, box_prbs_cls, box_msks_cls, boxs_hld, box_msks_hld, box_idxs_hld]
j = tf.constant(0)
[j, boxs_run, boxs_cls, box_prbs_cls, box_msks_cls, boxs_hld, box_msks_hld, box_idxs_hld] = \
tf.while_loop(cond, body, \
loop_vars=[j, boxs_run, boxs_cls, box_prbs_cls, box_msks_cls, boxs_hld, box_msks_hld, box_idxs_hld], \
shape_invariants=[j.get_shape(), boxs_run.get_shape(), boxs_cls.get_shape(), \
box_prbs_cls.get_shape(), box_msks_cls.get_shape(), tf.TensorShape([None, 4]), \
tf.TensorShape([None]+self.box_msk_siz), tf.TensorShape([None])], \
parallel_iterations=10, back_prop=False, swap_memory=True)
box_idxs_hld = tf.gather(box_idxs_cls, box_idxs_hld)
#保存结果
boxs_kep = tf.concat([boxs_kep, boxs_hld ], axis=0)
box_msks_kep = tf.concat([box_msks_kep, box_msks_hld], axis=0)
box_idxs_kep = tf.concat([box_idxs_kep, box_idxs_hld], axis=0)
return [i+1, boxs, box_clss, box_prbs, box_msks, boxs_tmp, box_clss_kep, boxs_kep, box_msks_kep, box_idxs_kep]
i = tf.constant(1) #要剔除背景类
[i, boxs, box_clss, box_prbs, box_msks, boxs_tmp, box_clss_kep, boxs_kep, box_msks_kep, box_idxs_kep] = \
tf.while_loop(cond1, body1, loop_vars=\
[i, boxs, box_clss, box_prbs, box_msks, boxs_tmp, box_clss_kep, boxs_kep, box_msks_kep, box_idxs_kep], \
shape_invariants=[i.get_shape(), boxs.get_shape(), box_clss.get_shape(), \
box_prbs.get_shape(), box_msks.get_shape(), boxs_tmp.get_shape(), \
box_clss_kep.get_shape(), tf.TensorShape([None, 4]), \
tf.TensorShape([None]+self.box_msk_siz), tf.TensorShape([None, 1])], \
parallel_iterations=10, back_prop=False, swap_memory=True)
#boxs_kep, box_msks_kep, box_idxs_kep
box_clss_kep = tf.gather_nd(box_clss_kep, box_idxs_kep)
box_prbs_kep = tf.gather_nd(box_prbs_kep, box_idxs_kep)
box_num = tf.shape(boxs_kep)[0]
paddings = [[0, self.box_nms_pst-box_num], [0, 0]]
boxs_kep = tf.pad(boxs_kep, paddings, "CONSTANT")
paddings = [[0, self.box_nms_pst-box_num]]
box_clss_kep = tf.pad(box_clss_kep, paddings, "CONSTANT")
box_prbs_kep = tf.pad(box_prbs_kep, paddings, "CONSTANT")
paddings = [[0, self.box_nms_pst-box_num], [0, 0], [0, 0]]
box_msks_kep = tf.pad(box_msks_kep, paddings, "CONSTANT")
return boxs_kep, box_clss_kep, box_prbs_kep, box_msks_kep, box_num
def merge_boxs(self, boxs=None, box_clss=None, box_prbs=None, box_msks=None, box_nums=None):
elems = [boxs, box_clss, box_prbs, box_msks, box_nums]
boxs, box_clss, box_prbs, box_msks, box_nums = \
tf.map_fn(self.merge_boxs_img, elems, dtype=(tf.float32, tf.int32, tf.float32, tf.float32, tf.int32),
parallel_iterations=10, back_prop=False, swap_memory=True, infer_shape=True)
return boxs, box_clss, box_prbs, box_msks, box_nums
|
{"hexsha": "d4d83416541bb5a9cd9551941b1fa1fbe012dd7f", "size": 18091, "ext": "py", "lang": "Python", "max_stars_repo_path": "Mybase/mask_rcnn_utils/bboxes_layer1.py", "max_stars_repo_name": "czyczyyzc/MyMaskRCNN", "max_stars_repo_head_hexsha": "e5a451fd05c593ae05d6e596813fc63aad7af2de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-16T08:10:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T08:10:12.000Z", "max_issues_repo_path": "Mybase/mask_rcnn_utils/bboxes_layer1.py", "max_issues_repo_name": "czyczyyzc/MyMaskRCNN", "max_issues_repo_head_hexsha": "e5a451fd05c593ae05d6e596813fc63aad7af2de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mybase/mask_rcnn_utils/bboxes_layer1.py", "max_forks_repo_name": "czyczyyzc/MyMaskRCNN", "max_forks_repo_head_hexsha": "e5a451fd05c593ae05d6e596813fc63aad7af2de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.5098684211, "max_line_length": 132, "alphanum_fraction": 0.5731579238, "include": true, "reason": "import numpy", "num_tokens": 5704}
|
# 0712.py
import cv2
import numpy as np
#1
src = cv2.imread('./data/lena.jpg')
down2 = cv2.pyrDown(src)
down4 = cv2.pyrDown(down2)
print('down2.shape=', down2.shape)
print('down2.shape=', down2.shape)
#2
up2 = cv2.pyrUp(src)
up4 = cv2.pyrUp(up2)
print('up2.shape=', up2.shape)
print('up4.shape=', up4.shape)
cv2.imshow('down2',down2)
##cv2.imshow('down4',down4)
cv2.imshow('up2',up2)
##cv2.imshow('up4',up4)
cv2.waitKey()
cv2.destroyAllWindows()
|
{"hexsha": "28c8260bcdade8e99d8570dbadd094e6bd9c1078", "size": 472, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter07/0712.py", "max_stars_repo_name": "0201shj/Python-OpenCV", "max_stars_repo_head_hexsha": "249f8cc9404e547da0f5c68000f29f2e598562a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter07/0712.py", "max_issues_repo_name": "0201shj/Python-OpenCV", "max_issues_repo_head_hexsha": "249f8cc9404e547da0f5c68000f29f2e598562a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter07/0712.py", "max_forks_repo_name": "0201shj/Python-OpenCV", "max_forks_repo_head_hexsha": "249f8cc9404e547da0f5c68000f29f2e598562a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6666666667, "max_line_length": 36, "alphanum_fraction": 0.6588983051, "include": true, "reason": "import numpy", "num_tokens": 164}
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : Sklearn_lego.py
@Time : 2019/07/22 20:16:06
@Author : xiao ming
@Version : 1.0
@Contact : xiaoming3526@gmail.com
@Desc : 用sklearn实现下岭回归
@github : https://github.com/aimi-cn/AILearners
'''
# here put the import lib
# -*-coding:utf-8 -*-
import numpy as np
from bs4 import BeautifulSoup
import random
'''
@description: 从页面读取数据,生成retX和retY列表
@param: retX - 数据X
retY - 数据Y
inFile - HTML文件
yr - 年份
numPce - 乐高部件数目
origPrc - 原价
@return:
'''
def scrapePage(retX, retY, inFile, yr, numPce, origPrc):
# 打开并读取HTML文件
with open(inFile, encoding='utf-8') as f:
html = f.read()
soup = BeautifulSoup(html)
i = 1
# 根据HTML页面结构进行解析
currentRow = soup.find_all('table', r = "%d" % i)
while(len(currentRow) != 0):
currentRow = soup.find_all('table', r = "%d" % i)
title = currentRow[0].find_all('a')[1].text
lwrTitle = title.lower()
# 查找是否有全新标签
if (lwrTitle.find('new') > -1) or (lwrTitle.find('nisb') > -1):
newFlag = 1.0
else:
newFlag = 0.0
# 查找是否已经标志出售,我们只收集已出售的数据
soldUnicde = currentRow[0].find_all('td')[3].find_all('span')
if len(soldUnicde) == 0:
print("商品 #%d 没有出售" % i)
else:
# 解析页面获取当前价格
soldPrice = currentRow[0].find_all('td')[4]
priceStr = soldPrice.text
priceStr = priceStr.replace('$','')
priceStr = priceStr.replace(',','')
if len(soldPrice) > 1:
priceStr = priceStr.replace('Free shipping', '')
sellingPrice = float(priceStr)
# 去掉不完整的套装价格
if sellingPrice > origPrc * 0.5:
print("%d\t%d\t%d\t%f\t%f" % (yr, numPce, newFlag, origPrc, sellingPrice))
retX.append([yr, numPce, newFlag, origPrc])
retY.append(sellingPrice)
i += 1
currentRow = soup.find_all('table', r = "%d" % i)
'''
@description: 依次读取六种乐高套装的数据,并生成数据矩阵
@param {type}
@return:
'''
def setDataCollect(retX, retY):
scrapePage(retX, retY, 'C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/lego/lego8288.html', 2006, 800, 49.99) #2006年的乐高8288,部件数目800,原价49.99
scrapePage(retX, retY, 'C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/lego/lego10030.html', 2002, 3096, 269.99) #2002年的乐高10030,部件数目3096,原价269.99
scrapePage(retX, retY, 'C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/lego/lego10179.html', 2007, 5195, 499.99) #2007年的乐高10179,部件数目5195,原价499.99
scrapePage(retX, retY, 'C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/lego/lego10181.html', 2007, 3428, 199.99) #2007年的乐高10181,部件数目3428,原价199.99
scrapePage(retX, retY, 'C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/lego/lego10189.html', 2008, 5922, 299.99) #2008年的乐高10189,部件数目5922,原价299.99
scrapePage(retX, retY, 'C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/lego/lego10196.html', 2009, 3263, 249.99) #2009年的乐高10196,部件数目3263,原价249.99
'''
@description: 使用sklearn
@param {type}
@return:
'''
def usesklearn():
from sklearn import linear_model
reg = linear_model.Ridge(alpha = .5)
lgX = []
lgY = []
setDataCollect(lgX, lgY)
reg.fit(lgX, lgY)
print('%f%+f*年份%+f*部件数量%+f*是否为全新%+f*原价' % (reg.intercept_, reg.coef_[0], reg.coef_[1], reg.coef_[2], reg.coef_[3]))
if __name__ == '__main__':
usesklearn()
|
{"hexsha": "189b81e7ecf1c5d489e5821596e15ef387829f00", "size": 3737, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/py2.x/ml/jqxxsz/8.Regression/lego/Sklearn_lego.py", "max_stars_repo_name": "BinLeeBit/AILearners", "max_stars_repo_head_hexsha": "39e96337b89470cd75e0653eb94ee069b7409724", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 350, "max_stars_repo_stars_event_min_datetime": "2019-04-17T06:48:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:37:24.000Z", "max_issues_repo_path": "src/py2.x/ml/jqxxsz/8.Regression/lego/Sklearn_lego.py", "max_issues_repo_name": "TingFeng-Git/AILearners", "max_issues_repo_head_hexsha": "5aec29a13fbb145a7a55e41ceedb5b42f5bbb1a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-19T20:55:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-19T20:55:33.000Z", "max_forks_repo_path": "src/py2.x/ml/jqxxsz/8.Regression/lego/Sklearn_lego.py", "max_forks_repo_name": "TingFeng-Git/AILearners", "max_forks_repo_head_hexsha": "5aec29a13fbb145a7a55e41ceedb5b42f5bbb1a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2019-04-17T06:51:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:43:12.000Z", "avg_line_length": 38.9270833333, "max_line_length": 199, "alphanum_fraction": 0.6125234145, "include": true, "reason": "import numpy", "num_tokens": 1373}
|
import os
import sys
import subprocess
import numpy as np
from openvino.inference_engine import IECore
class OpenVINOModel:
"""Class providing OpenVINO backend for TensorFlow models.
Class performs conversion to OpenVINO IR format using Model Optimizer tool.
"""
def __init__(self, base_model):
self.ie = IECore()
self.exec_net = None
self.base_model = base_model
self.input_names = None
self.input_ids = None
self.device = "CPU"
def _read_tf_model(self, inputs):
# Dump a model in SavedModel format
self.base_model.save('model')
# Read input signatures (names, shapes)
signatures = self.base_model._get_save_spec()
self.input_names = []
self.input_ids = []
input_shapes = []
for inp in signatures:
inp_idx = int(inp.name[inp.name.find('_') + 1:]) - 1
shape = list(inputs[inp_idx].shape)
if np.prod(shape) == 0:
continue
self.input_names.append(inp.name)
self.input_ids.append(inp_idx)
input_shapes.append(str(shape))
# Run Model Optimizer to get IR
subprocess.run([
sys.executable,
'-m',
'mo',
'--saved_model_dir=model',
'--input_shape',
','.join(input_shapes),
'--input',
','.join(self.input_names),
'--extension',
os.path.join(os.path.dirname(__file__), 'utils', 'openvino_ext'),
],
check=True)
self.exec_net = self.ie.load_network('saved_model.xml', self.device)
try:
os.remove('saved_model.xml')
os.remove('saved_model.bin')
os.rmdir('model')
except Exception:
pass
def __call__(self, inputs):
if self.exec_net is None:
self._read_tf_model(inputs)
tensors = {}
for idx, name in zip(self.input_ids, self.input_names):
tensors[name] = inputs[idx]
output = self.exec_net.infer(tensors)
output = next(iter(output.values()))
return output
def to(self, device):
self.device = device.upper()
|
{"hexsha": "61834cc625085bc2cbf0cdcc9c79b021d1332c71", "size": 2255, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml3d/tf/models/openvino_model.py", "max_stars_repo_name": "krshrimali/Open3D-ML", "max_stars_repo_head_hexsha": "e6352ee84d38a4b90c71dd7f376f5570fe849537", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-30T05:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:15:06.000Z", "max_issues_repo_path": "ml3d/tf/models/openvino_model.py", "max_issues_repo_name": "krshrimali/Open3D-ML", "max_issues_repo_head_hexsha": "e6352ee84d38a4b90c71dd7f376f5570fe849537", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml3d/tf/models/openvino_model.py", "max_forks_repo_name": "krshrimali/Open3D-ML", "max_forks_repo_head_hexsha": "e6352ee84d38a4b90c71dd7f376f5570fe849537", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1686746988, "max_line_length": 79, "alphanum_fraction": 0.5627494457, "include": true, "reason": "import numpy", "num_tokens": 478}
|
"""
This module acts as an eye. An input processing module responsible for processing visual raw data and activating the
ganglion cells that act as the gateway to the visual cortical pathways.
"""
import os
import struct
import numpy as np
from math import floor
from datetime import datetime
from inf import runtime_data, settings
from inf.db_handler import MongoManagement
from inf.disk_ops import save_processed_mnist_to_disk
from evo.neuron import neuron_finder
from evo.neuroembryogenesis import cortical_sub_group_members
def polarize_img(img):
polarized_image = mnist.read_nth_mnist_digit(seq=seq, digit=num, type=mnist_type)
# polarized_image = mnist.mnist_img_fetcher_mongo(num=num,
# kernel_size=kernel_size,
# seq=seq,
# mnist_type=mnist_type,
# random_num=random_num)
if runtime_data.parameters['Logs']['print_polarized_img']:
image = polarized_image['original_image']
npimage = np.array(image)
for _ in npimage:
print(_)
return polarized_image
def image_to_neuron_list(image, polarize=False):
"""
Plays the role of Ganglionic Layer in retina.
Responsible for converting visual stimuli to neuronal activity so it can be passed along the cortical pathways
Input: Standard Image Data
Output: List of neurons from various Thalamic Visual layers (LGN) that are activated
Output format:
neuron_list =
{
"cortical_area_1" : {list of activated neurons},
"cortical_area_2" : {list of activated neurons},
"cortical_area_3" : {list of activated neurons}
}
"""
neuron_list = {}
vision_group = cortical_sub_group_members('t_vision')
# Polarize image as an option
if polarize:
polarized_image = polarize_img(image)
# Convert image data to list of neurons
for cortical_area in vision_group:
neuron_list[cortical_area] = set()
cortical_direction_sensitivity = runtime_data.genome['blueprint'][cortical_area]['direction_sensitivity']
if polarize:
for key in polarized_image:
if key == cortical_direction_sensitivity:
try:
# print(np.array2string(np.array(polarized_image[cortical_direction_sensitivity]), max_line_width=np.inf))
# ipu_vision_array = \
# IPU_vision.Image.convert_direction_matrix_to_coordinates(
# polarized_image[cortical_direction_sensitivity])
ipu_vision_array = polarized_image[cortical_direction_sensitivity]
neuron_id_list = Image.convert_image_locations_to_neuron_ids(ipu_vision_array, cortical_area)
neuron_list[cortical_area].update(set(neuron_id_list))
if runtime_data.parameters['Logs']['print_activation_counters']:
print("\n Bipolar cell activation count in %s is %i" % (cortical_area, len(ipu_vision_array)))
print("Neuron id count activated in layer %s is %i\n\n" %
(cortical_area, len(neuron_id_list)))
except:
print("Error on direction selectivity")
else:
neuron_id_list = Image.convert_image_locations_to_neuron_ids(image, cortical_area)
neuron_list[cortical_area].update(set(neuron_id_list))
return neuron_list
def print_polarized_image(polarized_image, cortical_area):
if runtime_data.parameters['Logs']['print_polarized_img']:
print("\nPrinting polarized image for ", cortical_area)
cortical_direction_sensitivity = runtime_data.genome['blueprint'][cortical_area]['direction_sensitivity']
for row in polarized_image[cortical_direction_sensitivity]:
print(" ***")
for item in row:
print(settings.Bcolors.YELLOW + item + settings.Bcolors.ENDC, end='')
if item == '':
print(settings.Bcolors.RED + '.' + settings.Bcolors.ENDC, end='')
class Filter:
@staticmethod
def brightness(image):
new_image = np.zeros(image.shape)
for x in range(image.shape[0]):
for y in range(image.shape[1]):
if image[x, y] >= runtime_data.genome["image_color_intensity_tolerance"]:
new_image[x, y] = image[x, y]
else:
new_image[x, y] = 1
return new_image
@staticmethod
def contrast(image, kernel_size):
"""This function simulates the effect of Amacrine and Horizontal cells within human Retina"""
if divmod(kernel_size, 2)[1] == 0:
print("Error: Kernel size should only be Odd number!")
return
row_index = 0
col_index = 0
new_image = [[] for x in range(np.shape(image)[1])]
for row in image:
for row_item in row:
kernel_values = Image.image_read_by_block(image, kernel_size, [row_index, col_index])
cell_value = Kernel.kernel_contrast(kernel_values=kernel_values, kernel_size=kernel_size)
new_image[row_index].append(cell_value)
col_index += 1
col_index = 0
row_index += 1
new_image = np.asarray(new_image, dtype=np.int)
# print("Pre-normalized image:\n", new_image)
# Normalize pixel values
image_max_value = np.amax(new_image)
# print("Max value:", image_max_value)
row_index = 0
col_index = 0
normalized_image = [[] for x in range(np.shape(new_image)[1])]
for row in new_image:
for row_item in row:
# 255 is the max intensity value that each image cell can be
normalized_value = floor(row_item * 255 / image_max_value)
normalized_image[row_index].append(normalized_value)
col_index += 1
col_index = 0
row_index += 1
# print("NNN\n", normalized_image)
# normalized_image = np.asarray(normalized_image, dtype=np.int)
return normalized_image
@staticmethod
def direction(kernel_values, kernel_size, direction_key):
"""Function to apply a particular filter to a kernel region of any size"""
# end_result = {}
result = np.zeros((kernel_size, kernel_size))
filter_value = runtime_data.genome["IPU_vision_filters"][str(kernel_size)][direction_key]
for i in range(0, kernel_size):
for ii in range(0, kernel_size):
result[i][ii] = kernel_values[i][ii] * filter_value[i][ii]
ii += 1
i += 1
# end_result[direction_key] = result
return result
@staticmethod
def monochrome(image):
"""This function converts a gray-scale image to monochrome by setting all the pixels below a threshold to
zero and above that threshold to 255."""
row_index = 0
col_index = 0
new_image = [[] for x in range(np.shape(image)[1])]
for row in image:
for row_item in row:
if row_item < runtime_data.parameters["InitData"]["image_monochromization_threshold"]:
new_image[row_index].append(0)
else:
new_image[row_index].append(255)
col_index += 1
col_index = 0
row_index += 1
new_image = np.asarray(new_image, dtype=np.int)
return new_image
class Kernel:
@staticmethod
def kernel_sizer(kernel_values):
np.tmp = kernel_values
kernel_size = np.shape(np.tmp)
kernel_size = kernel_size[0]
if divmod(kernel_size, 2)[1] == 0:
print("Error: Kernel size should only be Odd number!")
return
return kernel_size
def kernel_direction(self, kernel_values):
"""
Apply all filters from the IPU_vision_filters to the kernel and evaluate the best match
Output is the Type of directional cell which will be activated
:param kernel_size:
:param kernel_values:
:return:
The following conditions will estimate the line orientation angle into 4 standard options as following:
1: / 2: \ 3: - 4: | 0 : none
Each if condition will perform a simple statistical analysis on the concentration of the pixels
"""
# todo: Important >>> Something is wrong with this function returning incorrect values as direction label changes
end_result = {}
kernel_size = self.kernel_sizer(kernel_values)
# print("Kernel size is: ", kernel_size)
for filter_entry in runtime_data.genome["IPU_vision_filters"][str(kernel_size)]:
end_result[filter_entry] = Filter.direction(kernel_values, kernel_size, filter_entry)
tmpArray = []
# print('this is tmp before all appends', tmpArray)
for entry in end_result:
# print(entry, "\n", end_result[entry], "\n\n\n")
sumation = np.sum(end_result[entry])
# print("Appending: %s Sum: %d \n End_result: \n %s" % (entry, summation,end_result[entry]))
# tmp = np.append(tmp, [entry, np.sum(end_result[entry])], axis=0)
tmpArray.append([entry, np.sum(end_result[entry])])
# print('***', tmpArray)
# print("This is the end result: \n %s" % end_result)
# print('tmp after appends %s' % tmpArray)
maxValue = max(list(zip(*tmpArray))[1])
# print("MaxValue: ", maxValue)
maxValueIndex = list(zip(*tmpArray))[1].index(maxValue)
direction = tmpArray[maxValueIndex][0]
# direction = direction.replace('\\', '\')
# print('max value is %s' % maxValue)
# print('max index is %s' % maxValueIndex)
# print('direction is %s' % direction)
tempSum = 0
for entry in tmpArray:
tempSum += abs(entry[1])
if tempSum == 0:
return "^"
return direction
@staticmethod
def kernel_contrast(kernel_values, kernel_size):
filtered_kernel = Filter.direction(kernel_values, kernel_size, 'o')
# contrast_value = np.sum(kernel_values * filtered_kernel)
contrast_value = np.sum(filtered_kernel)
if contrast_value < 0:
contrast_value = 0
return contrast_value
# todo: This function is super slow............
def create_direction_matrix(self, image, kernel_size, direction_sensitivity=''):
"""
Generates a Matrix where each element outlines the direction detected by the Kernel filters against each
corresponding pixel in the image.
"""
# print(">>> >>>", kernel_size, type(kernel_size))
if divmod(kernel_size, 2)[1] == 0:
print("Error: Kernel size should only be Odd number!")
return
row_index = 0
col_index = 0
direction_matrix = [[] for x in range(np.shape(image)[1])]
for row in image:
for row_item in row:
direction = self.kernel_direction(Image.image_read_by_block(image, kernel_size, [row_index, col_index]))
if direction == direction_sensitivity or direction_sensitivity == '':
direction_matrix[row_index].append(direction)
else:
direction_matrix[row_index].append('')
col_index += 1
col_index = 0
row_index += 1
return direction_matrix
def create_direction_matrix2(self, image, kernel_size):
"""
Generates a Matrix where each element outlines the direction detected by the Kernel filters against each
corresponding pixel in the image.
"""
if divmod(kernel_size, 2)[1] == 0:
print("Error: Kernel size should only be Odd number!")
return
direction_sensitivity_options = runtime_data.genome["IPU_vision_filters"][str(kernel_size)]
direction_matrix = {}
row_index = 0
col_index = 0
for direction_sensitivity in direction_sensitivity_options:
direction_matrix[direction_sensitivity] = []
for row in image:
for row_item in row:
image_block = Image.image_read_by_block(image, kernel_size, [row_index, col_index])
actual_direction = self.kernel_direction(image_block)
if actual_direction in direction_sensitivity_options:
direction_matrix[actual_direction].append([row_index, col_index])
col_index += 1
col_index = 0
row_index += 1
return direction_matrix
@staticmethod
def orientation_matrix(raw_image, orientation_key, kernel_size):
"""
Function to produce an orientation matrix based on the raw image data
"""
return
class Image:
@staticmethod
def resize_image(image):
img = Image.image_read_by_block(image=image)
new_image_dimension = runtime_data.parameters["InitData"]["image_magnification_factor"]
new_size = (new_image_dimension, new_image_dimension)
image = img.Image.resize_image(new_size)
return image
@staticmethod
def convert_image_to_coordinates(image): # Image is currently assumed to be a 28 x 28 numpy array
"""
Function responsible for reading an image and converting the pixel values to coordinates
"""
# Note: currently set to function based on Gray scale image
genome = runtime_data.genome
image_locations = []
for x in range(image.shape[0]):
for y in range(image.shape[1]):
if image[x, y] >= genome["image_color_intensity_tolerance"]:
image_locations.append([x, y, 0])
# Image location will be fed to another function to identify the Id of neurons to be activated
return image_locations
@staticmethod
def convert_direction_matrix_to_coordinates(image):
# print("Polarized image type = ", type(image))
image_locations = []
x = 0
y = 0
for row in image:
for column in row:
if image[x][y] != '':
image_locations.append([x, y, 0])
y += 1
y = 0
x += 1
return image_locations
# todo: Cythonize this
@staticmethod
def convert_image_locations_to_neuron_ids_old(image_locations, cortical_area):
"""
Queries the connectome for each location and provides the list of Neuron Ids matching the location
:param image_locations:
:return:
"""
genome = runtime_data.genome
neuron_id_list = []
for x in range(len(image_locations)):
# call the function to find neuron candidates for a given location
tmp = neuron_finder(cortical_area, image_locations[x], genome["location_tolerance"])
for item in tmp:
if (item is not None) and (neuron_id_list.count(item) == 0):
neuron_id_list.append(item)
return neuron_id_list
@staticmethod
def convert_image_locations_to_neuron_ids(image_locations, cortical_area):
"""
Queries the connectome for each location and provides the list of Neuron Ids matching the location
:param image_locations:
:return:
"""
# print("$$$$$ $ $ $ $ $ $ Image locations:", image_locations)
neuron_id_list = []
for x in range(len(image_locations)):
# print(">> Image location item:", x)
block_reference = str(image_locations[x][0]) + '-' + \
str(image_locations[x][1]) + '-' + \
str(0)
if block_reference in runtime_data.block_dic[cortical_area]:
neuron_list = runtime_data.block_dic[cortical_area][block_reference]
# print(">>..>> Neuron list:", neuron_list)
# print("XXXXXXXXXX XXXXXXXXX XXXXXXXX", cortical_area, block_reference, len(neuron_list))
for item in neuron_list:
if (item is not None) and (neuron_id_list.count(item) == 0):
neuron_id_list.append(item)
# print("+++++++++\n\n\n-----------\n\n\n++++++++\n\n\nYYYYYYYY YYYYYYYY YYYYYYY", cortical_area, neuron_id_list)
return neuron_id_list
@staticmethod
def image_read_by_block(image, kernel_size, seed_coordinates):
x = seed_coordinates[0]
y = seed_coordinates[1]
if divmod(kernel_size, 2)[1] == 0:
print("Error: Kernel size should only be Odd number!")
return
kernel_values = np.zeros((kernel_size, kernel_size))
scan_length = divmod(kernel_size, 2)[0]
for a in range(0, kernel_size):
for b in range(0, kernel_size):
if ((x-scan_length+a >= 0) and (y-scan_length+b >= 0) and (x-scan_length+a < np.shape(image)[0])
and (y-scan_length+b < np.shape(image)[1])):
kernel_values[a, b] = image[x-scan_length+a, y-scan_length+b]
return kernel_values
# todo: Need to add a method to combine multiple IPU layer data into a single one
# -Think how to build a direction agnostic representation of an object
@staticmethod
def image_processing():
"""
Function to read an image from a file and have it converted to it's fundamental components
"""
return
@staticmethod
def image_orientation_detector():
"""
Performs higher level analysis to detect the direction of an image
"""
# todo: need to figure which processing layer this belongs to. It might need to go thru entire stack
return
@staticmethod
def direction_stats(image_block):
"""
Reads direction Kernel data and returns statistics on the percentage of each direction
:param kernel:
:return:
"""
# direction_matrix = (image, kernel_size))
# print(image)
direction_matrix = ''
for row in image_block:
for item in row:
direction_matrix = direction_matrix + str(item)
# generate a list of all unique Characters present in the image block
unique_chars = []
for item in direction_matrix:
if unique_chars.count(item) == 0 and item != ' ':
unique_chars.append(item)
# print('list of unique chars = %s' % unique_chars)
# Count number of occurrences of each unique character
counts = []
for item in unique_chars:
counts.append([item, direction_matrix.count(item)])
# Calculate the percentage of usage of each word
stats = []
count_total = direction_matrix.__len__() - direction_matrix.count(' ')
for key in range(0, counts.__len__()):
stats.append([counts[key][0], str(counts[key][1] * 100 / float(count_total)) + ' %'])
return stats
|
{"hexsha": "0f13531f69a0d7fcdc4cb5f71578dfac9cf0e852", "size": 19487, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/ipu/processor/image.py", "max_stars_repo_name": "feagi/feagi-core", "max_stars_repo_head_hexsha": "d83c51480fcbe153fa14b2360b4d61f6ae4e2811", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-02-18T16:03:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T19:53:06.000Z", "max_issues_repo_path": "src/ipu/processor/image.py", "max_issues_repo_name": "feagi/feagi-core", "max_issues_repo_head_hexsha": "d83c51480fcbe153fa14b2360b4d61f6ae4e2811", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-12-17T04:59:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T20:58:46.000Z", "max_forks_repo_path": "src/ipu/processor/image.py", "max_forks_repo_name": "feagi/feagi-core", "max_forks_repo_head_hexsha": "d83c51480fcbe153fa14b2360b4d61f6ae4e2811", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-12-16T06:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-18T12:01:31.000Z", "avg_line_length": 41.6388888889, "max_line_length": 130, "alphanum_fraction": 0.6058911069, "include": true, "reason": "import numpy", "num_tokens": 4127}
|
!-----------------------------------------------------------------------
subroutine tridiagonal(N,au,bu,cu,du,fi,lt,value)
!
! !DESCRIPTION:
! A linear equation with tridiagonal matrix structure is solved here. The main
! diagonal is stored on {\tt bu}, the upper diagonal on {\tt au}, and the
! lower diagonal on {\tt cu}, the right hand side is stored on {\tt du}.
! The method used here is the simplified Gauss elimination, also called
! \emph{Thomas algorithm}.
!
! !USES:
IMPLICIT NONE
!
! !INPUT PARAMETERS:
integer, intent(in) :: N,fi,lt
real(8), dimension(N), intent(in) :: au, bu, cu, du
!
! !OUTPUT PARAMETERS:
real(8), intent(out) :: value(N)
!
!EOP
!
! !LOCAL VARIABLES:
integer :: i
real(8), dimension(N) :: ru, qu
!
!-----------------------------------------------------------------------
!BOC
ru(lt)=au(lt)/bu(lt)
qu(lt)=du(lt)/bu(lt)
do i=lt-1,fi+1,-1
ru(i)=au(i)/(bu(i)-cu(i)*ru(i+1))
qu(i)=(du(i)-cu(i)*qu(i+1))/(bu(i)-cu(i)*ru(i+1))
end do
qu(fi)=(du(fi)-cu(fi)*qu(fi+1))/(bu(fi)-cu(fi)*ru(fi+1))
value(fi)=qu(fi)
! write(6,*) 'fi = ',fi
! write(6,*) 'value(fi) = ',value(fi)
do i=fi+1,lt
value(i)=qu(i)-ru(i)*value(i-1)
end do
! write(6,*) 'value(lt) = ',value(lt)
return
end subroutine tridiagonal
|
{"hexsha": "de8ae4c2c1589fdad8410b22936dc13d73bf3299", "size": 1371, "ext": "f90", "lang": "FORTRAN", "max_stars_repo_path": "src/tridiagonal.f90", "max_stars_repo_name": "BingzhangChen/HOT", "max_stars_repo_head_hexsha": "c166ac038cd67a0e4dd5c8512bf5d678eb07b6cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tridiagonal.f90", "max_issues_repo_name": "BingzhangChen/HOT", "max_issues_repo_head_hexsha": "c166ac038cd67a0e4dd5c8512bf5d678eb07b6cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tridiagonal.f90", "max_forks_repo_name": "BingzhangChen/HOT", "max_forks_repo_head_hexsha": "c166ac038cd67a0e4dd5c8512bf5d678eb07b6cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8679245283, "max_line_length": 78, "alphanum_fraction": 0.5003646973, "num_tokens": 421}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.