File

src/app/home/timenet.service.ts

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
import { Injectable } from '@angular/core';

export interface TimeNetData {
    fileName: string;
    name: string;
    gedVersion: string;
    form: string;
    charset: string;

    persons: PersonData[];
    relationships: RelationShipData[];
}

/**
 * a point to draw the lines in the chart
 */
export interface GraphPoint {
    x: number;
    y: number;
}

export interface PersonData {
    id: string;
    sex: string;
    dateOfBirth: number;
    dateOfDeath: number;
    name: string[];
    baseLine: number;
    doi: number;
    parsedLine: GraphPoint[];
    relevantRelationships: RelationShipData[];
    block: LocationBlock;
}

/**
 * a block to determine the position of it's contained persons
 */
export interface LocationBlock {
    x: number;
    y: number;
    width: number;
    height: number;
    persons: PersonData[];
    childBlocks: LocationBlock[];
}

export interface RelationShipData {
    person1ID: string;
    person2ID: string;
    relationShipType: relationShipTypeEnum;
    relationShipStartDate: number;
    relationShipEndDate: number;
}

export enum relationShipTypeEnum {
  'Spouse-Of',
  'Child-Of',
  'Sibbling-Of'
}

export interface FamilyData {
  id: string;
  spouseIDs: string[];
  childIDs: string[];
}

@Injectable()
export class TimeNetDataService {

  private static getMaxOfArray(numArray) {
    return Math.max.apply(null, numArray);
  }

  private static getMinOfArray(numArray) {
    return Math.min.apply(null, numArray);
  }

  private static cleanID(person1ID: string): string{
    let pers = person1ID.split('@');
    return pers[1];
  }

  public _familyData: FamilyData[] = [];

  public _currentData: TimeNetData = {
    fileName:'', name: '', gedVersion: '', form: '', charset: '', persons: [], relationships: []
  };

  private _marriageOffset: number = 20;
  private _lifespanThreshold: number = 85;

  private _cachedPersonBirth: string[] = [];
  private _cachedPersonDeath: string[] = [];

  public _averageAge: number = 85;
  public _averageAgeBirth: number = 20;

  private _showConsoleLog: boolean = true;

  public newTimeNetData(fileName:string, name: string, gedVersion: string, form: string, charset: string): void {
      this._currentData.name = name;
      this._currentData.gedVersion = gedVersion;
      this._currentData.form = form;
      this._currentData.charset = charset;
      this._currentData.persons = [];
      this._currentData.relationships = [];
      this._familyData = [];
      this._currentData.fileName = fileName;

      this._cachedPersonDeath = [];
      this._cachedPersonBirth = [];
  }

  public getTimeNetData(): TimeNetData {
      return this._currentData;
  }

  public addSpouseToFamily(familyID, spouseID)
  {
    if (familyID.includes('@')) {
      familyID = TimeNetDataService.cleanID(familyID);
    }
    if (spouseID.includes('@')) {
      spouseID = TimeNetDataService.cleanID(spouseID);
    }
    let fam = this._familyData.find((f) => f.id === familyID);
    if (fam === undefined) {
      this._familyData.push(<FamilyData>{id:familyID, spouseIDs: [], childIDs: []});
      fam = this._familyData.find((f) => f.id === familyID);
    }
    fam.spouseIDs.push(spouseID);

  }

  public addChildToFamily(familyID, childID)
  {
    if (familyID.includes('@')) {
      familyID = TimeNetDataService.cleanID(familyID);
    }
    if (childID.includes('@')) {
      childID = TimeNetDataService.cleanID(childID);
    }
    var fam = this._familyData.find((f) => f.id === familyID);
    if (fam === undefined) {
      this._familyData.push(<FamilyData>{id:familyID, spouseIDs: [], childIDs: []});
      fam = this._familyData.find((f) => f.id === familyID);
    }
    fam.childIDs.push(childID);

  }

  public addPerson(id: string, names: string[], sex: string, dateOfBirth: string, dateOfDeath: string){
      let birthDate: number = TimeNetDataService.castStringToYear(dateOfBirth);
      let deathDate: number = TimeNetDataService.castStringToYear(dateOfDeath);
      if (id.includes('@')) {
        id = TimeNetDataService.cleanID(id);
      }
      this._currentData.persons.push(
        <PersonData> {id, name: names, sex, dateOfBirth: birthDate, dateOfDeath: deathDate, doi: 0.0});

  }

  public removePerson(person: PersonData): void {
      let index = this._currentData.persons.indexOf(person, 0);
      if (index > -1) {
          this._currentData.persons.splice(index, 1);
      }
  }

  public addReleationShip(person1ID: string, person2ID: string, relationShipType: relationShipTypeEnum,
                          relationShipStartDate: string, relationShipEndDate: string ): void {

    if (person1ID.includes('@')) {
      person1ID = TimeNetDataService.cleanID(person1ID);
    }
    if (person2ID.includes('@')) {
      person2ID = TimeNetDataService.cleanID(person2ID);
    }

    let startDate: number = TimeNetDataService.castStringToYear(relationShipStartDate);
    let endDate: number = TimeNetDataService.castStringToYear(relationShipEndDate);

    this._currentData.relationships.push( <RelationShipData> {
      person1ID,
      person2ID,
      relationShipType,
      relationShipStartDate: startDate,
      relationShipEndDate: endDate}
    );
  }

  public removeRelationShip(rel: RelationShipData): void {
      let index = this._currentData.relationships.indexOf(rel, 0);
      if (index > -1) {
          this._currentData.relationships.splice(index, 1);
      }
  }

  public getPersonById(id: string): PersonData {
    return this._currentData.persons.find((p) => p.id.substring(1, 11) === id.substring(1, 11));
  }

  private getAverageAgeOfPersons(): void {
    let age = this._lifespanThreshold;
    let lifeTimes: number[] = this._currentData.persons.filter((p) => isNaN(p.dateOfDeath) === false
            && isNaN(p.dateOfBirth) === false).map((p) => p.dateOfDeath - p.dateOfBirth);
    if( lifeTimes.length > 0) {
      this._averageAge = Math.round(lifeTimes.reduce((a, b) => (a + b)) / lifeTimes.length);
    } else {
      this._averageAge = age;
    }
  }

  private getAverageAgeOfPregnancy(): void {
    let age = this._marriageOffset;
    let totalYears = 0;
    let numberOfChildren = 0;

    for (let rel of this._currentData.relationships
      .filter((r) => r.relationShipType === relationShipTypeEnum['Child-Of']))
    {
      let child = this.getPersonById(rel.person1ID);
      let parent = this.getPersonById(rel.person2ID);

      if ((isNaN(child.dateOfBirth) === false) && (isNaN(parent.dateOfBirth) === false)) {
        totalYears += child.dateOfBirth - parent.dateOfBirth;
        numberOfChildren++;
      }
    }
    if (totalYears > 0) {
      age = Math.round(totalYears / numberOfChildren);
    }
    this._averageAgeBirth = age;
  }

  // final tasks which are made when the whole gedcom file information is read
  public finishImport(): void {
    console.log('Reading finished, starting missing data estimation');

    // estimate statistics
    this.getAverageAgeOfPersons();
    this.getAverageAgeOfPregnancy();

    if(this._currentData.persons.length > 1000) {
      this._showConsoleLog = false;
    }

    // check persondata, convert to timestamp
    this.checkPersonData();

    // check relationships for duplicates
    this.checkRelationshipData();

    // missing data estimation
    this.missingDataEstimation();

    // find relationships of each person for optimization
    this.findFittingRelationships();
  }

  private findFittingRelationships(): void {
    for (let person of this._currentData.persons) {
      person.relevantRelationships =
        this._currentData.relationships.filter((r) => r.person1ID === person.id);
      person.relevantRelationships = person.relevantRelationships.concat(
        this._currentData.relationships.filter((r) => r.person2ID === person.id));
      for (var i = 0; i < person.relevantRelationships.length; i++) {
        for (var j = i + 1; j < person.relevantRelationships.length; j++) {
          let rel1 = person.relevantRelationships[i];
          let rel2 = person.relevantRelationships[j];
          if (rel1.relationShipType === relationShipTypeEnum['Spouse-Of']
            && rel2.relationShipType === relationShipTypeEnum['Spouse-Of']
            && rel1.relationShipStartDate === rel2.relationShipStartDate
            && rel1.relationShipEndDate === rel2.relationShipEndDate
            && (rel1.person1ID === rel2.person1ID
            || rel1.person2ID === rel2.person2ID
            || rel1.person1ID === rel2.person2ID
            || rel1.person2ID === rel2.person1ID)) {
            person.relevantRelationships.splice(j, 1);
          }
        }
      }
    }
  }

  private missingDataEstimation(): void {

    if ( this._currentData.persons.filter((p) => isNaN(p.dateOfBirth) === false).length === 0) {
      this._currentData.persons[0].dateOfBirth = 0;
    }
    // check for Birth date first run
    for (let person of this._currentData.persons.filter((p) => isNaN(p.dateOfBirth) === true)) {
      person.dateOfBirth = this.estimateBirthDate(person.id);
    }

    // run the missing people again
    let oldCachedPerson: string[] = [];
    let newCachedPerson: string[] = this._cachedPersonBirth.slice();
    while (oldCachedPerson.length !== newCachedPerson.length) {
      oldCachedPerson = newCachedPerson.slice();
      if (oldCachedPerson.length > 0) {
        newCachedPerson = [];
        for ( let i = 0; i < oldCachedPerson.length; i++) {
          let persID: string = oldCachedPerson[i];
          let birth = this.estimateBirthDate(persID);

          if (isNaN(birth) === false) {
            this._currentData.persons.find((p) => p.id === persID).dateOfBirth = birth;
          } else {
            newCachedPerson.push(persID);
          }
        }
      }
    }

    // No information for those people available
    for (let persID of newCachedPerson) {
      this._currentData.persons.find((p) => p.id === persID).dateOfBirth = this.getEarliestYear();
      console.log('No data available, set birth to earliest date for ' + persID);
    }

    if ( this._currentData.persons.filter((p) => isNaN(p.dateOfDeath) === false).length === 0) {
      this._currentData.persons[0].dateOfDeath = this._averageAge;
    }

    // check for death date first run
    for (let person of this._currentData.persons.filter((p) => isNaN(p.dateOfDeath) === true)) {
      // check if its probability that person is alive
      if (person.dateOfBirth + this._averageAge < this.getLatestYear()) {
        person.dateOfDeath = this.estimateDeathDate(person.id);
      }else {
        // set to latest year
        console.log('Estimated person is alive therefore set to latest year: ' + person.id);
        person.dateOfDeath = this.getLatestYear();
      }
    }

    // run the missing people again
    oldCachedPerson = [];
    newCachedPerson = this._cachedPersonDeath.slice();
    while (oldCachedPerson.length !== newCachedPerson.length) {
      oldCachedPerson = newCachedPerson.slice();
      if (oldCachedPerson.length > 0) {
        newCachedPerson = [];
        for (let i = 0; i < oldCachedPerson.length; i++) {
          let persID: string = oldCachedPerson[i];
          let birth = this.estimateDeathDate(persID);

          if (isNaN(birth) === false) {
            this._currentData.persons.find((p) => p.id === persID).dateOfDeath = birth;
          } else {
            newCachedPerson.push(persID);
          }
        }
      }
    }

    // No information for those people available
    for (let persID of newCachedPerson) {
      this._currentData.persons.find((p) => p.id === persID).dateOfDeath
        = this._currentData.persons.find((p) => p.id === persID).dateOfBirth + this._averageAge ;
      console.log('No data available, set death to average lifetime for ' + persID);
    }

    // Missing data of marriages
    for (let rel of this._currentData.relationships.filter((r) => r.relationShipType === 0)) {
      rel.relationShipStartDate = Math.round(
        (this.getPersonById(rel.person1ID).dateOfBirth + this.getPersonById(rel.person2ID).dateOfBirth) / 2) + this._averageAgeBirth;

      /*
      if (this.getPersonById(rel.person1ID).dateOfDeath > this.getPersonById(rel.person2ID).dateOfDeath) {
        rel.relationShipEndDate = this.getPersonById(rel.person2ID).dateOfDeath;
      } else {
        rel.relationShipEndDate = this.getPersonById(rel.person1ID).dateOfDeath;
      }*/
    }

  }

  private checkRelationshipData(): void {
    // convert families to relationships
    for (let i = 0; i < this._familyData.length; i++) {
      let famData = this._familyData[i];
      // remove double entries
      famData.childIDs = Array.from(new Set(famData.childIDs));
      famData.spouseIDs = Array.from(new Set(famData.spouseIDs));

      // Add relationships child of and sibbling of
      for (let child of famData.childIDs) {
        for (let parent of famData.spouseIDs) {
          this.addReleationShip(child, parent, 1, '', '');
        }
        for (let sibbling of famData.childIDs) {
          if (sibbling !== child) {
            this.addReleationShip(child, sibbling, 2, '', '');
          }
        }
      }
      for (let parent of famData.spouseIDs) {
        for (let spouse of famData.spouseIDs) {
          if (parent !== spouse) {
            this.addReleationShip(parent, spouse, 0, '', '');
          }
        }
      }
    }
  }

  private checkPersonData(): void {

  }

  private static castStringToYear(dateString: string): number {
    let date: number;

    // save it with date null, missing values estimation is done
    // when the whole data information is available.
    if (dateString === null || dateString === '') {
      date = NaN;
    }else {
      let yearOffset: number = 0;
      // check if date has lotr ages

      if (dateString.includes('FA')) {
          dateString = dateString.replace('FA', '');
          yearOffset = 0;
        } else if (dateString.includes('SA')) {
          dateString = dateString.replace('SA', '');
          yearOffset = 583;
        } else if (dateString.includes('TA')) {
          dateString = dateString.replace('TA', '');
          yearOffset = 583 + 3441;
        } else if (dateString.includes('FoA')) {
          dateString = dateString.replace('FoA', '');
          yearOffset = 583 + 3441 + 3021;
         }else if (dateString.includes('SR')) {
          dateString = dateString.replace('SR', '');
          yearOffset = 1600 + 583 + 3441;
        }
      if ( dateString.toLowerCase().startsWith('bef') || dateString.toLowerCase().startsWith('aft')
        || dateString.toLowerCase().startsWith('est') || dateString.toLowerCase().startsWith('abt')) {
        dateString = dateString.slice(4);
      }
      // use date parser for different date formats
      let tempdate = new Date(dateString);

      // workaround for dates under 100, because the date parser converts them to 19xx
      if (dateString.length <= 4) {
        date = parseInt(dateString) + yearOffset;
      } else {
        date = tempdate.getFullYear() + yearOffset;
      }

      // when not inthe yearof the sun set it to 0
      if (dateString.includes('YT')) {
        date = 0;
      }

    }

    return date;
  }

  private estimateDeathDate(personID: string): number {
    // get all relationship for a person
    let relations = this._currentData.relationships.filter((r) => r.person1ID === personID
    || r.person2ID === personID);

    // mean sibling death
    let sibblings: string[] = relations
      .filter((r) => r.person1ID === personID && r.relationShipType === 2)
      .map((r) => r.person2ID);
    let yearsOfSibs = 0;
    let numberOfSibsWithDeath = 0;

    for (let sib of sibblings) {
      if (isNaN(this.getPersonById(sib).dateOfDeath) === false) {
        yearsOfSibs += this.getPersonById(sib).dateOfDeath;
        numberOfSibsWithDeath++;
      }
    }
    if (yearsOfSibs > 0) {
      if(this._showConsoleLog) {
        console.log('Estimated Death(sibbling average) for ' + personID);
      }
      return Math.round(yearsOfSibs / numberOfSibsWithDeath);
    }

    // mean spouse death
    let spouses: string[] = relations
      .filter((r) => r.person1ID === personID && r.relationShipType === 0)
      .map((r) => r.person2ID);
    let yearsOfSpouse = 0;
    let numberOfSpouseWithDeath = 0;

    for (let spouse of spouses) {
      if (isNaN(this.getPersonById(spouse).dateOfDeath) === false) {
        yearsOfSpouse += this.getPersonById(spouse).dateOfDeath;
        numberOfSpouseWithDeath++;
      }
    }
    if (yearsOfSpouse > 0) {
      if(this._showConsoleLog) {
        console.log('Estimated Death(spouse average) for ' + personID);
      }
      return Math.round(yearsOfSpouse / numberOfSpouseWithDeath);
    }

    let childs: string[] = relations
      .filter((r) => r.person2ID === personID && r.relationShipType === 1)
      .map((r) => r.person1ID);
    let yearsOfChildren = 0;
    let numberOfChildsWithDeath = 0;

    for (let child of childs) {
      if (isNaN(this.getPersonById(child).dateOfDeath) === false) {
        yearsOfChildren += this.getPersonById(child).dateOfDeath;
        numberOfChildsWithDeath++;
      }
    }
    if (yearsOfChildren > 0) {
      if(this._showConsoleLog) {
        console.log('Estimated Death(children average) for ' + personID);
      }
      return Math.round(yearsOfChildren / numberOfChildsWithDeath) - this._averageAgeBirth;
    }

    this._cachedPersonDeath.push(personID);
    return NaN;
  }

  private estimateBirthDate(personID: string): number {
    // get all relationship for a person
    let relations = this._currentData.relationships.filter((r) => r.person1ID === personID
    || r.person2ID === personID);

    // check for parent marriage

    // actually no use because, marriage data is not saved in gedcom files...

    let parentsRel = relations.filter((r) => r.person1ID === personID && r.relationShipType === 1);
    /*if (parentsRel.length === 2) {
      let parent1 = parentsRel[0].person1ID;
      let parent2 = parentsRel[1].person2ID;

      let mariage = this._currentData.relationships
        .filter((r) => (r.person1ID === parent1 && r.person2ID === parent2) ||
      (r.person1ID === parent2 && r.person2ID === parent1));

      for (let obj of mariage) {
        if ( isNaN(obj.relationShipStartDate) === false) {
         return obj.relationShipStartDate;
        }
      }
    }*/

    // mean sibling birth
    let sibblings: string[] = relations
      .filter((r) => r.person1ID === personID && r.relationShipType === 2)
      .map((r) => r.person2ID);
    let yearsOfSibs = 0;
    let numberOfSibsWithBirth = 0;

    for (let sib of sibblings) {
      if (isNaN(this.getPersonById(sib).dateOfBirth) === false) {
        yearsOfSibs += this.getPersonById(sib).dateOfBirth;
        numberOfSibsWithBirth++;
      }
    }
    if (yearsOfSibs > 0) {
      if(this._showConsoleLog) {
        console.log('Estimated Birth(sibbling) for ' + personID);
      }
      return Math.round(yearsOfSibs / numberOfSibsWithBirth);
    }

    // mean spouse birth
    let spouses: string[] = relations
      .filter((r) => r.person1ID === personID && r.relationShipType === 0)
      .map((r) => r.person2ID);
    let yearsOfSpouse = 0;
    let numberOfSpouseWithBirth = 0;

    for (let spouse of spouses) {
      if (isNaN(this.getPersonById(spouse).dateOfBirth) === false) {
        yearsOfSpouse += this.getPersonById(spouse).dateOfBirth;
        numberOfSpouseWithBirth++;
      }
    }
    if (yearsOfSpouse > 0) {
      if(this._showConsoleLog) {
        console.log('Estimated Birth(spouse) for ' + personID);
      }
      return Math.round(yearsOfSpouse / numberOfSpouseWithBirth);
    }

    // estimate if death is known
    let pers = this.getPersonById(personID);
    if (isNaN(pers.dateOfDeath) === false) {
      if(this._showConsoleLog) {
        console.log('Estimated Birth(death+average) for ' + personID);
      }
      return pers.dateOfDeath - this._averageAge;

    }

    // estimate if birth of parents is known
    let parIds = parentsRel.map((p) => p.person2ID);
    for (let parid of parIds) {
      if (isNaN(this.getPersonById(parid).dateOfBirth) === false) {
        if(this._showConsoleLog) {
          console.log('Estimated Birth(parent birth + average) for' + personID);
        }
        return this.getPersonById(parid).dateOfBirth + this._averageAgeBirth;
      }
    }

    // estimate if birth of children is known
    let childs = relations
      .filter((r) => r.person2ID === personID && r.relationShipType === 1)
      .map((p) => p.person1ID);
    let childBirthYears: number[] =  [];
    for (let childid of childs) {
      if (isNaN(this.getPersonById(childid).dateOfBirth) === false) {
        childBirthYears.push(this.getPersonById(childid).dateOfBirth);
      }
    }
    if (childBirthYears.length > 0) {
      let yearOfOldestChild = TimeNetDataService.getMinOfArray(childBirthYears);
      if (this._showConsoleLog) {
        console.log('Estimated Birth(child birth + average) for' + personID);
      }
      return yearOfOldestChild - this._averageAgeBirth;
    }

    this._cachedPersonBirth.push(personID);
    return NaN;
  }



  private getEarliestYear(): number {
    return TimeNetDataService.getMinOfArray(this._currentData.persons
      .filter((p) => isNaN(p.dateOfBirth) === false).map((r) => r.dateOfBirth));
  }

  private getLatestYear(): number {
    return TimeNetDataService.getMaxOfArray(this._currentData.persons
      .filter((p) => isNaN(p.dateOfDeath) === false).map((r) => r.dateOfDeath));
  }

}

results matching ""

    No results matching ""