This repository has been archived by the owner on Sep 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
Report.py
2020 lines (1686 loc) · 112 KB
/
Report.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
:mod:`EdgarRenderer.Report`
~~~~~~~~~~~~~~~~~~~
Edgar(tm) Renderer was created by staff of the U.S. Securities and Exchange Commission.
Data and content created by government employees within the scope of their employment
are not subject to domestic copyright protection. 17 U.S.C. 105.
"""
# must prevent EDGAR from writing into system directories, use environment variable:
# MPLCONFIGDIR= ... arelle's xdgConfigHome value
from matplotlib import use as matplotlib_use
# must initialize matplotlib to not use tkinter or $DISPLAY (before other imports)
matplotlib_use("Agg")
import os, datetime, decimal, io, time
import regex as re
from collections import defaultdict
from lxml.etree import Element, SubElement, XSLT, tostring as treeToString, fromstring
import arelle.XbrlConst
from . import Utils
Filing = None
from arelle.XbrlConst import qnIXbrl11Hidden
xlinkRole = '{' + arelle.XbrlConst.xlink + '}role' # constant belongs in XbrlConsts`headingList
class Report(object):
def __init__(self, filing, cube, embedding):
global Filing
if Filing is None:
from . import Filing
self.filing = filing
self.controller = filing.controller
filing.numReports += 1
self.cube = cube
self.embedding = embedding
self.promotedAxes = []
self.rowList = []
self.colList = []
self.numColumns = 0
self.numVisibleColumns = 0
self.numRows = 0
self.numVisibleRows = 0
self.footnoteTextList = []
self.RoundingOption = None
self.rootETree = Element('InstanceReport', nsmap={'xsi' : 'http://www.w3.org/2001/XMLSchema-instance'})
self.columnsETree = SubElement(self.rootETree, 'Columns') # children added later
self.rowsETree = SubElement(self.rootETree, 'Rows') # children added later
self.shortName = self.cube.shortName # each Report can edit its own shortName
self.factToColDefaultDict = defaultdict(list)
self.hasEmbeddedReports = False
self.logList = []
self.scalingFactorsQuantaSymbolTupleDict = {}
self.repressPeriodHeadings = embedding.suppressHeadingDates # Usually false, additional analysis can set it true.
def generateCellVector(self, rowOrColStr, index):
if rowOrColStr == 'col':
return (self.colList[index], [row.cellList[index] for row in self.rowList if not row.isHidden])
else:
row = self.rowList[index]
return (row, [cell for i, cell in enumerate(row.cellList) if not self.colList[i].isHidden])
def generateRowsOrCols(self, rowOrColStr, sortedFactAxisMemberGroupList):
previousRowOrCol = None
for factAxisMemberGroup in sortedFactAxisMemberGroupList:
# if primary on columns, then we have multiple primary elements per Row.
# in that case, coordinateListWithoutPrimary == coordinateList so coordinateList is right
# if primary on rows then one primary Element per Row, so we want coordinateList again
# because same primary elements have same coordinates.
coordinateList = []
coordinateListWithoutPrimary = []
coordinateListWithoutUnit = []
coordinateListWithoutUnitPeriod = []
coordinateListWithoutUnitPeriodPrimary = []
coordinateListWithoutUnitPrimary = []
#groupedCoordinateList = []
fact = factAxisMemberGroup.fact
preferredLabel = factAxisMemberGroup.preferredLabel
startEndContext = None
if rowOrColStr == 'col':
elementQnameMemberForColHidingSet = set()
for factAxisMember in factAxisMemberGroup.factAxisMemberRowList + factAxisMemberGroup.factAxisMemberColList:
if factAxisMember.pseudoAxisName not in {'period', 'unit', 'primary'} and factAxisMember.member is not None:
elementQnameMemberForColHidingSet.add((fact.qname, factAxisMember.member))
if rowOrColStr == 'row':
factAxisMemberList = factAxisMemberGroup.factAxisMemberRowList
else:
factAxisMemberList = factAxisMemberGroup.factAxisMemberColList
for factAxisMember in factAxisMemberList:
pseudoAxisName = factAxisMember.pseudoAxisName
axisMemberPositionTuple = factAxisMember.axisMemberPositionTuple
#if rowOrColStr == 'row' and pseudoAxisName in self.embedding.groupedAxisQnameSet:
# groupedCoordinateList += [axisMemberPositionTuple]
if pseudoAxisName == 'period':
startEndContext = factAxisMember.member
coordinateList += [axisMemberPositionTuple]
if pseudoAxisName != 'primary':
coordinateListWithoutPrimary += [axisMemberPositionTuple]
if pseudoAxisName != 'unit':
coordinateListWithoutUnit += [axisMemberPositionTuple]
if pseudoAxisName != 'period':
coordinateListWithoutUnitPeriod += [axisMemberPositionTuple]
if pseudoAxisName != 'primary':
coordinateListWithoutUnitPeriodPrimary += [axisMemberPositionTuple]
if pseudoAxisName != 'primary':
coordinateListWithoutUnitPrimary += [axisMemberPositionTuple]
# if isElements, every single fact should have it's own row and altogether, there should be exactly one column.
# it looks like 3 columns, but really the style sheet makes those columns.
if previousRowOrCol is None or previousRowOrCol.coordinateList != coordinateList or self.cube.isElements:
if rowOrColStr == 'row':
isStart = Utils.isPeriodStartLabel(preferredLabel)
IsCalendarTitle = self.cube.isStatementOfEquity and (isStart or Utils.isPeriodEndLabel(preferredLabel))
# this is goofy, in handlePeriodStartEndLabel() we turn instant facts into durations
# for the purposes of layout, but now, we artificially make the rows instants again.
if IsCalendarTitle and startEndContext is not None:
# we kill the startTime, which makes it an instant
if startEndContext.startTime is not None and isStart:
startEndTuple = (None, startEndContext.startTime)
else:
startEndTuple = (None, startEndContext.endTime)
try: # if startEndContext exists, find it
startEndContext = self.filing.startEndContextDict[startEndTuple]
except KeyError: # if not, create one and add it to respective data structures
startEndContext = Filing.StartEndContext(fact.context, startEndTuple)
self.filing.startEndContextDict[startEndTuple] = startEndContext
self.cube.timeAxis.add(startEndContext)
rowOrCol = Row(self.filing, self, startEndContext=startEndContext, factAxisMemberGroup=factAxisMemberGroup,
coordinateList=coordinateList,
coordinateListWithoutPrimary=coordinateListWithoutPrimary,
coordinateListWithoutUnit=coordinateListWithoutUnit,
coordinateListWithoutUnitPeriod=coordinateListWithoutUnitPeriod,
coordinateListWithoutUnitPeriodPrimary=coordinateListWithoutUnitPeriodPrimary,
coordinateListWithoutUnitPrimary=coordinateListWithoutUnitPrimary,
IsCalendarTitle=IsCalendarTitle, elementQname=fact.qname)
#groupedCoordinateList=groupedCoordinateList, IsCalendarTitle=IsCalendarTitle, elementQname=fact.qname)
self.rowList += [rowOrCol]
elif not self.cube.isElements or len(self.colList) == 0:
rowOrCol = Column(self.filing, self, startEndContext, factAxisMemberGroup,
coordinateList, coordinateListWithoutUnit, coordinateListWithoutUnitPeriod)
self.colList += [rowOrCol]
previousRowOrCol = rowOrCol
# now assign fact to columns. possible to assign one fact to multiple columns because of periodStartLabel and periodEndLabel
if rowOrColStr == 'row':
for colNum in (self.factToColDefaultDict.get((fact, preferredLabel)) or []):
col = self.colList[colNum]
previousRowOrCol.cellList[colNum] = Cell(self.filing, previousRowOrCol, col, colNum, fact=fact, preferredLabel=preferredLabel)
if fact.unit is not None:
self.updateUnitTypeToFactSetDefaultDict(fact, col)
if fact.unit is not None:
self.updateUnitTypeToFactSetDefaultDict(fact, rowOrCol)
rowOrCol.factList += [fact]
else:
self.factToColDefaultDict[(fact, preferredLabel)].append(previousRowOrCol.index)
rowOrCol.factList += [fact]
rowOrCol.elementQnameMemberForColHidingSet.update(elementQnameMemberForColHidingSet)
# return generateRowOrCols
def decideWhetherToRepressPeriodHeadings(self):
# for risk return filings, if there is only one period (durations and instants ending at the same time are ok too) we don't
# need to print the period everywhere.
if self.embedding.rowPeriodPosition != -1:
self.decideWhetherToSuppressPeriod('row', self.rowList, self.embedding.rowPeriodPosition)
elif self.embedding.columnPeriodPosition != -1:
self.decideWhetherToSuppressPeriod('col', self.colList, self.embedding.columnPeriodPosition)
def decideWhetherToSuppressPeriod(self, rowOrColStr, rowOrColList, periodPosition):
# returns if more than one period, otherwise represses period headings. i use memberLabel, because it will treat an instant
# and duration ending at the same time as the instant as the same.
if rowOrColStr == 'row':
first = rowOrColList[0].factAxisMemberGroup.factAxisMemberRowList[periodPosition].memberLabel
for row in rowOrColList:
if first != row.factAxisMemberGroup.factAxisMemberRowList[periodPosition].memberLabel:
return # we're done, there are two periods
else:
first = rowOrColList[0].factAxisMemberGroup.factAxisMemberColList[periodPosition].memberLabel
for col in rowOrColList:
if first != col.factAxisMemberGroup.factAxisMemberColList[periodPosition].memberLabel:
return # we're done, there are two periods
self.repressPeriodHeadings = True # there's only one period, don't show it.
def proposeAxisPromotions(self, rowOrColStr, rowOrColList, pseudoAxisNameList):
# don't promote axes if there's only one row or col. true, some might be hidden, but we don't want to check
# that hard yet because in the future more rows and cols may be hidden, so this is quick and dirty. we'll check
#for real after all that is done.
if len(rowOrColList) == 1:
return
# loop through each axis and if len(memberSet) == 1 promote axis because all rows or cols have the same label,
# no use repeating it for every row or col. if memberSet bigger, don't promote.
for i, pseudoAxisName in enumerate(pseudoAxisNameList):
if pseudoAxisName == 'unit':
unitAndMaybeSymbolStr = self.proposeUnitAxisPromotion(rowOrColList)
if unitAndMaybeSymbolStr is not None:
self.promotedAxes += [('unit', rowOrColStr, unitAndMaybeSymbolStr)]
continue
if pseudoAxisName == 'primary' or (self.repressPeriodHeadings and pseudoAxisName == 'period'):
continue
memberLabel = None
startEndContextDuration = None
for rowOrCol in rowOrColList:
if rowOrColStr == 'row':
factAxisMember = rowOrCol.factAxisMemberGroup.factAxisMemberRowList[i]
else:
factAxisMember = rowOrCol.factAxisMemberGroup.factAxisMemberColList[i]
if memberLabel is None:
memberLabel = factAxisMember.memberLabel
#second case if factAxisMember.memberLabel was None
if memberLabel != factAxisMember.memberLabel or memberLabel == None or factAxisMember.memberIsDefault:
memberLabel = None
break # there's more than one different member so can't promote axis
if pseudoAxisName == 'period' and factAxisMember.member.periodTypeStr == 'duration':
if startEndContextDuration is None:
startEndContextDuration = factAxisMember.member
elif startEndContextDuration != factAxisMember.member:
memberLabel = None # there is more than one duration, don't promote
break
if memberLabel is not None:
# we do this because we want to promote the period if there's an instant and duration ending at the same time.
# for the sake of promotion, we consider these two one member, even though they are different. if we tack on the months
# before we get to this stage, these two will seem different, even though for our purposes, they are the same.
if startEndContextDuration is not None and startEndContextDuration.numMonths > 0:
memberLabel = '{!s} months ended {}'.format(startEndContextDuration.numMonths, memberLabel)
self.promotedAxes += [(pseudoAxisName, rowOrColStr, memberLabel)]
# this is complicated because we still might promote units even if there are multiple units. for instance, if there are
# USD, USD/Share and shares as the units, we still promote USD. same for any pair of two from those three. however, we won't promote
# if we have ounces and barrels of oil for instance, or USD, JPY/Share and Share.
def proposeUnitAxisPromotion(self, rowOrColList):
monetaryFact = perShareMonetaryFact = sharesFact = anotherKindOfFact = None
for rowOrCol in rowOrColList:
fact = rowOrCol.factAxisMemberGroup.fact
if fact.unit is not None:
if fact.concept.isMonetary:
if monetaryFact is not None and monetaryFact.unitID != fact.unitID:
return # can't have two different currencies
monetaryFact = fact
elif Utils.isFactTypeEqualToOrDerivedFrom(fact, Utils.isPerShareItemTypeQname):
if perShareMonetaryFact is not None and perShareMonetaryFact.unitID != fact.unitID:
return # can't have two different currencies / share
perShareMonetaryFact = fact
elif fact.concept.isShares:
if sharesFact is not None and sharesFact.unitID != fact.unitID:
return # can't have two different shares
sharesFact = fact
elif Utils.isRate(fact, self.filing):
continue # it's essentially a pure fact, so we don't need to worry about it.
else:
if anotherKindOfFact is not None and anotherKindOfFact.unitID != fact.unitID:
return # can't have two different types of units, like barrels and ounces
anotherKindOfFact = fact
# boolean arithmetic
numPossiblyCompatibleTypes = (perShareMonetaryFact is not None) + (monetaryFact is not None)
allTypes = numPossiblyCompatibleTypes + (sharesFact is not None) + (anotherKindOfFact is not None)
if numPossiblyCompatibleTypes > 0:
if numPossiblyCompatibleTypes == 2 and perShareMonetaryFact.unit.measures[0][0].localName != monetaryFact.unit.measures[0][0].localName:
return # this makes sure we don't have USD and JPY/share. makes sure both units have the same numerator.
elif sharesFact is None:
if allTypes > numPossiblyCompatibleTypes:
return # makes sure it doesn't have USD and Ounces, or USD, USD/Share and Ounces.
elif allTypes > numPossiblyCompatibleTypes + 1:
return # Makes sure we don't have USD, USD/Share, Shares and Ounces
elif allTypes > 1:
return # makes sure we don't have Ounces and Shares
if anotherKindOfFact is not None:
return Utils.getUnitAndSymbolStr(anotherKindOfFact)
elif monetaryFact is not None:
return Utils.getUnitAndSymbolStr(monetaryFact)
elif perShareMonetaryFact is not None:
return Utils.getUnitAndSymbolStr(perShareMonetaryFact)
elif sharesFact is not None:
return Utils.getUnitAndSymbolStr(sharesFact)
# now we know what rows and cols will be hidden, so we can now finalize the promotions.
def finalizeProposedPromotions(self):
if len(self.promotedAxes) == 0:
return
def dontPromoteUnlessMultipleNonHiddenRowsOrCols(rowOrColList, rowOrColStr):
# if there's only one non-hidden row or col at this point, don't promote anything for it.
if (rowOrColStr == 'row' and self.numVisibleRows == 1) or (rowOrColStr == 'col' and self.numVisibleColumns == 1):
self.promotedAxes = [axisTriple for axisTriple in self.promotedAxes if axisTriple[1] != rowOrColStr]
rowOrColStrs = [axisTriple[1] for axisTriple in self.promotedAxes]
if 'row' in rowOrColStrs:
dontPromoteUnlessMultipleNonHiddenRowsOrCols(self.rowList, 'row')
if 'col' in rowOrColStrs:
dontPromoteUnlessMultipleNonHiddenRowsOrCols(self.colList, 'col')
unitStrToAppendToEnd = None
for axis, ignore, s in self.promotedAxes:
if axis == 'unit':
unitStrToAppendToEnd = s
else:
self.shortName += self.filing.titleSeparatorStr + s
if unitStrToAppendToEnd is not None:
self.shortName += self.filing.titleSeparatorStr + unitStrToAppendToEnd
def mergeRowsOrColsIfUnitsCompatible(self, rowOrColStr, rowOrColList):
i = 0
while i < len(rowOrColList):
coordinateListWithoutUnitOfFirstRowOrCol = rowOrColList[i].coordinateListWithoutUnit
monetarySet = set()
perShareSet = set()
nonMonetarySet = set()
while i < len(rowOrColList) and rowOrColList[i].coordinateListWithoutUnit == coordinateListWithoutUnitOfFirstRowOrCol:
rowOrCol = rowOrColList[i]
# at this point, rows or cols only have one unit in them, so it's simple to break them up and combine them.
if 'monetaryDerivedType' in rowOrCol.unitTypeToFactSetDefaultDict:
monetarySet.add(rowOrCol) # we might add more to this set next, but we separate it for speed, because it's unlikely
elif 'perShareDerivedType' in rowOrCol.unitTypeToFactSetDefaultDict:
perShareSet.add(rowOrCol)
else:
nonMonetarySet.add(rowOrCol)
i += 1
# non-monetary rows or cols might overlap, in which case, call the whole thing off, don't merge this group.
# the other sets can't overlap.
if len(nonMonetarySet) > 1 and self.doVectorsOverlap(nonMonetarySet, rowOrColStr):
continue
# in these two cases below, we mangle these three sets, and if either of these two conditions are satisfied,
# in the below for loop, monetary might not be monetary anymore, and nonmonetary might not be nonmonetary either.
if len(monetarySet) == 0:
if len(perShareSet) == 0:
if len(nonMonetarySet) > 1:
# this can happen if adjacent columns are (say) strings and decimals
# they are still mergable, we just treat one of them as if it were the 'monetary'.
monetarySet.add(nonMonetarySet.pop())
else:
monetarySet = perShareSet.copy()
perShareSet.clear()
# see above comments, monetary and nonmonetary might not mean what they say, might have been mangled above.
for monetaryRowOrCol in monetarySet:
for perShareRowOrCol in perShareSet:
# if monetary, the numerator is the currency, if perShareDerivedType, numerator is also currency.
perShareNumerators = {fact.unit.measures[0][0].localName for fact in (perShareRowOrCol.unitTypeToFactSetDefaultDict.get('perShareDerivedType') or [])}
monetaryNumerators = {fact.unit.measures[0][0].localName for fact in (monetaryRowOrCol.unitTypeToFactSetDefaultDict.get('monetaryDerivedType') or [])}
if len(perShareNumerators.union(monetaryNumerators)) == 1:
self.deepCopyRowsOrCols(rowOrColStr, monetaryRowOrCol, perShareRowOrCol)
for nonMonetaryRowOrCol in nonMonetarySet:
self.deepCopyRowsOrCols(rowOrColStr, monetaryRowOrCol, nonMonetaryRowOrCol)
def mergeRowsOrColsInstantsIntoDurationsIfUnitsCompatible(self, rowOrColStr, rowOrColList):
# if units are on rows and we're merging columns, there's no need to consider them, and vice versa.
# also, note that there might not be any units.
if rowOrColStr == 'row':
unitsAxisOnRowsOrCols = self.embedding.rowUnitPosition != -1
else:
unitsAxisOnRowsOrCols = self.embedding.columnUnitPosition != -1
tempRowOrColList = sorted(rowOrColList, key = lambda thing : thing.coordinateListWithoutUnitPeriod)
while len(tempRowOrColList) > 0:
previousCoordinateListWithoutPeriodAndUnit = tempRowOrColList[0].coordinateListWithoutUnitPeriod
instantRowOrColList = []
durationRowOrColList = []
while len(tempRowOrColList) > 0 and previousCoordinateListWithoutPeriodAndUnit == tempRowOrColList[0].coordinateListWithoutUnitPeriod:
rowOrCol = tempRowOrColList.pop(0)
if not rowOrCol.isHidden and rowOrCol.startEndContext is not None:
if rowOrCol.startEndContext.periodTypeStr == 'instant':
instantRowOrColList += [rowOrCol]
else:
durationRowOrColList += [rowOrCol]
instantRowOrColList.sort (key = lambda thing : thing.startEndContext.endTime)
durationRowOrColList.sort(key = lambda thing : thing.startEndContext.endTime)
while len(instantRowOrColList) > 0 and len(durationRowOrColList) > 0:
instantRowOrCol = instantRowOrColList[0]
durationRowOrCol = durationRowOrColList[0]
# compare instants to durations. if not equal, throw one away and try again, else continue
if instantRowOrCol.startEndContext.endTime < durationRowOrCol.startEndContext.endTime:
del instantRowOrColList[0]
elif instantRowOrCol.startEndContext.endTime > durationRowOrCol.startEndContext.endTime:
del durationRowOrColList[0]
else:
# if we're doing the rows and units isn't on the rows (and vice versa), we don't check unit compatibility,
# otherwise we need the units to be compatible. Also make sure the vectors don't overlap.
if ((not unitsAxisOnRowsOrCols or self.areFactsCompatableByUnits(instantRowOrCol, durationRowOrCol)) and
not self.doVectorsOverlap([instantRowOrCol, durationRowOrCol], rowOrColStr)):
self.deepCopyRowsOrCols(rowOrColStr, durationRowOrCol, instantRowOrCol)
del durationRowOrColList[0]
def doVectorsOverlap(self, rowsOrCols, rowOrColStr):
# zip takes multiple lists and zips them together and gives you tuples. the star character basically takes a list or
# set of lists and makes each one an argument for zip(). The lists here are basically lists of true/false values,
# where true means that the cell is occupied and false means it's empty. then i do some boolean math and since True == 1,
# and false == 0, you can sum the tuple that zip provides and if the sum is greater than 1, you know that you that
# for some position the vectors overlap, so you can't combine them.
z = zip(*[[cell is not None for cell in self.generateCellVector(rowOrColStr, rowOrCol.index)[1]] for rowOrCol in rowsOrCols])
return any(sum(trueFalseTuple) > 1 for trueFalseTuple in z)
def areFactsCompatableByUnits(self, colOrRowToBeMerged, colOrRowToBeMergedInto):
colOrRowToBeMergedMonetaryUnitSet = {fact.unit for fact in (colOrRowToBeMerged.unitTypeToFactSetDefaultDict.get('monetaryDerivedType') or [])}
colOrRowToBeMergedIntoMonetaryUnitSet = {fact.unit for fact in (colOrRowToBeMergedInto.unitTypeToFactSetDefaultDict.get('monetaryDerivedType') or [])}
if len(colOrRowToBeMergedMonetaryUnitSet.union(colOrRowToBeMergedIntoMonetaryUnitSet)) > 1:
return False # there are two different monetary units here
# this makes sure we don't merge usd/share with jpy
# if monetary, the numerator is the currency, if perShareDerivedType, numerator is also currency.
colOrRowToBeMergedMonetaryPerShareNumeratorSet = {fact.unit.measures[0][0].localName for fact in (colOrRowToBeMerged.unitTypeToFactSetDefaultDict.get('perShareDerivedType') or [])}
colOrRowToBeMergedIntoMonetaryPerShareNumeratorSet = {unit.measures[0][0].localName for unit in colOrRowToBeMergedIntoMonetaryUnitSet}
unionSize = len(colOrRowToBeMergedMonetaryPerShareNumeratorSet.union(colOrRowToBeMergedIntoMonetaryPerShareNumeratorSet))
if unionSize > 1:
return False
return True
def deepCopyRowsOrCols(self, rowOrColStr, mergeIntoThisRowOrCol, mergeRowOrCol):
mergeIntoThisRowOrColCellVector = self.generateCellVector(rowOrColStr, mergeIntoThisRowOrCol.index)[1]
mergeRowOrColCellVector = self.generateCellVector(rowOrColStr, mergeRowOrCol.index)[1]
for i in range(len(mergeIntoThisRowOrColCellVector)):
mergeCell = mergeRowOrColCellVector[i]
if mergeCell is not None: # do a deep copy
fact = mergeCell.fact
preferredLabel = mergeCell.preferredLabel
if fact.unit is not None: # update unitTypeToFactSetDefaultDict with new cell
self.updateUnitTypeToFactSetDefaultDict(fact, mergeIntoThisRowOrCol)
if rowOrColStr == 'col':
row = self.rowList[i]
col = mergeIntoThisRowOrCol
mergeIntoThisCell = row.cellList[col.index] = Cell(self.filing, row, col, col.index, fact=fact, preferredLabel=preferredLabel)
else:
row = mergeIntoThisRowOrCol
col = self.colList[i]
mergeIntoThisCell = row.cellList[i] = Cell(self.filing, row, col, i, fact=fact, preferredLabel=preferredLabel)
mergeIntoThisCell.currencySymbol = mergeCell.currencySymbol
mergeIntoThisCell.currencyCode = mergeCell.currencyCode
mergeIntoThisCell.unitID = mergeCell.unitID
mergeIntoThisCell.showCurrencySymbol = mergeCell.showCurrencySymbol
mergeRowOrCol.hide()
mergeIntoThisRowOrCol.factList += mergeRowOrCol.factList
def hideRedundantColumns(self):
factSets = {}
for col in self.colList:
if not col.isHidden:
factSets[col] = set(col.factList) # fact objects are unique and not copied.
for col1,facts1 in factSets.items():
if not col1.isHidden:
for col2,facts2 in factSets.items():
if not col1 is col2 and not col2.isHidden:
if facts2.issubset(facts1):
col2.hide()
def updateUnitTypeToFactSetDefaultDict(self, fact, rowOrCol):
if fact.concept.isMonetary:
# we manufacture an item type because there are a bunch that are monetary. easier to check for one than a bunch each time.
typeName = 'monetaryDerivedType'
elif Utils.isFactTypeEqualToOrDerivedFrom(fact, Utils.isPerShareItemTypeQname):
typeName = 'perShareDerivedType'
else:
typeName = fact.concept.type.name
rowOrCol.unitTypeToFactSetDefaultDict[typeName].add(fact)
# determine scaling factors for a certain currency, like USD. scaling is done at intervals of three, -3, -6, -9, ... .
#, which means that it's done in thousands. a scaling value of 0 is not scaled.
def scaleUnitGlobally(self): # so far currencies and shares.
monetaryExampleFactSet = set()
monetaryPerShareExampleFactSet = set()
# first decide how much to scale each currency. we only care if the value is below -3, otherwise it's not scaled.
for unitID, factSet in self.embedding.unitsToScaleGloballySet.items():
maxSoFar = Utils.minNumber
symbol = None
exampleFact = None
for fact in factSet:
if fact.decimals and not fact.isNil:
if exampleFact is None:
exampleFact = fact
if symbol is None:
symbol = Utils.getSymbolStr(fact) or unitID
if fact.decimals.casefold() == 'inf' or maxSoFar > -3:
maxSoFar = 0
break # to be scaled, every fact must have a decimals value of -3 or less. inf inhibits scaling.
else:
maxSoFar = max(maxSoFar, int(fact.decimals))
if exampleFact is not None:
if exampleFact.concept.isMonetary:
monetaryExampleFactSet.add(exampleFact)
elif Utils.isFactTypeEqualToOrDerivedFrom(exampleFact, Utils.isPerShareItemTypeQname):
monetaryPerShareExampleFactSet.add(exampleFact) # Treat it as a monetary.
if maxSoFar <= -3:
roundedMax = round(maxSoFar / 3) * 3
self.scalingFactorsQuantaSymbolTupleDict[unitID] = (roundedMax, pow(2,(roundedMax - maxSoFar)), symbol)
if len(self.scalingFactorsQuantaSymbolTupleDict) == 0:
return # nothing to scale, we're done.
# it could be confusing if a report has $ and $/share types, and the $ is scaled, but $/share isn't. here we check if it has
# both, and if the $ is scaled, and the $/share is not, and then we add the $/share into the scaling dict, with no scaling
# so it will print out something less confusing like $ in Millions, $/share in Units.
if self.cube.cubeType != 'statement':
for moneyFact in monetaryExampleFactSet:
matchingFact = None
for moneyPerShareFact in monetaryPerShareExampleFactSet:
if moneyFact.unit.measures[0][0].localName == moneyPerShareFact.unit.measures[0][0].localName:
matchingFact = moneyPerShareFact
break
if matchingFact is not None and matchingFact.unitID not in self.scalingFactorsQuantaSymbolTupleDict:
self.scalingFactorsQuantaSymbolTupleDict[matchingFact.unitID] = (0,
0,
Utils.getSymbolStr(moneyPerShareFact) or moneyPerShareFact.unitID)
# now if a cell is scaled, change its cell.scalingFactor
for row in self.rowList:
if not row.isHidden:
for cell in row.cellList:
if cell is not None and not cell.column.isHidden and not cell.fact.isNil:
try:
cell.scalingFactor, cell.quantum, ignore = self.scalingFactorsQuantaSymbolTupleDict[cell.fact.unitID]
except KeyError:
pass
scalingFactorHeading = ''
scalingWordDict = {0:'Units', -3:'Thousands', -6:'Millions', -9:'Billions', -12:'Trillions', -15:'Quadrillions', -18:'Quintillions'}
# note: we just need to sort by scaling factor, but we additionally sort by unit because we don't want the user
# to render a filing twice and have each run look different. we want the orderings to be the same every time.
for scalingFactor, ignore, unitSymbol in reversed(sorted(self.scalingFactorsQuantaSymbolTupleDict.values(), key = lambda thing : (thing[0], thing[2]))):
try:
scalingWord = scalingWordDict[scalingFactor]
except KeyError:
scalingWord = 'scaling factor is ' + str(scalingFactor)
scalingFactorHeading += ' {} in {},'.format(unitSymbol, scalingWord)
# removes the last comma
if scalingFactorHeading != '':
self.RoundingOption = scalingFactorHeading[:-1]
def handleFootnotes(self):
# here we look up each fact and dynamically build footnoteDict as we go
footnoteDict = {}
for row in self.rowList:
if not row.isHidden and not set(row.factList).isdisjoint(self.filing.factFootnoteDict):
for cell in row.cellList:
if cell is not None and not cell.column.isHidden:
#factFootnoteDict is a defaultdict, so returns [] not keyError
# we need to sort it, otherwise the ordering will change each time we run and filers will wonder why their footnotes are changing
footnoteListForThisCell = sorted((self.filing.factFootnoteDict.get(cell.fact) or []), key=lambda thing : thing[1])
for footnoteResource, footnoteText in footnoteListForThisCell:
try:
# if no exception, we have already added this footnote to footnoteDict, so we go and get it's index.
cell.footnoteNumberSet.add(footnoteDict[footnoteResource])
except KeyError:
# first time seeing this footnote, add it to footnoteDict
footnoteIndex = len(footnoteDict) + 1 # because footnote numbering starts at 1 not 0
footnoteDict[footnoteResource] = footnoteIndex
cell.footnoteNumberSet.add(footnoteIndex)
self.footnoteTextList += [footnoteText]
def setAndMergeFootnoteRowsAndColumns(self, rowOrColStr, rowOrColList):
# if we're looking at rows and there is only one col, it doesn't make sense to promote footnotes to the rows,
# only maybe the columns.
if (rowOrColStr == 'row' and self.numVisibleColumns == 1) or (rowOrColStr == 'col' and self.numVisibleRows == 1):
return
for i, rowOrCol in enumerate(rowOrColList):
if not rowOrCol.isHidden:
cellVector = self.generateCellVector(rowOrColStr, i)[1]
listOfFootnoteNumberSetsForNonEmptyCells = [cell.footnoteNumberSet for cell in cellVector if cell is not None]
# intersection below can take many arguments, the * below spreads out the list into multiple arguments
try:
rowOrColSet = set.intersection(*listOfFootnoteNumberSetsForNonEmptyCells)
except TypeError:
rowOrColSet = set()
if len(rowOrColSet) > 0:
rowOrCol.footnoteNumberSet = rowOrColSet # set attribute of row or col
# go back through these sets and remove footnotes that have been promoted to rows or columns
for footnoteNumberSet in listOfFootnoteNumberSetsForNonEmptyCells:
footnoteNumberSet -= rowOrColSet
def writeFootnoteIndexerEtree(self, footnoteNumberSet, etreeNode):
if len(footnoteNumberSet) > 0:
numberListForDisplayStr = ''
for number in sorted(footnoteNumberSet):
numberListForDisplayStr += '[{!s}],'.format(number)
numberListForDisplayStr = numberListForDisplayStr[:-1] # "[:-1]" cuts off trailing comma from string
SubElement(etreeNode, 'FootnoteIndexer').text = numberListForDisplayStr
else:
SubElement(etreeNode, 'FootnoteIndexer') # the stylesheet needs this, even if empty?
def removeVerticalInteriorSymbols(self):
for i, col in enumerate(self.colList):
if len(col.unitTypeToFactSetDefaultDict) > 0 and not col.isHidden:
previousCellCode = None
previousCell = None
for row in self.rowList:
cell = row.cellList[i]
if cell is not None and not row.isHidden:
currentCellUnitID = cell.unitID
if previousCellCode == currentCellUnitID:
cell.showCurrencySymbol = False
else:
if previousCell is not None:
previousCell.showCurrencySymbol = previousCellCode is not None
cell.showCurrencySymbol = currentCellUnitID is not None
previousCellCode = currentCellUnitID
previousCell = cell
if previousCell is not None:
previousCell.showCurrencySymbol = previousCellCode is not None
def makeSegmentTitleRows(self):
counter = 0
prevRow = None
forbiddenAxisSet = {'primary', 'unit'}
coordinateList = 'coordinateListWithoutUnitPrimary'
if self.cube.forbidsDatesInSegmentTitleRows:
forbiddenAxisSet |= {'period'}
coordinateList = 'coordinateListWithoutUnitPeriodPrimary'
forbiddenAxisSet |= {axisTriple[0] for axisTriple in self.promotedAxes}
while counter < len(self.rowList):
row = self.rowList[counter]
if (not row.isHidden and
(prevRow == None or vars(row)[coordinateList] != vars(prevRow)[coordinateList])):
prevRow = self.rowList[counter]
# build heading list
headingList = []
axisInSegmentTitleHeaderBoolList = []
for factAxisMember in row.factAxisMemberGroup.factAxisMemberRowList:
if factAxisMember.pseudoAxisName not in forbiddenAxisSet and not factAxisMember.memberIsDefault:
headingList += [factAxisMember.memberLabel]
axisInSegmentTitleHeaderBoolList += [True]
else:
axisInSegmentTitleHeaderBoolList += [False]
# make new segment title row and insert into rowList
if headingList != []:
headerRow = Row(self.filing, self, index=counter, isSegmentTitle=True)
if self.cube.isUnlabeled:
# this is because the heading column on the left gets killed if the cube is "unlabeled" so we have to move the heading over
# into the first cell.
headerRow.cellList[0] = Cell(self.filing, headerRow, self.colList[0], 0, NonNumericText=self.filing.rowSeparatorStr.join(headingList))
# you'd think we didn't need to add heading list for isUnlabeled, since we're pushing the heading into the cell too,
# but unless it's in both the R-file row "Label" field, and the cell, the style sheet will hide the first row of each report,
# which it shouldn't. so, because it works, we do both.
headerRow.headingList = headingList
headerRow.axisInSegmentTitleHeaderBoolList = axisInSegmentTitleHeaderBoolList
self.rowList.insert(counter, headerRow)
counter += 1
counter += 1
def addAbstracts(self):
# here we sort the abstracts under primary and we get their orders along the primary pseudoaxis that
# we will compare with the other elements on the primary Axis.
sortedListOfAbstractQnamePositionTuples = sorted(self.cube.abstractDict.items(), key = lambda thing: thing[1])
sortedListOfAbstractFactsPosition = 0
counter = 0
while counter < len(self.rowList):
row = self.rowList[counter]
if row.isHidden:
pass
elif row.isSegmentTitle or row.IsCalendarTitle:
sortedListOfAbstractFactsPosition = 0
else:
factPrimaryAxisPosition = row.coordinateList[self.embedding.rowPrimaryPosition][1]
if (sortedListOfAbstractFactsPosition < len(sortedListOfAbstractQnamePositionTuples) and
factPrimaryAxisPosition > sortedListOfAbstractQnamePositionTuples[sortedListOfAbstractFactsPosition][1]):
# we don't want to print two adjacent abstract rows. so check to see if there are any adjacent and if so,
# then just print the last one.
while (sortedListOfAbstractFactsPosition < len(sortedListOfAbstractQnamePositionTuples) - 1 and
sortedListOfAbstractQnamePositionTuples[sortedListOfAbstractFactsPosition + 1][1] < factPrimaryAxisPosition):
sortedListOfAbstractFactsPosition += 1
# add a row
elementQname = sortedListOfAbstractQnamePositionTuples[sortedListOfAbstractFactsPosition][0]
if not( elementQname in self.filing.builtinLineItems):
abstractRow = Row(self.filing, self, index=counter, IsAbstractGroupTitle=True, elementQname=elementQname)
abstractRow.headingList = [self.cube.labelDict[elementQname]]
self.rowList.insert(counter, abstractRow)
counter += 1 # we add to the row counter twice, because we're adding a row
sortedListOfAbstractFactsPosition += 1
counter += 1
def generateRowAndOrColHeadingsForElements(self):
for row in self.rowList: # if isElements, we just need rows, don't need cols
if not (row.IsAbstractGroupTitle or row.isSegmentTitle):
for factAxisMember in row.factAxisMemberGroup.factAxisMemberRowList:
# since cube isElements, we know primary must be on the rows, we checked.
if factAxisMember.pseudoAxisName == 'primary':
row.headingList += [factAxisMember.memberLabel]
break
def generateRowAndOrColHeadingsGeneralCase(self):
# axes to not generate headings for, cheaper to build this set only once and pass it in.
promotedAxesSet = {axisTriple[0] for axisTriple in self.promotedAxes}
noHeadingsForTheseAxesSet = promotedAxesSet.union(self.embedding.noDisplayAxesSet) #.union(self.embedding.groupedAxisQnameSet)
if self.repressPeriodHeadings:
noHeadingsForTheseAxesSet.add('period')
# generate the column headings
for col in self.colList:
if not col.isHidden:
self.generateRowOrColHeading('col', col, col.factAxisMemberGroup.factAxisMemberColList, noHeadingsForTheseAxesSet, None)
# we keep track of the mostRecentSegmentTitleRow because we don't want to relist the same set of members in the rows beneath it,
# would be redundant. so we keep track of the most recent segment title row, and the members it contains, and don't reprint those
# members when we're generating row headers. since segment title rows are only on rows, this doesn't effect cols.
mostRecentSegmentTitleRow = None
rowUnitHeadingDefaultDict = defaultdict(list)
for row in self.rowList:
if not row.isHidden:
if row.isSegmentTitle:
mostRecentSegmentTitleRow = row
elif not row.IsAbstractGroupTitle and row.headingList == []:
self.generateRowOrColHeading('row', row, row.factAxisMemberGroup.factAxisMemberRowList, noHeadingsForTheseAxesSet, mostRecentSegmentTitleRow)
if self.embedding.columnUnitPosition != -1 and 'unit' not in promotedAxesSet and len(row.unitTypeToFactSetDefaultDict) == 1:
unitHeading = self.appendUnitsToRowsIfUnitsOnColsAndRowHasOnlyOneUnit(row)
if unitHeading is not None:
rowUnitHeadingDefaultDict[unitHeading].append(row)
# don't print the most popular unitHeading, only the rest. we do this to prevent clutter, it looks ugly.
# however, if the most popular is a tie, we print all the most popular. since we're not printing the most popular, if
# there's only 1, we just quit, only proceed if there are two or above.
if len(rowUnitHeadingDefaultDict) < 2:
return
def addToRows(listOfUnitRowSetTuples):
for unitHeading, rowSet in listOfUnitRowSetTuples:
for row in rowSet:
row.headingList += [unitHeading]
if self.embedding.suppressHeadingUnits:
return
sortedList = sorted(rowUnitHeadingDefaultDict.items(), key=lambda thing : len(thing[1])) # sort by number of rows per unit
addToRows(sortedList[:-1]) # do the first n-1 units, which are the ones with the least rows
if len(sortedList[len(sortedList) - 1][1]) == len(sortedList[len(sortedList) - 2][1]):
addToRows(sortedList[-1:]) # if the unit with the most rows, is tied with the second to last, do the last one too.
def generateRowOrColHeading(self, rowOrColStr, rowOrCol, factAxisMemberList, noHeadingsForTheseAxesSet, mostRecentSegmentTitleRow):
preferredLabel = getattr(rowOrCol, 'preferredLabel', None)
monthsEndedText = None
headingList = rowOrCol.headingList
verboseHeadings = self.filing.verboseHeadingsForDebugging
previousPseudoAxisNames = []
noDateRepetitionFlag = False
substituteForEmptyHeading = self.embedding.getEmptyHeading(self.cube.linkroleUri)
for i, factAxisMember in enumerate(factAxisMemberList):
pseudoAxisName = factAxisMember.pseudoAxisName
if (pseudoAxisName in noHeadingsForTheseAxesSet or
(mostRecentSegmentTitleRow is not None # do not repeat member information in previous segment title row.
and mostRecentSegmentTitleRow.axisInSegmentTitleHeaderBoolList[i])):
pass
# TODO: for grouped, if factAxisMember.member is None: continue
elif pseudoAxisName == 'unit':
self.generateAndAddUnitHeadings(rowOrCol, rowOrColStr)
elif pseudoAxisName == 'period':
try:
numMonths = rowOrCol.startEndContext.numMonths
if (numMonths > 0):
monthsEndedText = '{!s} Months Ended'.format(numMonths)
if self.embedding.columnPeriodPosition != -1:
headingList += [rowOrCol.startEndContext.label]
except AttributeError:
pass # incomplete or forever context
elif verboseHeadings:
headingList += [factAxisMember.memberLabel]
elif not factAxisMember.memberIsDefault:
if (not isinstance(pseudoAxisName,str)
and Utils.isEfmStandardNamespace(pseudoAxisName.namespaceURI)
and pseudoAxisName.localName == 'CreationDateAxis'):
if headingList == []:
headingList = ['('+ factAxisMember.memberLabel + ')']
else:
headingList[-1] = headingList[-1] + ' ('+ factAxisMember.memberLabel + ')'
else:
if (not isinstance(pseudoAxisName,str)
and Utils.isEfmStandardNamespace(pseudoAxisName.namespaceURI)
and pseudoAxisName.localName == 'StatementScenarioAxis'
and Utils.isEfmStandardNamespace(factAxisMember.member.namespaceURI)
and factAxisMember.member.localName == 'RestatementAdjustmentMember'):
noDateRepetitionFlag = True
headingList += [factAxisMember.memberLabel]
elif factAxisMember.memberIsDefault and self.cube.isTransposed:
substituteForEmptyHeading = factAxisMember.memberLabel
previousPseudoAxisNames += [pseudoAxisName]
if rowOrColStr == 'row':
thisLayoutDirectionHasPeriodAxis = self.embedding.rowPeriodPosition != -1
else:
thisLayoutDirectionHasPeriodAxis = self.embedding.columnPeriodPosition != -1
if Utils.isPeriodStartOrEndLabel(preferredLabel) and thisLayoutDirectionHasPeriodAxis and headingList != []:
strDate = (rowOrCol.context.endDatetime + datetime.timedelta(days=-1)).strftime('%b. %d, %Y')
headingList = [x for x in headingList if x != strDate ]
heading = ''
if len(headingList) > 0:
heading = headingList[0]
if len(headingList) > 1:
heading += ' (' + (', '.join(headingList[1:])) + ')'
if noDateRepetitionFlag:
headingList = [heading]
else:
headingList = [heading + ' at ' + strDate]
if monthsEndedText is not None and self.embedding.columnPeriodPosition != -1:
headingList = [monthsEndedText] + headingList
if headingList == [] and 'primary' not in previousPseudoAxisNames:
headingList = [substituteForEmptyHeading]
rowOrCol.headingList = headingList
def generateAndAddUnitHeadings(self, rowOrCol, rowOrColStr):
if self.embedding.suppressHeadingUnits:
return
# sorting by type, but monetary should always come first
sortedListOfFactSets = []
for unitType, factSet in sorted(rowOrCol.unitTypeToFactSetDefaultDict.items()):
if unitType == 'monetaryDerivedType':
sortedListOfFactSets = [factSet] + sortedListOfFactSets
else:
sortedListOfFactSets += [factSet]
unitSet = set()
unitAndMaybeSymbolList = []
for arelleFactSet in sortedListOfFactSets:
# we need a fact for each unit, why? because the type of the unit is actually in the element declaration
# so we do all this just to pull the fact out and pass it to getUnitAndSymbolStr, which will probably call fact.unitSymbol()
for fact in sorted(arelleFactSet, key = lambda thing : thing.unit.sourceline or 0):
if fact.unit not in unitSet:
unitSet.add(fact.unit)
unitSymbolStr = Utils.getUnitAndSymbolStr(fact)
if unitSymbolStr is not None:
unitAndMaybeSymbolList += [unitSymbolStr]
# we handle rows and cols slightly differently because for rows, we don't want to put filing.rowSeparatorStr between
# each of the units in the list of units for the row. however, for column headings, it's done differently, so they should be
# separated. so for rows, we want a long string, for cols, we want to append each to the list.
if len(unitAndMaybeSymbolList) > 0:
if rowOrColStr == 'row':
rowOrCol.headingList += [', '.join(sorted(unitAndMaybeSymbolList))]
else:
rowOrCol.headingList += unitAndMaybeSymbolList
# this function is used to append the unit to the end of a row if the units are on the columns and not promoted and
# if all facts in the row are using the same unit.
def appendUnitsToRowsIfUnitsOnColsAndRowHasOnlyOneUnit(self, row):
# the length is 1, so let's pull out the first in list.
unitType, arelleFactSet = list(row.unitTypeToFactSetDefaultDict.items())[0]
# there could be multiple currencies, like USD, JPY, make sure there are not.
if len({fact.unit for fact in arelleFactSet}) == 1:
return Utils.getSymbolStr(list(arelleFactSet)[0])
# we have to do something special where the row is all perShare, but in different currencies.
elif unitType == 'perShareDerivedType':
row.headingList += ['(per share)']
def HideAdjacentInstantRows(self):
# Rows are "adjacent" if they are
# 1. the same qname (because you could have a monetary, a shares, a decimal...)
# 2. previous is an end label and the next one a start label
# 3. the same instant endtime (implied by condition 4 but faster to test)
# 4. the same facts are displayed on both rows
def tracer(row):
self.controller.logDebug("In ''{}'', {} fact(s) in redundant rows will be hidden: qname={} instant={}".format(
self.cube.shortName, len(row.factList), row.elementQnameStr, row.startEndContext.endTime))
return # from tracer
mergeableRows = defaultdict(list)
for row in self.rowList:
if not row.isHidden and row.IsCalendarTitle:
coordinateListWithoutPeriod = tuple([row.elementQnameStr]+row.coordinateListWithoutUnitPeriodPrimary) # TODO - pretend unit can't appear on rows
mergeableRows[coordinateListWithoutPeriod] += [row]
for rowList in mergeableRows.values():
for index, thisRow in enumerate(rowList):
if index > 0:
prevRow = rowList[index-1]
if (Utils.isPeriodEndLabel(prevRow.preferredLabel) and
Utils.isPeriodStartLabel(thisRow.preferredLabel) and
prevRow.startEndContext.endTime==thisRow.startEndContext.endTime and
prevRow.factList==thisRow.factList):
tracer(thisRow)
thisRow.hide()
del mergeableRows
def emitRFile(self):
# we emit the cols and rows first and then plug them into the header and footer later.
# this is because there are side effects of the col and row processing that the header and footer depend on.
self.emitRFileCols()
self.emitRFileRows()
self.emitRFileHeaderAndFooter()
def emitRFileCols(self):
for index, col in enumerate(self.colList):
if not col.isHidden:
col.emitColumn(index)
def emitRFileRows(self):
for index, row in enumerate(self.rowList):
if not row.isHidden:
row.emitRow(index)
def emitRFileHeaderAndFooter(self):
SubElement(self.rootETree, 'Version').text = self.filing.controller.VERSION
SubElement(self.rootETree, 'ReportLongName').text = self.cube.definitionText
SubElement(self.rootETree, 'DisplayLabelColumn').text = str(not self.cube.isUnlabeled).casefold()
SubElement(self.rootETree, 'ShowElementNames').text = str(self.cube.isElements).casefold()
if self.RoundingOption is None:
SubElement(self.rootETree, 'RoundingOption')