dataframes.py 43.3 KB
Newer Older
1 2 3 4
# -*- coding: utf-8 -*-
"""report_dataframe module

"""
5
import json
6
import numpy as np
7
import pandas as pd
8
import time
9 10 11 12


from datetime import date
from gluon import current
13
from gluon.storage import Storage
14 15


16 17
DATE_MIN = date(1990, 01, 01)
DATE_MAX = date(2050, 12, 31)
18

19 20 21 22 23 24 25
HISTORY_QUERY_FIELDS = [
        "id_events",
        "id_domains",
        "id_fundings",
        "id_objects",
        "id_object_categories",
        "id_people",
26
        "id_people_code",
27 28
        "id_projects",
        "id_teams",
29 30
        "object_categories_category",
        "people_categories_category",
31 32 33
        "year_end",
        "year_start"]

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
def _get_column_names(fields):
    """Snippet to get list of column names from a list of database field.

    Rules are applied to resolve ambiguities when the field name is used
    in different table, *e.g* code, category or note.

    Args:
        fields (list): list of gluon.dal.Field

    Returns:
        list

    """

    # columns name for the DataFrame from database fields
    # resolve ambiguities for code, category and note
    columns = []
    for field in fields:
        name = field.name
        if name in ("code", "category", "note"):
            name = "%s_%s" % (field._table._tablename, name)
        columns.append(name)
    return columns


def _get_items_per_year(func, **kwargs):
    """Snippet transforming a of active items between year_start and year_end
    to a list of active items per year.

    The year range is defined by the keyword ``year_start`` and ``year_end``.
    The underlying logic deal with all cases.

    Args:
        func (reference):
            reference to a function generating the dataframe for active items.
        **kwargs (dict):
            key, value pair to select item, the event and the year range.
            They are use by the function func.

    Returns:
        pandas.DataFrame

    """

LE GAC Renaud's avatar
LE GAC Renaud committed
79 80 81
    is_start = \
        "year_start" in kwargs and kwargs["year_start"] not in (None, '')

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
    is_end = "year_end" in kwargs and kwargs["year_end"] not in (None, '')

    if not is_start and not is_end:
        kwargs["year_start"] = DATE_MIN.year
        kwargs["year_end"] = DATE_MAX.year

    elif is_start and not is_end:
        kwargs["year_end"] = kwargs["year_start"]

    elif is_end and not is_start:
        kwargs["year_start"] = kwargs["year_end"]

    ystart = int(kwargs["year_start"])
    yend = int(kwargs["year_end"])

    df = (func(**kwargs)
          .reset_index()
          .pipe(expand_per_year, ystart, yend))

    return df


def active_period(**kwargs):
    """Determine the period of activity for a person / object when the
    domain and/or project and/or team and or category is fixed.

    For example, for a person belonging to a domain and team for which
    people category / project evolve as function of time, the start and the
    end of the period of activity are shown by the ^:

            -------
                   --------
                           ----------
            ^                       ^

    Keyword Args:
        id_events (int): identifier of the event [required]
        id_domains (int):
        id_fundings (int):
        id_objects (int):
        id_object_categories (int):
        id_people (int):
        id_people_categories (int):
        id_projects (int):
        id_teams (int):

    Returns
        tuple:
            start (date): is fixed to DATE_MIN when not defined
            stop (date): is fixed to DATE_MAX when not defined

    """
    db = current.globalenv['db']
    history = db.history

    # extract database information
    query = query_history(db, **kwargs)

    fields = [history.start_date, history.end_date]
LE GAC Renaud's avatar
LE GAC Renaud committed
141
    rows = db.executesql(db(query)._select(*fields))
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

    # fin the start / end point using DataFrame
    df = (pd.DataFrame(list(rows), columns=["start", "end"])
          .assign(
              start=lambda x: x.start.fillna(DATE_MIN),
              end=lambda x: x.end.fillna(DATE_MAX))
          .sort_values("start"))

    return (df.start.min(), df.end.max())


def coverage(start_date, end_date, year_start, year_end):
    """Vectorized function to compute the quantify coverage.

    Args:
        start_date (datetime64): start date of the event
        start_date (datetime64): end date of the event
        year_start (datetime64): start of the year
        end_year (datetime64): end of the year

    Returns:
        float64

    """
LE GAC Renaud's avatar
LE GAC Renaud committed
166 167
    coverage = \
        np.minimum(end_date, year_end) - np.maximum(start_date, year_start)
168 169 170 171

    return coverage / (year_end - year_start)


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
def db2df(db, query, fields=[], columns=None):
    """Transform a database query into a dataframe.

    Example::

        # database query
        query = history.id_events == id_event
        query &= history.id_projects == id_project
        query &= history.id_fundings == db.fundings.id
        query &= history.id_people == db.people.id
        query &= history.id_people_categories == db.people_categories.id
        query &= history.id_teams == db.teams.id

        # fields to be extracted from the database
        fields = [
            history.id_domains,
            history.id_events,
            history.id_people,
            history.id_projects,
            history.id_teams,
            db.teams.team,
            db.people_categories.category,
            db.people_categories.code,
            db.people.first_name,
            db.people.last_name,
            history.percentage,
            history.start_date,
            history.end_date,
            history.data,
            db.fundings.agency]

        # get the DataFrame
        df = db2df(query, fields)
        print df.info()

    Args:
        db (pyDAL.DAL): database connection.

        query: database query including statement to join foreign table.

        fields (list): list of pyDAL.Field to be extracted from the query.
            All fields are extracted when not defined.

        columns (list): name of the columns in the dataframe. There is one
            to one correspondence between the fields and columns list.
            Names of database field are used when columns is not defined.

    Returns:
        pandas.DataFrame

    """
    if columns is None and len(fields) > 0:
        columns = [field.name for field in fields]

    rows = db.executesql(db(query)._select(*fields))
    return pd.DataFrame.from_records(list(rows), columns=columns)


230 231
def debug_df(df, opt=""):
    """Helper tool to debug a DataFrame.
232

233 234 235
    Args
        df (pandas.DataFrame):
        opt (str): debug options:
LE GAC Renaud's avatar
LE GAC Renaud committed
236

237 238 239 240 241 242
            * ``a``: equivalent to icIht
            * ``c``: show columns
            * ``I``: show index
            * ``h``: show head
            * ``t``: show tail
            * ``f``: show the whole dataframe
243

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    """
    if "i" in opt or "a" in opt:
        df.memory_usage()
        print df.info()

    if "c" in opt or "a" in opt:
        print df.columns

    if "I" in opt or "a" in opt:
        print df.index

    if "h" in opt or "a" in opt:
        print df.head()

    if "t" in opt or "a" in opt:
        print df.tail()

    if "f" in opt or "a" in opt:
        print df


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
def expand_per_year(df, year_start, year_end):
    """Expand the list of active items between year_start and year_end to
    a list of active items per year. An item appears several time when it
    is active during several years.

    Graphically, the item

            --+...+ 2012-06 2014-02 +--++

    becomes
            2012 --+...+ 2012-06 2014-02 +--++
            2013 --+...+ 2012-06 2014-02 +--++
            2014 --+...+ 2012-06 2014-02 +--++

    Note:
        The columns `start_date` and `end_date` have to be defined in the
        DataFrame.

    Args:
        year_start (date):
        year_end (date):

    Returns:
        pandas.DataFrame:
            Columns are:
                * those of the initial DataFrame
                * year (int)
    """
    # for each item compute the list of year for which the item is active
    # the information is kept in a PeriodIndex stored in the column years.

    # NOTE:
    #    - failed to implemented a faster way using df.apply
    #
    li = []
    for row in df.itertuples():
        li.append([pd.period_range(row.start_date, row.end_date, freq="A")])

    df1 = df.merge(pd.DataFrame(li, columns=["years"]),
                   left_index=True,
                   right_index=True)

    # for each year keep the list of active items
    # an item appears several time when it is active during several years.
    df2 = pd.DataFrame()

    for year in xrange(year_start, year_end+1):
        dfi = (df1.loc[[str(year) in el for el in df1.years]]
               .assign(year=year))
        df2 = pd.concat((df2, dfi), ignore_index=True)

    # Keep the memory foot print low by removing the years column
    df2 = df2.drop("years", axis="columns")

    return df2


def full_name(first_name, last_name):
    """Vectorized function to build the full name of a people.

    Args
        first (series of string):
        last (series of string):

    Returns:
        Series of string

    """
    return first_name.str.cat(last_name, sep=" ")


def get_items(**kwargs):
337 338
    """Return the DataFrame with active items belonging to the event id_event.

339 340 341 342
    The DataFrame contains all information for each item, namely the meta-data,
    categories, domain, funding, object, people, project, team information
    as well as the history.data. The latter is a dictionary which is
    "json normalised", one column per key.
343 344 345 346 347 348

    The selection of the item is performed by querying the database.
    The query is built using the keyword arguments.

    Active items are selected using the arguments ``year_start``
    and ``year_end``.
349 350

    Keyword Args:
351
        id_events (int): identifier of the event [required]
352 353 354 355 356 357 358 359 360 361 362 363
        id_domains (int):
        id_fundings (int):
        id_objects (int):
        id_object_categories (int):
        id_people (int):
        id_people_categories (int):
        id_projects (int):
        id_teams (int):
        year_end (date):
        year_start (date):

    Returns:
364 365 366 367 368 369
        pandas.DataFrame:
            The index of the DataFrame is the history table identifier.
            The columns of the DataFrame are:

                * id_domains (int)
                * id_events (int)
370
                * id_fundings (int)
371 372 373 374 375 376
                * id_objects (int)
                * id_objects_categories (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395

                * agency (str)
                * batch_number (str)
                * birth_date (str)
                * domain (str)
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * first_name (str)
                * history_note (str)
                * last_name (str)
                * object_categories_category (str)
                * object_categories_code (str)
                * objects_note (str)
                * people_categories_category (str)
                * people_categories_code (str)
                * people_note (str)
                * percentage (int)
                * project (str)
                * reference (str)
                * serial_number (str)
396
                * start_date (date): undefined dates are forced to ``DATE_MIN``
397 398 399
                * team (str)

                * one column for each key of the history.data dictionary
400 401 402 403 404

    """
    db = current.globalenv['db']
    history = db.history

405
    # database query including foreign table
406
    query = query_history(db, **kwargs)
407

408 409 410 411 412 413 414 415 416
    query &= history.id_domains == db.domains.id
    query &= history.id_fundings == db.fundings.id
    query &= history.id_objects == db.objects.id
    query &= history.id_object_categories == db.object_categories.id
    query &= history.id_people == db.people.id
    query &= history.id_people_categories == db.people_categories.id
    query &= history.id_projects == db.projects.id
    query &= history.id_teams == db.teams.id

417 418 419 420 421 422
    # fields to be extracted from the database
    fields = [
        history.id,
        history.id_domains,
        history.id_events,
        history.id_fundings,
423
        history.id_objects,
424 425 426 427 428
        history.id_object_categories,
        history.id_people,
        history.id_people_categories,
        history.id_projects,
        history.id_teams,
429 430 431
        history.data,
        history.note,
        history.percentage,
432 433
        history.start_date,
        history.end_date,
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
        db.domains.domain,
        db.fundings.agency,
        db.objects.reference,
        db.objects.serial_number,
        db.objects.batch_number,
        db.objects.note,
        db.object_categories.code,
        db.object_categories.category,
        db.people.first_name,
        db.people.last_name,
        db.people.birth_date,
        db.people.note,
        db.people_categories.code,
        db.people_categories.category,
        db.projects.project,
        db.teams.team]
450 451

    # columns name for the DataFrame
452 453
    # resolve ambiguities for code, category and note
    columns = _get_column_names(fields)
454 455 456 457 458 459

    # the DataFrame
    df = (db2df(db, query, fields, columns)
          .set_index("id")
          .pipe(normalize_history_data)
          .assign(
460 461 462 463 464 465
              start_date=lambda x: x.start_date.fillna(DATE_MIN),
              end_date=lambda x: x.end_date.fillna(DATE_MAX)))

    return df


466 467 468
def get_items_per_year(**kwargs):
    """Return the DataFrame with active items for each year,
    belonging to the event id_event. An item appears several time when it
469 470
    is active during several years.

471 472 473 474
    The DataFrame contains all information for each item, namely the meta-data,
    categories, domain, funding, object, people, project, team information
    as well as the history.data. The latter is a dictionary which is
    "json normalised", one column per key.
475

476 477
    The selection of the item is performed by querying the database.
    The query is built using the keyword arguments.
478

479 480 481
    The range of years are selected using the arguments ``year_start``
    and ``year_end``. The scan is between ``DATE_MIN`` and/or ``DATE_MAX`` when
    ``year_start`` and/or ``DATE_MIN`` is/are not defined.
482

483 484 485 486 487 488 489 490 491 492
    Keyword Args:
        id_events (int): identifier of the event [required]
        id_domains (int):
        id_fundings (int):
        id_objects (int):
        id_object_categories (int):
        id_people (int):
        id_people_categories (int):
        id_projects (int):
        id_teams (int):
493
        year_end (date):
494
        year_start (date):
495 496 497

    Returns:
        pandas.DataFrame:
498
            The columns of the DataFrame are:
499

500 501 502 503 504 505 506 507 508 509
                * id (int): history table identifier for the item
                * id_domains (int)
                * id_events (int)
                * id_fundings (int)
                * id_objects (int)
                * id_objects_categories (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)
510

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
                * agency (str)
                * batch_number (str)
                * birth_date (str)
                * domain (str)
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * first_name (str)
                * history_note (str)
                * last_name (str)
                * object_categories_category (str)
                * object_categories_code (str)
                * objects_note (str)
                * people_categories_category (str)
                * people_categories_code (str)
                * people_note (str)
                * percentage (int)
                * project (str)
                * reference (str)
                * serial_number (str)
                * start_date (date): undefined dates are forced to ``DATE_MIN``
                * team (str)
531

532
                * one column for each key of the history.data dictionary
533

534 535
    """
    return _get_items_per_year(get_items, **kwargs)
536 537


538 539
def get_items_small(**kwargs):
    """Return the DataFrame with active items belonging to the event id_event.
540 541

    The DataFrame contains the minimal set of information for each item,
542 543
    namely the meta-data as well as the history.data. The latter is a
    dictionary which is "json normalised", one column per key.
544 545 546 547

    The selection of the item is performed by querying the database.
    The query is built using the keyword arguments.

548 549
    Active items are selected using the arguments ``year_start``
    and ``year_end``.
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

    Keyword Args:
        id_events (int): identifier of the event [required]
        id_domains (int):
        id_fundings (int):
        id_objects (int):
        id_object_categories (int):
        id_people (int):
        id_people_categories (int):
        id_projects (int):
        id_teams (int):
        year_end (date):
        year_start (date):

    Returns:
        pandas.DataFrame:
566
            The index of the DataFrame is the history table identifier.
567 568 569 570
            The columns of the DataFrame are:

                * id_domains (int)
                * id_events (int)
LE GAC Renaud's avatar
LE GAC Renaud committed
571
                * id_fundings (int)
572 573 574 575 576 577
                * id_objects (int)
                * id_objects_categories (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)
578 579

                * end_date (date): undefined dates are forced to ``DATE_MAX``
580 581
                * start_date (date): undefined dates are forced to ``DATE_MIN``

582
                * one column for each key of the history.data dictionary
583

584 585 586
    """
    db = current.globalenv['db']
    history = db.history
587

588 589
    # database query
    query = query_history(db, **kwargs)
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
    # fields to be extracted from the database
    fields = [
        history.id,
        history.id_domains,
        history.id_events,
        history.id_fundings,
        history.id_objects,
        history.id_object_categories,
        history.id_people,
        history.id_people_categories,
        history.id_projects,
        history.id_teams,
        history.start_date,
        history.end_date,
        history.data]

    # columns name for the DataFrame
    columns = [field.name for field in fields]

    # the DataFrame
    df = (db2df(db, query, fields, columns)
          .set_index("id")
          .pipe(normalize_history_data)
          .assign(
              start_date=lambda x: x.start_date.fillna(DATE_MIN),
              end_date=lambda x: x.end_date.fillna(DATE_MAX)))

    return df


def get_items_small_per_year(**kwargs):
    """Return the DataFrame with active items for each year,
    belonging to the event id_event. An item appears several time when it
    is active during several years.

    The DataFrame contains the minimal set of information for each item,
    namely the meta-data, the year as well as the history.data.
    The latter is a dictionary which is "json normalised", one column per key.

    The selection of the item is performed by querying the database.
    The query is built using the keyword arguments.

    The range of years are selected using the arguments ``year_start``
    and ``year_end``. The scan is between ``DATE_MIN`` and/or ``DATE_MAX`` when
    ``year_start`` and/or ``DATE_MIN`` is/are not defined.

    Keyword Args:
        id_events (int): identifier of the event [required]
        id_domains (int):
        id_fundings (int):
        id_objects (int):
        id_object_categories (int):
        id_people (int):
        id_people_categories (int):
        id_projects (int):
        id_teams (int):
        year_end (date):
        year_start (date):

    Returns:
        pandas.DataFrame:
            The columns of the DataFrame are:

                * id (int): history table identifier for the item
                * id_domains (int)
                * id_events (int)
                * id_objects (int)
                * id_objects_categories (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)

                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * start_date (date): undefined dates are forced to ``DATE_MIN``
                * year (int)

                * one column for each key of the history.data dictionary

    """
    return _get_items_per_year(get_items_small, **kwargs)


def get_objectlike_items(**kwargs):
    """Return the DataFrame with active items belonging to the event id_event
    when items are related to object.

    The DataFrame contains a reduced set of information for each item, namely
    the meta-data, category, domain, funding, object, project, team information
    as well as the history.data. The latter is a dictionary which is
    "json normalised", one column per key.

    The selection of the item is performed by querying the database.
    The query is built using the keyword arguments.

    Active items are selected using the arguments ``year_start``
    and ``year_end``.

    Keyword Args:
        id_events (int): identifier of the event [required]
        id_domains (int):
        id_fundings (int):
        id_objects (int):
        id_object_categories (int):
        id_projects (int):
        id_teams (int):
        year_end (date):
        year_start (date):

    Returns:
        pandas.DataFrame:
            The index of the DataFrame is the history table identifier.
            The columns of the DataFrame are:

                * id_domains (int)
                * id_events (int)
                * id_fundings (int)
                * id_objects (int)
                * id_objects_categories (int)
                * id_projects (int)
                * id_teams (int)

                * agency (str)
                * batch_number (str)
                * domain (str)
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * history_note (str)
                * object_categories_category (str)
                * object_categories_code (str)
                * objects_note (str)
                * project (str)
                * reference (str)
                * serial_number (str)
                * start_date (date): undefined dates are forced to ``DATE_MIN``
                * team (str)

                * one column for each key of the history.data dictionary

    """
    db = current.globalenv['db']
    history = db.history

    # database query including foreign table
    query = query_history(db, **kwargs)

    query &= history.id_domains == db.domains.id
    query &= history.id_fundings == db.fundings.id
    query &= history.id_objects == db.objects.id
    query &= history.id_object_categories == db.object_categories.id
    query &= history.id_projects == db.projects.id
    query &= history.id_teams == db.teams.id

    # fields to be extracted from the database
    fields = [
        history.id,
        history.id_domains,
        history.id_events,
        history.id_fundings,
        history.id_objects,
        history.id_object_categories,
        history.id_projects,
        history.id_teams,
        history.data,
        history.note,
        history.start_date,
        history.end_date,
        db.domains.domain,
        db.fundings.agency,
        db.objects.reference,
        db.objects.serial_number,
        db.objects.batch_number,
        db.objects.note,
        db.projects.project,
        db.teams.team]

    # columns name for the DataFrame
    # resolve ambiguities for code, category and note
    columns = _get_column_names(fields)

    # the DataFrame
    df = (db2df(db, query, fields, columns)
          .set_index("id")
          .pipe(normalize_history_data)
          .assign(
              start_date=lambda x: x.start_date.fillna(DATE_MIN),
              end_date=lambda x: x.end_date.fillna(DATE_MAX)))

    return df


def get_objectlike_items_per_year(**kwargs):
    """Return the DataFrame with active items for each year, belonging to the
    event id_event when the event is related to object. An item appears several
    time when it is active during several years.

    The DataFrame contains a reduced set of information for each item, namely
    the meta-data, category, domain, funding, object, project, team information
    as well as the history.data. The latter is a dictionary which is
    "json normalised", one column per key.

    The selection of the item is performed by querying the database.
    The query is built using the keyword arguments.

    The range of years are selected using the arguments ``year_start``
    and ``year_end``. The scan is between ``DATE_MIN`` and/or ``DATE_MAX`` when
    ``year_start`` and/or ``DATE_MIN`` is/are not defined.

    Keyword Args:
        id_events (int): identifier of the event [required]
        id_domains (int):
        id_fundings (int):
        id_objects (int):
        id_object_categories (int):
        id_projects (int):
        id_teams (int):
        year_end (date):
        year_start (date):

    Returns:
        pandas.DataFrame:
            The columns of the DataFrame are:

                * id (int): history table identifier for the item
                * id_domains (int)
                * id_events (int)
                * id_fundings (int)
                * id_objects (int)
                * id_objects_categories (int)
                * id_projects (int)
                * id_teams (int)

                * agency (str)
                * batch_number (str)
                * domain (str)
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * history_note (str)
                * object_categories_category (str)
                * object_categories_code (str)
                * objects_note (str)
                * project (str)
                * reference (str)
                * serial_number (str)
                * start_date (date): undefined dates are forced to ``DATE_MIN``
                * team (str)

                * one column for each key of the history.data dictionary

    """
LE GAC Renaud's avatar
LE GAC Renaud committed
839
    return _get_items_per_year(get_objectlike_items, **kwargs)
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


def get_peoplelike_items(**kwargs):
    """Return the dataFrame with active items belonging to the event id_event
    when the event is related to people.

    The DataFrame contains a reduced set of information for each item, namely
    the meta-data, category, domain, funding, people, project, team information
    as well as the history.data. The latter is a dictionary which is
    "json normalised", one column per key.

    The selection of the item is performed by querying the database.
    The query is built using the keyword arguments.

    Active items are selected using the arguments ``year_start``
    and ``year_end``.

    Keyword Args:
        id_events (int): identifier of the event [required]
        id_domains (int):
        id_fundings (int):
        id_people (int):
        id_people_categories (int):
        id_projects (int):
        id_teams (int):
        year_end (date):
        year_start (date):

    Returns:
        pandas.DataFrame:
            The index of the DataFrame is the history table identifier.
            The columns of the DataFrame are:

                * id_domains (int)
                * id_fundings (int)
                * id_events (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)

                * agency (str)
                * birth_date (str)
                * domain (str)
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * first_name (str)
                * history_note (str)
                * last_name (str)
                * people_categories_category (str)
                * people_categories_code (str)
                * people_note (str)
                * percentage (int)
                * project (str)
                * start_date (date): undefined dates are forced to ``DATE_MIN``
                * team (str)

                * one column for each key of the history.data dictionary

    """
    db = current.globalenv['db']
    history = db.history

    # database query including foreign table
    query = query_history(db, **kwargs)

    query &= history.id_domains == db.domains.id
    query &= history.id_fundings == db.fundings.id
    query &= history.id_people == db.people.id
    query &= history.id_people_categories == db.people_categories.id
    query &= history.id_projects == db.projects.id
    query &= history.id_teams == db.teams.id

    # fields to be extracted from the database
    fields = [
        history.id,
        history.id_domains,
        history.id_events,
        history.id_fundings,
        history.id_people,
        history.id_people_categories,
        history.id_projects,
        history.id_teams,
        history.data,
        history.note,
        history.percentage,
        history.start_date,
        history.end_date,
        db.domains.domain,
        db.fundings.agency,
        db.people.first_name,
        db.people.last_name,
        db.people.birth_date,
        db.people.note,
        db.people_categories.code,
        db.people_categories.category,
        db.projects.project,
        db.teams.team]

    # columns name for the DataFrame
    # resolve ambiguities for code, category and note
    columns = _get_column_names(fields)

    # the DataFrame
    df = (db2df(db, query, fields, columns)
          .set_index("id")
          .pipe(normalize_history_data)
          .assign(
              start_date=lambda x: x.start_date.fillna(DATE_MIN),
              end_date=lambda x: x.end_date.fillna(DATE_MAX)))
949 950 951 952

    return df


953 954 955 956 957 958
def get_people_per_year(**kwargs):
    """Return the DataFrame with active items for each year, belonging to a
    people like event. An item appears several time when it is active during
    several years.

    The DataFrame contains a reduced set of information for each item, namely
LE GAC Renaud's avatar
LE GAC Renaud committed
959 960 961 962
    the meta-data, category, domain, funding, people, project, team
    information, the ``history.data`` and a set of computed values.
    The ``history.data`` is a dictionary which is "json normalised",
    one column per key.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040

    The DataFrame contains computed columns:
        * coverage
        * fte
        * full_name
        * is_end
        * is_start
        * period_end
        * period_start

    The selection of items is performed by querying the database.
    The query is built using the keyword arguments.

    The range of years are selected using the arguments ``year_start``
    and ``year_end``. The scan is between ``DATE_MIN`` and/or ``DATE_MAX`` when
    ``year_start`` and/or ``DATE_MIN`` is/are not defined.

    Item belonging to the same year, domain, team project and people are
    group in order to compute properly coverage and fte values.

    Keyword Args:
        id_events (int): identifier of the people like event [required]
        id_domains (int):
        id_fundings (int):
        id_people (int):
        id_people_categories (int):
        id_projects (int):
        id_teams (int):
        year_end (date):
        year_start (date):

    Returns:
        pandas.DataFrame:
            The columns of the DataFrame are:

                * id (int): history table identifier for the item
                * id_domains (int)
                * id_events (int)
                * id_fundings (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)

                * agency (str)
                * birth_date (str)
                * coverage (float)
                * domain (str)
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * first_name (str)
                * full_name (str)
                * fte (float)
                * history_note (str)
                * is_end (bool)
                * is_start (bool)
                * last_name (str)
                * people_categories_category (str)
                * people_categories_code (str)
                * people_note (str)
                * percentage
                * period_start (date):
                * period_end (date):
                * project (str)
                * start_date (date): undefined dates are forced to ``DATE_MIN``
                * team (str)

                * one column for each key of the history.data dictionary

    """
    # compute the period of activity when the person is attached to the
    # same domain, project and team

    # compute the beginning and ending of each year
    # it is temporarily columns which are used in coverage computation

    df = (_get_items_per_year(get_peoplelike_items, **kwargs)
          .assign(
              period=lambda x:
LE GAC Renaud's avatar
LE GAC Renaud committed
1041 1042 1043 1044 1045 1046 1047
              x.apply(lambda y:
                      active_period(id_events=y.id_events,
                                    id_people=y.id_people,
                                    id_domains=y.id_domains,
                                    id_teams=y.id_teams,
                                    id_projects=y.id_projects),
                      axis="columns"))
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
          .assign(
              period_start=lambda x: x.period.apply(lambda y: y[0]),
              period_end=lambda x: x.period.apply(lambda y: y[1]),
              year_start=lambda x: x.year.apply(lambda y: date(y, 01, 01)),
              year_end=lambda x: x.year.apply(lambda y: date(y, 12, 31))))

    #
    # compute coverage, fte, full_name, is_start and is_end
    #
    df = (df
          .assign(

              coverage=lambda x:
LE GAC Renaud's avatar
LE GAC Renaud committed
1061 1062 1063 1064
              coverage(x.start_date,
                       x.end_date,
                       x.year_start,
                       x.year_end),
1065 1066 1067 1068

              full_name=lambda x: full_name(x.first_name, x.last_name),

              is_start=lambda x:
LE GAC Renaud's avatar
LE GAC Renaud committed
1069
              is_start(x.year_start, x.year_end, x.period_start),
1070 1071

              is_end=lambda x:
LE GAC Renaud's avatar
LE GAC Renaud committed
1072
              is_end(x.year_start, x.year_end, x.period_end))
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

          .assign(fte=lambda x: x.coverage * x.percentage * 0.01))

    #
    # aggregate item split during the year and sum the fte
    #
    cols = ["year", "id_domains", "id_projects", "id_teams", "id_people"]
    group = df.groupby(cols)
    dfa = group[["fte"]].aggregate(np.sum).reset_index()
    dfb = df.drop("fte", axis="columns")
    df = (pd.merge(dfa, dfb, on=cols, how="left")
          .drop_duplicates(cols))

    #
    # Clean and keep memory footprint low
    #
1089
    df = (df.drop(["period", "year_start", "year_end"], axis="columns")
1090 1091 1092
          .assign(
              agency=lambda x: pd.Categorical(x.agency),

LE GAC Renaud's avatar
LE GAC Renaud committed
1093 1094
              people_categories_category=lambda x:
              pd.Categorical(x.people_categories_category),
1095

LE GAC Renaud's avatar
LE GAC Renaud committed
1096 1097
              people_categories_code=lambda x:
              pd.Categorical(x.people_categories_code),
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195

              team=lambda x: pd.Categorical(x.team)))

    return df


def get_peoplelike_items_per_year(**kwargs):
    """Return the DataFrame with active items for each year, belonging to the
    event id_event when the event is related to people. An item appears several
    time when it is active during several years.

    The DataFrame contains a reduced set of information for each item, namely
    the meta-data, category, domain, funding, people, project, team information
    as well as the history.data. The latter is a dictionary which is
    "json normalised", one column per key.

    The selection of the item is performed by querying the database.
    The query is built using the keyword arguments.

    The range of years are selected using the arguments ``year_start``
    and ``year_end``. The scan is between ``DATE_MIN`` and/or ``DATE_MAX`` when
    ``year_start`` and/or ``DATE_MIN`` is/are not defined.

    Keyword Args:
        id_events (int): identifier of the event [required]
        id_domains (int):
        id_fundings (int):
        id_people (int):
        id_people_categories (int):
        id_projects (int):
        id_teams (int):
        year_end (date):
        year_start (date):

    Returns:
        pandas.DataFrame:
            The columns of the DataFrame are:

                * id (int): history table identifier for the item
                * id_domains (int)
                * id_events (int)
                * id_fundings (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)

                * agency (str)
                * birth_date (str)
                * domain (str)
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * first_name (str)
                * history_note (str)
                * last_name (str)
                * people_categories_category (str)
                * people_categories_code (str)
                * people_note (str)
                * percentage (int)
                * project (str)
                * start_date (date): undefined dates are forced to ``DATE_MIN``
                * team (str)

                * one column for each key of the history.data dictionary

    """
    return _get_items_per_year(get_peoplelike_items, **kwargs)


def is_end(year_start, year_end, period_end):
    """Vectorized function to determine if the active period end in the year.

    Args
        year_start (Series of date)
        year_end (Series of date)
        period_end (series of date)

    Returns
        Series of boolean

    """
    return (year_start <= period_end) & (period_end <= year_end)


def is_start(year_start, year_end, period_start):
    """Vectorized function to determine if the active period start in the year.

    Args
        year_start (Series of date)
        year_end (Series of date)
        period_start (series of date)

    Returns
        Series of boolean

    """
    return (year_start <= period_start) & (period_start <= year_end)


1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
def normalize_history_data(df):
    """Normalise the JSON field ``history.data``.

    The database field ``history.data`` contains a JSON string serialising
    a dictionary. Each key is transformed into a DataFrame columns which are
    add to the initial DataFrame. The column data is dropped.

    Args:
        df (pandas.DataFrame): the DataFrame has to contains the columns data.

    Returns:
        pandas.DataFrame

    """
    # 1) convert json string into json object for each row
    # 2) convert the data serie into a json string preserving index (split)
    #    Fix the issue with "name":"data" in pandas version 0.18

1214 1215 1216
    sdata = (df.data
             .fillna("{}")
             .apply(lambda x: json.loads(x))
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
             .to_json(orient="split")
             .replace('"name":"data",', ""))

    # 3) convert the json string into a dataframe, with a column for each key
    # 4) fix possible wrong boolean value
    # 5) merge dataframe using index
    # 6) drop the obsolete columns data

    df = (pd.read_json(sdata, orient="split")
          .replace("false", False)
          .replace("true", True)
          .merge(df, left_index=True, right_index=True, how="right")
          .drop("data", axis="columns"))

    return df


1234 1235
def query_history(db, **kwargs):
    """Build the query for the history table from the keyword arguments.
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
    The operator AND is applied between the conditions.

    Args:
        db (gluon.dal.DAL): database connection.

    Keyword Args:
        id_events (int):
        id_domains (int):
        id_fundings (int):
        id_objects (int):
1246
        id_object_code (int): select object per category.code
1247
        id_people (int):
1248
        id_people_code (int): select people per category.code (quality)
1249 1250
        id_projects (int):
        id_teams (int):
1251 1252
        object_categories_category (str): select object per category
        people_categories_category (str): select people per category
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        year_end (date):
        year_start (date):

    Returns:
        gluon.DAL.Query

    """
    history = db.history
    query = None

1263 1264 1265
    di = {k: kwargs[k] for k in HISTORY_QUERY_FIELDS if k in kwargs}

    for k, v in di.iteritems():
1266

1267
        if (v in ('', None)) or (k == "data"):
1268 1269 1270
            continue

        if k == "year_end":
1271
            year_end = date(int(di["year_end"]), 12, 31)
1272 1273 1274
            qi = history.start_date <= year_end

        elif k == "year_start":
1275
            year_start = date(int(di["year_start"]), 01, 01)
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
            qi = (history.end_date == None) | (history.end_date >= year_start)

        elif k == "id_object_code":
            qi = history.id_object_categories == int(v)

        elif k == "object_categories_category":
            object_cats = db.object_categories
            cat_ids = db(object_cats.category == v)._select(object_cats.id)
            qi = history.id_object_categories.belongs(cat_ids)

        elif k == "id_people_code":
            qi = history.id_people_categories == int(v)

        elif k == "people_categories_category":
            people_cats = db.people_categories
            cat_ids = db(people_cats.category == v)._select(people_cats.id)
            qi = history.id_people_categories.belongs(cat_ids)
1293 1294 1295 1296 1297 1298 1299

        else:
            qi = history[k] == v

        query = (qi if query is None else (query) & (qi))

    return query
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323


class Timer(object):
    """Utility to time a part of the code.
    From https://www.huyng.com/posts/python-performance-analysis

    Example::

        with Timer("build data frame for RH") as t:
            df = get_human_resources("LHCb", 2014, 2018)

    """
    def __init__(self, msg):
        self.msg = msg

    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.end = time.time()
        self.secs = self.end - self.start
        self.msecs = self.secs * 1000  # millisecs
        print '\n%s\n\telapsed time: %f ms' % (self.msg, self.msecs)
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358


def to_extjs_gridcolumns(df):
    """Introspect the DataFrame in order to derive configuration for
    ``Ext.grid.column.Column`` which are used by an ``Ext.grid.Panel``.

    Note:
        * The first columns shows the row number.
        * The type of the grid column is derived from the DataFrame.dtype
          as well as from the name of the DataFrame column.
        * The default xtype ``gridcolumn`` is used for string and for
          dtype == object which are not resolved. Later, the user can tune
          the column type.

    Args:
        df (pandas.DataFrame):

    Returns:
        list:
            configuration are stored in a dictionary.

    """
    li = [dict(xtype="rownumberer")]

    cfgcol = Storage(dataIndex="",
                     flex=1,
                     hidden=False,
                     text="",
                     xtype="gridcolumn")

    for colname, coltype in df.dtypes.sort_index().iteritems():
        cfg = Storage(cfgcol)

        cfg.dataIndex = cfg.text = colname

LE GAC Renaud's avatar
LE GAC Renaud committed
1359
        if colname.startswith("id"):
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
            cfg.flex = 0.5
            cfg.format = "0"
            cfg.hidden = True
            cfg.xtype = "numbercolumn"

        elif coltype in (np.int8, np.int16, np.int32, np.int64):
            cfg.format = "0"
            cfg.xtype = "numbercolumn"

        elif coltype in (np.float16, np.float32, np.float64):
1370 1371
            cfg.formatter = "round(2)"
            cfg.summaryFormatter = "round(2)"
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
            cfg.summaryType = "sum"
            cfg.xtype = "numbercolumn"

        elif coltype == np.bool_ or colname.startswith("is"):
            cfg.falseText = "False"
            cfg.trueText = "True"
            cfg.xtype = "booleancolumn"

        elif coltype == np.datetime64 or colname in ("date",
                                                     "end_date",
                                                     "period_end",
                                                     "period_start",
                                                     "start_date"):
            cfg.format = "Y-m-d"
            cfg.xtype = "datecolumn"

        li.append(cfg)

1390
    return li