Interface ModelCalcFormulaContext

All Superinterfaces:
DistFormulaContext, ModelFormulaContext

public interface ModelCalcFormulaContext extends ModelFormulaContext
The ModelCalcFormulaContext is exposed to model logics through the model binding, when calculating a model.
cf. ModelFormulaContext for details on model definition and evaluation vs. model calculation.
  • Method Details

    • findCalcItems

      List<?> findCalcItems(Object key1)
      Deprecated.
      Parameters:
      key1 -
      Returns:
    • findCalcItem

      Object findCalcItem(Object key1, Object key2)
      Deprecated.
      Parameters:
      key1 -
      key2 -
      Returns:
    • addTree

      Long addTree(String treeName, Collection<String> levelNames)
      Adds a tree to this model, which is effectively a FilterNode object that acts as the root of the tree, i.e. one that does not point to a parent FilterNode. The levelNames are persisted in the FilterNode.output attribute, later used to construct a more readable map representation of the node's path (see ModelFormulaContext.getFilterNodePath() and ModelFormulaContext.getFilterNodePath(Long).
      If a tree with the given name already exists, the id of the root node is returned, and no further action is taken.
      Parameters:
      treeName - Name to be set on the root node (FilterNode.name)
      levelNames - Names of the first, second etc. level of the tree
      Returns:
      The id of the root node of the tree
    • addTree

      List<Long> addTree(String treeName, Matrix2D data, Collection<String> levelCols)
      Adds a tree to this model, consisting of nodes constructed from a data set, usually a PA query result.
      The root node is the same as created by addTree(String, Collection).
      The immediate descendents of the root node are created from the values found in the first level column (as dictated by the levelCols argument).
      The second level descendants are created from the values in the second level column, if any. And so on.

      Example: creating a tree with name 'Segments' from data set

       Region,        Channel
       EMEA,  Retail
       APAC,  Retail
       APAC,  Industry
       

      results in the following tree, when the level columns are chosen to be 'Region' and 'Channel', in that order.

       Segments
            |
               + EMEA
               |    |
               |    + Retail
               |
               + APAC
                    |
                        + Retail
                        |
                        + Industry
       


      If a tree with the given name already exists, it is deleted before the new one is created.
      Parameters:
      treeName - Name of the tree to be created, i.e. FilterNode.name of the root node
      data - Data from which to construct the tree
      levelCols - Labels of the columns in data to be used to 1) name the tree levels and 2) identify the column to populate each level from
      Returns:
      All of the added tree nodes' ids
    • addTree

      List<Long> addTree(String treeName, Matrix2D data, Collection<String> levelCols, Collection<String> labelCols, String outputColName, String outputColFormat)
      Creates or replaces a tree as in addTree(String, Matrix2D, Collection), with the additional specification of an output or output format, and/or labels. Whereas in the previous method tree nodes are created with FilterNode.output == null and Filter.label -- null, this method sets:

      • output field to the value found in the column identified by outputColName (== column label). If outputColName is null and outputColFormat is not, then the output value is constructed as String.format(outputColFormat, n);, with n being the (n-1)th node created (i.e. n=0 for the root node).
      • label field to "[val1, val2, ...]" where val1, val2, ... are the values found in the columns identified by labelCols respectively.

      Parameters:
      treeName - Name of the tree to be created, i.e. FilterNode.name of the root node
      data - Data from which to construct the tree
      levelCols - Labels of the columns in data to be used to 1) name the tree levels and 2) identify the column to populate each level from
      labelCols - Labels of the columns in data from which to construct the label (sets FilterNode.label)
      outputColName - Label of the column in data from which to pick the output value (sets FilterNode.output)
      outputColFormat - The format from which to construct the output value when outputColName == null
      Returns:
      All of the added tree nodes' ids
    • deleteTree

      void deleteTree(String treeName)
      Deletes the tree with the given name, if it exists. No action is taken and no error returned if it doesn't. Note that deleting a tree means deleting the root node as well as all of its direct and indirect descendents.
      Parameters:
      treeName - Name of the tree, i.e. name of root FilterNode, to delete
    • addTreeNode

      Long addTreeNode(Long parentId, String name, String label, String output, Filter filter)
      Adds a descendent to an existing tree node, identified by its parentId.
      If the parent node does not exist, no action is taken and no error is returned.
      Parameters:
      parentId - Id of the parent node
      name - To be FilterNode.name (of the added node)
      label - To be FilterNode.label
      output - To be FilterNode.output
      filter - To be FilterNode.filter
      Returns:
      The id of the added tree node, or null if the parent node doesn't exist
    • addRecord

      Object addRecord(String name, CalendarUtil.TimePeriod period, Map<String,?> attributeValues, Map<String,FieldFormatType> fieldFormatTypesByColLabel, boolean... calculate)
      Adds a new record with the given name if none exist yet with that name in the DRAFT status (workflowStatus == WorkflowStatus.DRAFT). Otherwise, that existing record is updated instead. Note that there can be multiple records with the same name, as long as there is only one in the DRAFT state. Usually these records will then also have varying validity periods (for ex. one valid and approved for Q1, with a new one, yet to be approved for Q2).
      Parameters:
      name - Name of the record to be added/updated.
      period - The validity period for the record, i.e. defining its startDate and endDate (both inclusive)
      attributeValues - Map of attribute (label, value) pairs. Note that this is a map from the field's label (not name)
      fieldFormatTypesByColLabel - Map of attribute (label, FieldFormatType), defining the type of each record attribute to be set. Entries in the attributeValues argument for which no FieldFormatType is defined, are ignored, i.e. are not set.
      calculate - Optional flag, indicating that once the record is added/updated, a second, embedded, evaluation takes place, in which the record being calculated is identified by the result of getRecord(). See also the MethodType.recordLogic property.
      Returns:
      A map representation of the added/updated ModelRecord
    • getRecord

      Map<String,Object> getRecord()
      Gets the ModelRecord ('PolicyRecord' in the UI) set as context in the 'record' logic evaluation (the logic set in the ModelType.recordLogic attribute). The evaluation is done when a record is added using addRecord(String, TimePeriod, Map, Map, boolean...) when the calculate argument is true.
      Specified by:
      getRecord in interface ModelFormulaContext
      Returns:
      A map representation of the ModelRecord
    • deleteRecords

      int deleteRecords()
      Deletes all ModelRecords associated with the model, which are not yet submitted into the workflow.
      Returns:
      The number of records created.
    • addOrUpdateCalcItem

      Object addOrUpdateCalcItem(Object calcStep, Object id, Object value)
      Creates a new or updates an existing calculation item (entry in the Model CalcItems PP) for a given calculation step. For example, a 'Segmentation' step may create a CalcItem for scoring 'Segment 001', injected into the logic context when the calculation of the 'Scoring' step for that segment is initiated.
      Parameters:
      calcStep - The name of the calculation step in which the added item is to be calculated; this goes into Key1
      id - Key2 of the calculation item
      value - A JSON-serializable value to be stored in the Value attribute of the calculation item
      Returns:
    • addTable

      DatamartContext.Table addTable(String tableName, Object source) throws Exception
      Creates a table, represented by a DMTable object in the PA DB, modelled on and populated from the given source.
      The uniqueName of the table is a combination of the model's typedId and the passed in tableName. The table's label is set to the given tableName or from the source.
      If a DMTable with this tableName (i.e. with equal derived uniqueNames) already exists, that table is updated and truncated rather than dropped and recreated. If this is not desirable, then the existing table can be dropped beforehand.
      Note that when directly using a DatamartContext.SqlQuery, the types of the selected fields must be made explicit via casting for the resulting table to have the proper types.
      If a query is passed as a source, the projections become the fields of the new/updated table, and the result is used to populate the table.

      Note: Can only be used in a model calculation.


      Sample code:
      
            def ctx = api.getDatamartContext()
                  def ds = ctx.getDataSource("txDS")
                  def t1 = ctx.newQuery(ds)
                  t1.select("sku", "P")
                  t1.select("SUM(amount)", "R")
                  def query = ctx.newSqlQuery()
                  query.addSource(t1)
                  query.setQuery('SELECT P, R::numeric as R FROM T1 ORDER BY P')
                  // add table using a query definition
                  model.addTable('MyTable', query)
                  // add table using fields definitions
                  model.addTable("RevenueByProduct", [
                     [ name:"productId", label:"Product ID", type:"TEXT", key:true],
                     [ name:"productGroup", label:"ProductGroup", type:"TEXT", dimension:true],
                     [ name:"revenue", label:"Revenue", type:"MONEY"]
            ])
                  // add table using full definitions
                  model.addTable("RevenueByProduct", [
                          label: "Revenue By Product",
                    fields: [
                        [ name:"productId", label:"Product ID", type:"TEXT", key:true],
                        [ name:"productGroup", label:"ProductGroup", type:"TEXT", dimension:true],
                        [ name:"revenue", label:"Revenue", type:"MONEY"],
                    ]
            ])
       
      Parameters:
      tableName - The name of the table, unique over all tables associated to this model.
      source - One of the following types
      Note: For table field types, please refer to Enum FieldType

      .

      Returns:
      A DatamartContext.Table object that can be used as a source to a query in the DatamartContext. It is the same DatamartContext.Table object that can be retrieved using ModelFormulaContext.getTable(String).
      Throws:
      Exception - in case of error.
    • loadTable

      long loadTable(DatamartContext.Table table, Object source) throws Exception
      Load data into an existing table without truncating it.
      The the projections of the query passed as a source must match the fields of the table, and the result of the query is used to populate the table.
      Note that when directly using a DatamartContext.SqlQuery, the types of the selected fields must be made explicit via casting for the resulting table to have the proper types.

      Note: Can only be used in a model calculation.


      Sample code:
      
            def ctx = api.getDatamartContext()
                  def ds = ctx.getDataSource("txDS")
                  def t1 = ctx.newQuery(ds)
                  t1.select("sku", "P")
                  t1.select("SUM(amount)", "R")
                  def query = ctx.newSqlQuery()
                  query.addSource(t1)
                  query.setQuery('SELECT P, R::numeric as R FROM T1 ORDER BY P')
                  // load table using a query definition
                  def table = model.getTable('MyTable')
                  model.loadTable(table, query)
       
      Parameters:
      table - The table object, see ModelFormulaContext.getTable(String) or addTable(String, Object) to retrieve it.
      source - One of the following query types
      Returns:
      The number of row added.
      Throws:
      Exception - in case of error.
    • loadTable

      long loadTable(DatamartContext.Table table, Object source, boolean truncate) throws Exception
      Load data into an existing table, optionally truncating it.
      The the projections of the query passed as a source must match the fields of the table, and the result of the query is used to populate the table.
      Note that when directly using a DatamartContext.SqlQuery, the types of the selected fields must be made explicit via casting for the resulting table to have the proper types.

      Note: Can only be used in a model calculation.


      Sample code:
      
            def ctx = api.getDatamartContext()
                  def ds = ctx.getDataSource("txDS")
                  def t1 = ctx.newQuery(ds)
                  t1.select("sku", "P")
                  t1.select("SUM(amount)", "R")
                  def query = ctx.newSqlQuery()
                  query.addSource(t1)
                  query.setQuery('SELECT P, R::numeric as R FROM T1 ORDER BY P')
                  // load table using a query definition
                  def table = model.getTable('MyTable')
                  model.loadTable(table, query, true)
       
      Parameters:
      table - The table object, see ModelFormulaContext.getTable(String) or addTable(String, Object) to retrieve it.
      source - One of the following query types
      truncate - If the table should be truncated before loading the data.
      Returns:
      The number of row added.
      Throws:
      Exception - in case of error.
    • dropTable

      boolean dropTable(String tableName)
      Drops the table, uniquely identified by tableName within this model.

      Note: Can only be used in a model calculation.


      Sample code:
      
                  model.dropTable('MyTable')
       
      Parameters:
      tableName - The table name.
      Returns:
      True if that table existed, false otherwise.
    • truncateTable

      void truncateTable(DatamartContext.Table table)
      Truncate the table.

      Note: Can only be used in a model calculation.


      Sample code:
      
            def table = model.getTable('MyTable')
            model.truncateTable(table)
       
      Parameters:
      table - The table.
    • getDataLoader

      Returns: