dataframes.py 45.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
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
41
    end of the period of activity are shown by the `^`::
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

    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
72
    rows = db.executesql(db(query)._select(*fields))
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

    # 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
97 98
    coverage = \
        np.minimum(end_date, year_end) - np.maximum(start_date, year_start)
99 100 101 102

    return coverage / (year_end - year_start)


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
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)


161 162
def debug_df(df, opt=""):
    """Helper tool to debug a DataFrame.
163

164 165 166
    Args
        df (pandas.DataFrame):
        opt (str): debug options:
LE GAC Renaud's avatar
LE GAC Renaud committed
167

168 169 170 171 172 173
            * ``a``: equivalent to icIht
            * ``c``: show columns
            * ``I``: show index
            * ``h``: show head
            * ``t``: show tail
            * ``f``: show the whole dataframe
174

175 176 177 178 179 180
    """
    if "i" in opt or "a" in opt:
        df.memory_usage()
        print df.info()

    if "c" in opt or "a" in opt:
181
        print df.columns.sort_values()
182 183 184 185 186 187 188 189 190 191 192 193 194 195

    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


196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
def elapse_time(start_date, end_date, xdate):
    """Vectorized function to compute the elapse time between the starting date
    and xdate or end_date:

        * it is computed between the start_date and the end_date
          when the end_date is above xdate
        * otherwise it is computed between the start_date and xdate

    Args:
        start_date (pandas.Series): starting date for items
        end_date (pandas.Series): ending date for items
        xdate (date)

    Returns:
        pandas.Series:
            with the timedelta in days

    """
    return end_date.mask(end_date > xdate, xdate) - start_date


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
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=" ")


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
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


313
def get_items(**kwargs):
314 315
    """Return the DataFrame with active items belonging to the event id_event.

316 317 318 319
    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.
320 321 322 323 324 325

    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``.
326 327

    Keyword Args:
328
        id_events (int): identifier of the event [required]
329 330 331 332 333 334 335 336 337 338 339 340
        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:
341 342 343 344 345 346
        pandas.DataFrame:
            The index of the DataFrame is the history table identifier.
            The columns of the DataFrame are:

                * id_domains (int)
                * id_events (int)
347
                * id_fundings (int)
348 349 350 351 352 353
                * id_objects (int)
                * id_objects_categories (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)
354 355 356 357 358

                * agency (str)
                * batch_number (str)
                * birth_date (str)
                * domain (str)
359
                * duration (float): in days
360 361 362 363 364 365 366 367 368 369 370 371 372 373
                * 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)
374
                * start_date (date): undefined dates are forced to ``DATE_MIN``
375 376 377
                * team (str)

                * one column for each key of the history.data dictionary
378 379 380 381 382

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

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

386 387 388 389 390 391 392 393 394
    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

395 396 397 398 399 400
    # fields to be extracted from the database
    fields = [
        history.id,
        history.id_domains,
        history.id_events,
        history.id_fundings,
401
        history.id_objects,
402 403 404 405 406
        history.id_object_categories,
        history.id_people,
        history.id_people_categories,
        history.id_projects,
        history.id_teams,
407 408 409
        history.data,
        history.note,
        history.percentage,
410 411
        history.start_date,
        history.end_date,
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        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]
428 429

    # columns name for the DataFrame
430
    # resolve ambiguities for code, category and note
431
    columns = get_column_names(fields)
432 433 434 435 436 437

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

441 442 443
    df["duration"] = (elapse_time(df.start_date, df.end_date, date.today())
                      .apply(lambda x: x.days))

444 445 446
    return df


447 448 449
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
450 451
    is active during several years.

452 453 454 455
    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.
456

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

460 461 462
    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.
463

464 465 466 467 468 469 470 471 472 473
    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):
474
        year_end (date):
475
        year_start (date):
476 477 478

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

481 482 483 484 485 486 487 488 489 490
                * 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)
491

492 493 494 495
                * agency (str)
                * batch_number (str)
                * birth_date (str)
                * domain (str)
496
                * duration (float): in days
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
                * 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)
513

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

516
    """
517
    return to_items_per_year(get_items, **kwargs)
518 519


520 521
def get_items_small(**kwargs):
    """Return the DataFrame with active items belonging to the event id_event.
522 523

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

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

530 531
    Active items are selected using the arguments ``year_start``
    and ``year_end``.
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547

    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:
548
            The index of the DataFrame is the history table identifier.
549 550 551 552
            The columns of the DataFrame are:

                * id_domains (int)
                * id_events (int)
LE GAC Renaud's avatar
LE GAC Renaud committed
553
                * id_fundings (int)
554 555 556 557 558 559
                * id_objects (int)
                * id_objects_categories (int)
                * id_people (int)
                * id_people_categories (int)
                * id_projects (int)
                * id_teams (int)
560

561
                * duration (float): in days
562
                * end_date (date): undefined dates are forced to ``DATE_MAX``
563 564
                * start_date (date): undefined dates are forced to ``DATE_MIN``

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

567 568 569
    """
    db = current.globalenv['db']
    history = db.history
570

571 572
    # database query
    query = query_history(db, **kwargs)
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
    # 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)))

601 602 603
    df["duration"] = (elapse_time(df.start_date, df.end_date, date.today())
                      .apply(lambda x: x.days))

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
    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)

650
                * duration (float): in days
651 652 653 654 655 656 657
                * 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

    """
658
    return to_items_per_year(get_items_small, **kwargs)
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


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)
703
                * duration (float): in days
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
                * 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
756
    columns = get_column_names(fields)
757 758 759 760 761 762 763 764 765

    # 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)))

766 767 768
    df["duration"] = (elapse_time(df.start_date, df.end_date, date.today())
                      .apply(lambda x: x.days))

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
    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)
816
                * duration (float): in days
817 818 819 820 821 822 823 824 825 826 827 828 829 830
                * 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

    """
831
    return to_items_per_year(get_objectlike_items, **kwargs)
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


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)
876
                * duration (float): in days
877 878
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * first_name (str)
879
                * full_name(str)
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
                * 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
934
    columns = get_column_names(fields)
935 936 937 938 939 940

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

945 946 947
    df["duration"] = (elapse_time(df.start_date, df.end_date, date.today())
                      .apply(lambda x: x.days))

948 949 950
    return df


951 952 953 954 955 956
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
957 958 959 960
    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.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

    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):
1023
                * period_duraton (float): in days
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
                * 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

1037
    df = (to_items_per_year(get_peoplelike_items, **kwargs)
1038
          .drop("duration", axis="columns")
1039 1040
          .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

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

1101 1102 1103 1104
    df["period_duration"] = \
        (elapse_time(df.period_start, df.period_end, date.today())
         .apply(lambda x: x.days))

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
    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)
1152
                * duration (float): in days
1153 1154
                * end_date (date): undefined dates are forced to ``DATE_MAX``
                * first_name (str)
1155
                * full_name (str)
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
                * 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

    """
1169
    return to_items_per_year(get_peoplelike_items, **kwargs)
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 1196 1197 1198 1199 1200 1201


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)


1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
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

1220 1221 1222
    sdata = (df.data
             .fillna("{}")
             .apply(lambda x: json.loads(x))
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
             .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


1240 1241
def query_history(db, **kwargs):
    """Build the query for the history table from the keyword arguments.
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    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):
1252
        id_object_code (int): select object per category.code
1253
        id_people (int):
1254
        id_people_code (int): select people per category.code (quality)
1255 1256
        id_projects (int):
        id_teams (int):
1257 1258
        object_categories_category (str): select object per category
        people_categories_category (str): select people per category
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
        year_end (date):
        year_start (date):

    Returns:
        gluon.DAL.Query

    """
    history = db.history
    query = None

1269 1270 1271
    di = {k: kwargs[k] for k in HISTORY_QUERY_FIELDS if k in kwargs}

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

1273
        if (v in ('', None)) or (k == "data"):
1274 1275 1276
            continue

        if k == "year_end":
1277
            year_end = date(int(di["year_end"]), 12, 31)
1278 1279 1280
            qi = history.start_date <= year_end

        elif k == "year_start":
1281
            year_start = date(int(di["year_start"]), 01, 01)
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
            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)
1299 1300 1301 1302 1303 1304 1305

        else:
            qi = history[k] == v

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

    return query
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329


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)
1330 1331


LE GAC Renaud's avatar
LE GAC Renaud committed
1332
def to_extjs_gridcolumns(df, meta=False):
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    """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):
LE GAC Renaud's avatar
LE GAC Renaud committed
1346
        meta (bool): add column with metadata identifier when true
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

    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
1366
        if colname.startswith("id"):
LE GAC Renaud's avatar
LE GAC Renaud committed
1367 1368 1369
            if not meta:
                continue

1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
            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):
1380 1381
            cfg.formatter = "round(2)"
            cfg.summaryFormatter = "round(2)"
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
            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)

1400
    return li
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444


def to_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

    """

    is_start = \
        "year_start" in kwargs and kwargs["year_start"] not in (None, '')

    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