t r
U U
t h
About Trwth Guide Introduction Quick Start Guide Core Components Formulas App Configuration Advanced Features Troubleshooting FAQ Contact Support

Introduction

Trwth is a lightweight JavaScript framework designed to simplify the creation of data-driven single-page applications (SPAs). It empowers both programmers and non-programmers to build efficient, secure, and dynamic applications with ease. By engaging AI and focusing on transparency, extensibility, and connectedness, Trwth allows industries like banking, healthcare, and insurance to transition from complex legacy systems to more agile development environments. Trwth provides users the straightforward what, who, why, and wheres.

Quick Start Guide

This Quick Start guide will walk you through setting up Trwth and building & running a simple application. You'll learn how to:

Let's get started!

Step 1: Download the Trwth Framework

1.1 Visit the Trwth GitHub Repository

Open your web browser and navigate to the Trwth GitHub repository.

1.2 Download the Repository

  1. Click the green "Code" button located near the top right corner.
  2. Select "Download ZIP" from the dropdown menu.
  3. Save the ZIP file to a directory of your choice on your computer.

Step 2: Extract and Set Up the Framework

2.1 Extract the ZIP File

  1. Navigate to the directory where you saved the ZIP file.
  2. Right-click the ZIP file and select "Extract All..." or use your preferred extraction tool.
  3. Choose a destination folder for the extracted files.

2.2 Explore the Framework Directory

Open the extracted folder. You should see directories like /apps, /libraries, and others. The /apps directory contains sample applications organized in subdirectories, including the Quickstart.html file you will find in the /demos directory which we'll use.

Step 3: Prepare the Sample Data

3.1 Obtain the Test Data File

Ensure you have a test data file named random_generated_loan_data.csv in the /data directory. This CSV file should contain randomly generated loan data that the Quiskstart application will use.

If you don't have this file, create a simple CSV with headers like Portfolio, Branch, Principal, OpenDate, etc., and add some sample data.

3.2 Place the Data File

  1. Copy random_generated_loan_data.csv into the /data directory within the Trwth framework folder if it's not already in the \data folder.

Your directory structure should look like:

/trwth
          /apps
          /core
          /data
            random_generated_loan_data.csv
          /libraries
          ...
        

You can leave random_generated_loan_data.csv in \data or you can copy it to another secure local folder. Note: All data processing and storage occur locally on the user’s machine, minimizing the risk of data breaches. By keeping data within the local environment, Trwth prevents unauthorized access and interception that can occur during data transmission over networks.

Step 4: Start with a Simple Application

4.1 Open the Quickstart Application

  1. Navigate to the /apps/demos directory.
  2. Find and open the Quickstart.html file in your favorite text editor (Visual Studio, Sublime, etc).

4.2 Review the App Configuration

In Quickstart.html, locate the <script> section where appConfig is defined. Here's the code for reference:

const appConfig = { libraries: [ 'financial', 'organization' ], formula: 'loan.open > "2020-10-31" & loan.open < "2024-11-03" ? loan.averageBalance : null', groupBy: 'portfolio', presentation: { columns: [ { heading: 'Branch', field: 'branch' }, { heading: 'Officer', field: 'owner' } ], } };

Explanation:

4.3 Save the Changes

If you made any changes to appConfig, save your changes to Quickstart.html in your text editor.

Step 5: Run the Application

5.1 Open the Application in a Browser

  1. Double-click Quickstart.html to open it in your default web browser.
  2. Alternatively, right-click the file, select "Open with", and choose your preferred browser.

5.2 Interact with the Application

The application should load, provide a button to select loan source where you select test_loan_data.csv, and click run. You should see a table or presentation of data showing the Branch and Principal for loans that meet the criteria specified in your formula.

Result
200106555 (2)2392$1,212,609.43
200102722 (1)2392$313,590.84

Core Components

Understanding the core components of Trwth is essential for building robust and efficient applications. These components work together to handle data processing, logic execution, and presentation within your single-page applications (SPAs).

1. Formulas

Formulas are the heart of Trwth, defining and evaluating the logic of applications and data transformations using a human-readable syntax.

Example Formula:

loan.open > "2020-10-31" && loan.open < "2024-11-03" ? loan.principal : null

This formula checks if the loan's open date is between October 31, 2020, and November 3, 2024. If true, it returns the loan principal; otherwise, it returns null.

2. Functions

Functions in Trwth are reusable JavaScript functions used for calculations or data manipulation within your application.

Example Function:

const functions = {
  loanPayment: {
    description: "Calculates the monthly loan payment based on principal, annual rate, and amortization months",
    implementation: function(principal, annualRate, amortizationMonths) {
      const monthlyRate = annualRate / 12;
      const payment = principal * (monthlyRate / (1 - Math.pow(1 + monthlyRate, -amortizationMonths)));
      return payment.toFixed(2);
    }
  }
};

This function calculates the monthly loan payment based on the principal amount, annual interest rate, and the number of amortization months.

3. Attributes

Attributes are constants or fixed values used throughout the application. They provide essential data points that can be referenced in formulas and functions.

Example Attribute:

const attributes = {
  loanServicingFactor: {
    description: "Factor used to calculate loan servicing costs",
    value: 0.0025,
  }
};

This attribute defines a servicing factor used in calculating loan servicing expenses.

4. Dictionaries

Dictionaries are key-value pairs used for data lookups and mappings. They allow for flexible data retrieval and manipulation based on predefined keys.

Example Dictionary:

annualOperatingExpense: { checking: { description: "The checking account annual operating costs", values: { "Consumer": 112, "Business": 145 } }, savings: { description: "The savings account annual operating costs", values: { "Consumer": 28, "Business": 56 } } }

This dictionary maps various loan types to their respective identifiers, facilitating easy lookups within formulas and functions.

5. Libraries

Libraries are collections of functions, attributes, and dictionaries organized for specific functionalities. They help maintain code organization and reusability.

Example Library Structure:

const libraries = {
  financial: {
    functions: { /* Financial functions here */ },
    attributes: { /* Financial attributes here */ },
    dictionaries: { /* Financial dictionaries here */ },
  },
  organization: {
    functions: { /* Organization functions here */ },
    attributes: { /* Organization attributes here */ },
    dictionaries: { /* Organization dictionaries here */ },
  }
};

In this example, the `financial` library contains functions, attributes, and dictionaries related to financial operations, while the `organization` library manages organization-specific data.

Integration of Core Components

These core components interact seamlessly within Trwth to process data, execute logic, and present results. Here's how they work together:

By understanding and effectively utilizing these core components, you can harness the full power of Trwth to build sophisticated and scalable applications.


Formulas

In the Trwth.js framework, formulas serve as the core mechanism that connects data with functions, enabling powerful interactions. They allow users to perform dynamic calculations across multiple data sources, execute complex financial and analytical operations, and deliver results to defined outputs—all within a consistent, no-code, no-SQL, and human-readable syntax. Before diving deeper, let’s explore the syntax that makes it all possible.

In Trwth.js, formulas act as the kernel of the framework, coordinating the interaction between raw data, advanced operations, and outputs. As the foundation of the system, formulas provide:

  1. Central Coordination: Directing how data flows and is processed from sources to outputs.
  2. Simplified Abstraction: Translating simple syntax into complex computations.
  3. Dynamic Adaptability: Adjusting to various operations, from simple functions to AI-powered insights.
  4. Empowered Accessibility: Allowing users of all technical levels to harness powerful data interactions without needing code or SQL.

Formulas act as the Kernel

Secure Environment

Data Files

Form Content

Data Streams

Functions

Advanced Operations

AI

API Calls

Results in Browser

Trwth.js formulas extract data from local sources securely; leverage lirbraies of functions, advanced operations, AI, and/or API integrations; and deliver dynamic results to the browser in real time. All operations in Trwth.js reside securely within your organization's local infrastructure. Data remains protected while formulas extract, process, and deliver insights.

Let's start with this example:
{{ !loan.risk == 'low' }} ? loan.profit - loan.principal * 0.05 : loan.profit

Secure Environment

loan.csv

Profit
Function

! {{ }} - == *
Operations

AI

Treasury API

Results in Browser

Understanding Variables in Formulas

Variables in Trwth.js formulas represent data fields or properties derived from your data sources. They allow formulas to perform operations based on the values of these fields. Here's a breakdown of how to define and use these variables:

1. Data Sources and Fields

Variables such as loan.open are structured as source.field, where:

To define these variables, ensure that your data sources are correctly configured in your single page application and that each source contains the necessary fields.

When working with formulas in Trwth.js, it's crucial to understand how to reference your data sources. For detailed instructions on importing and setting up your data, refer to the Setting Up Data Sources section.

2. Metric Properties: Units and Tally

In your formula, variables like units and tally are built-in metric properties used by Trwth.js.

Defining Units

Units represent the total number of instances of the groupBy field that have been combined or aggregated.

Defining Tally

Tally counts the number of instances within each groupBy field that have a valid result according to the formula.

3. Defining Variables in Formulas

Trwth.js intuitively connects the data sources required by the formula based on the variable names in formula, for instance;

  formula: 'tally == units && loan.class in [1, 20] && loan.open > "2024-01-01" && loan.open <= "2024-11-03" ? loan.principal : null',
  groupBy: 'Portfolio',
  ...

Trwth.js Supported Formula Syntax

Arithmetic Operations (JavaScript)

Logical NOT

The ! operator is known as the logical NOT operator. It's used to invert the boolean value of an operand. Here’s a quick rundown of how it works: Logical NOT (!): If the operand is true, the result is false, and if the operand is false, the result is true.

Conditional (Ternary) Operators (JavaScript)

Operators that take three operands— a condition followed by a question mark ?, then an expression to execute if the condition is truthy, followed by a colon :, and finally the expression to execute if the condition is falsy. Conditional expressions allow for decision-making:

Format:
condition ? expressionIfTrue : expressionIfFalse
Example:
loan.amount > 50000 ? loan.profit : null

Note the condition uses > in this code. The > comparison in our framework and most porgamming environments is an evaluation of two values to determine their relationship. This can involve checking if they are equal, not equal, greater than, less than, greater than or equal to, or less than or equal to each other. Here are the main types of comparison operators:

Another Example:
checking.daysSinceOpen < 90 ? checking.balance : null

In this example, if the checking account has been open for less than 90 days (checking.daysSinceOpen < 90) include the checking account balance in the result (? checking.balance) else include nothing for this account in the final result (: null)

Comparison Operators:

Array Membership (Set Inclusion) Operator

The 'in' operator enables set inclusion testing, allowing you to check if a value belongs to a predefined set:

Format:
value in [set]
Example:
loan.class in [30, 40, 50] ? loan.amount : null //loan.class is 30, 40, or 50
logical NOT operator Example:
!loan.class in [30, 40, 50] ? loan.amount : null //loan.class NOT 30, 40, or 50

Date Handling in Formulas

Formulas can process date conditions by calculating day differences:

Format:
dateField > "YYYY-MM-DD", dateField < "MM/DD/YYYY", etc.
Example:
loan.open > "2023-07-15" & loan.open < "2023-12-31" ? loan.profit : null

Truth Propagation with Conditional Locks

Truth propagation allows certain conditions to “lock” all other conditions within the formula to true once any one condition evaluates as true. Use double curly braces {{ }} to define such locks:

Format:
{{ condition }}
Example:
{{ loan.risk == 'high' }} ? loan.principal * 0.05 : loan.principal

Properties in Trwth.js

In Trwth.js, Properties are essential elements that define how data is managed, processed, and presented within your single-page applications (SPAs). Properties are categorized into two primary types:

  1. Presentation Properties
  2. Metrics Properties (Units and Tally)

Understanding these categories and their roles will enable you to effectively configure and visualize your data-driven applications.

1. Presentation Properties

Presentation Properties dictate how data is displayed to the end-user. They are primarily used within the presentation section of the appConfig to define the structure and content of the data presentation layers, such as tables or charts.

Structure
const appConfig = {
  presentation: {
    columns: [
      { heading: 'Branch', field: 'branch' },
      { heading: 'Type', field: 'class' },
      { heading: 'Zip', field: 'zip' },
      { heading: 'Birth Year', field: 'birth' },
      { heading: 'Gender', field: 'customer.gender' }
    ],
  },
};

Components

Example

const appConfig = {
  presentation: {
    columns: [
      { heading: 'Branch', field: 'branch' },
      { heading: 'Principal', field: 'principal' },
    ],
  },
};

In this example:

2. Properties

Metrics Properties provide quantitative insights into the data by tracking and summarizing specific aspects. In Trwth.js, the primary metrics properties are units and tally.

2.1 Units

Units represent the total number of instances of a particular groupBy field that have been combined or aggregated within the application.

Purpose
Example
const appConfig = {
  metrics: {
    units: 'Portfolio',
  },
};

In this example:

2.2 Tally

Tally counts the number of instances within each groupBy field that have a valid result according to the specified formula.

Purpose
Example
const appConfig = {
  metrics: {
    units: 'Portfolio',
    tally: 'Portfolio',
  },
};

In this example:

Logic Behind Units and Tally

  1. Units:
    • Definition: Total instances of the groupBy field.
    • Calculation: Counts all unique groups based on the groupBy field.
    • Use Case: Provides a high-level overview of how data is distributed across different groups.
  2. Tally:
    • Definition: Instances within each group that have valid results as per the formula.
    • Calculation: For each group defined by groupBy, counts the number of records that satisfy the formula.
    • Use Case: Measures the effectiveness or relevance of data within each group, highlighting areas that meet specific criteria.

Combined Use Case

When used together, Units and Tally offer a comprehensive view of your data:

Example Scenario:

This combination allows stakeholders to quickly assess both the distribution and the quality of the data.

Visual Representation

To better understand how Properties function within Trwth.js, consider the following diagram:

/trwth
          /apps
          /data
            test_loan_data.csv
          /libraries
          /core
          /styles
          ...
        

The diagram illustrates the hierarchical structure of a Trwth application, highlighting where different components like presentation, units, and tally fit within the overall framework.

Summary

By effectively utilizing both types of Properties, you can create robust, insightful, and user-friendly applications with Trwth.js.


App Build Process

In this section, we'll walk you through building a simple Trwth application using the base template located at apps/template/starter_rename.html. We'll animate the process of filling out the appConfig to help you understand each step clearly.

Step 1: Open the Base Template

Start by navigating to the apps/template directory in your Trwth framework folder. Open the starter_rename.html file in your preferred text editor.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Security-Policy" content="img-src 'self' data:; default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self' https://trwth.com; object-src 'none';">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="../../styles/base.css">
  <title></title>
</head>
<body>
  <div id="app-container"></div>
  <script>
    // App configuration
    const appConfig = {
      libraries: [
      ],
      formula: '',
      groupBy: '',
      presentation: {
        columns: [
          { heading: '', field: '' },
        ],
      }
    };
  </script>
  <script src="../../core/ai.js" defer></script>
  <script src="../../core/main.js" defer></script>
  <script src="../../core/ux.js" defer></script>
  <script src="../../core/charts.js" defer></script>
</body>
</html>

Step 2: Define the App Configuration

We'll fill out the appConfig object step-by-step to configure our application. Each step will add a new part to the configuration.

2.1 Specify the Libraries

Libraries are collections of functions, attributes, and dictionaries that provide specific functionalities to your application. We'll include the financial and organization libraries.

const appConfig = {
  libraries: ['financial', 'organization'],
  formula: '',
  groupBy: '',
  presentation: {
    columns: [
      { heading: '', field: '' },
    ],
  },
};

2.2 Define the Formula

The formula determines the logic for processing data. In this example, we'll filter loans opened between October 31, 2020, and November 3, 2024, and return their principal amounts.

const appConfig = {
  libraries: ['financial', 'organization'],
  formula: 'loan.open > "2020-10-31" && loan.open < "2024-11-03" ? loan.principal : null',
  groupBy: '',
  presentation: {
    columns: [
      { heading: '', field: '' },
    ],
  },
};

Setting Up Data Sources

Data sources can be defined through various means, such as importing CSV files or utilizing predefined libraries. Here's how to define a data source:

Example: Defining the Loan Data Source

Assume you have a CSV file named test_loan_data.csv with the following headers:

Portfolio,Branch,Principal,OpenDate,class,zip,birth,customer.gender
        Portfolio A,Branch X,5000,2024-05-15,1,12345,1980,M
        Portfolio B,Branch Y,3000,2024-03-22,20,67890,1992,F
        ...

This CSV file will serve as the loan data source with fields like Portfolio, Branch, Principal, OpenDate, class, zip, birth, and customer.gender.

Integrating the Data Source in appConfig

Ensure that your appConfig is set to recognize and utilize the loan data source:

const appConfig = {
  libraries: ['financial', 'organization'],
  formula: 'tally == units && loan.class in [1, 20] && loan.open > "2024-01-01" && loan.open <= "2024-11-03" ? loan.principal : null',
  groupBy: 'Portfolio',
  presentation: {
    columns: [
      { heading: 'Branch', field: 'branch' },
      { heading: 'Type', field: 'class' },
      { heading: 'Zip', field: 'zip' },
      { heading: 'Birth Year', field: 'birth' },
      { heading: 'Gender', field: 'customer.gender' }
    ],
  }
};

2.3 Group the Data

Grouping allows you to aggregate data based on a common field. We'll group the loans by the Portfolio field.

const appConfig = {
  libraries: ['financial', 'organization'],
  formula: 'loan.open > "2020-10-31" && loan.open < "2024-11-03" ? loan.principal : null',
  groupBy: 'Portfolio',
  presentation: {
    columns: [
      { heading: '', field: '' },
    ],
  },
};

2.4 Set Up the Presentation

The presentation section defines how the data will be displayed in the application. We'll display the Branch and Principal for each portfolio.

const appConfig = {
  libraries: ['financial', 'organization'],
  formula: 'loan.open > "2020-10-31" && loan.open < "2024-11-03" ? loan.principal : null',
  groupBy: 'Portfolio',
  presentation: {
    columns: [
      { heading: 'Branch', field: 'branch' },
      { heading: 'Principal', field: 'principal' },
    ],
  },
};

Step 3: Save and Run the Application

After defining the appConfig, save the changes to starter_rename.html and run the application to see the results.

3.1 Save the Changes

Ensure all your changes to starter_rename.html are saved.

3.2 Open the Application in a Browser

  1. Navigate to the apps directory.
  2. Double-click starter_rename.html to open it in your default web browser.
  3. Alternatively, right-click the file, select "Open with", and choose your preferred browser.

3.3 Interact with the Application

The application should now display a table showing the Branch and Principal for loans that were opened between October 31, 2020, and November 3, 2024, grouped by their respective Portfolio.

Step 4: Understanding the Framework Through the Demo

Let's break down how Trwth processes the data and renders the application based on our configuration.

4.1 The Data Flow

4.2 Grouping and Presentation

4.3 Libraries and Functions

Step 5: Experiment and Extend

Now that you've built a basic application, let's explore how you can customize and enhance it further.

5.1 Modify the Formula

Change the date range in the formula to see how it affects the displayed data.

Example:

formula: 'loan.open > "2019-01-01" && loan.open < "2021-12-31" ? loan.principal : null',

5.2 Add More Columns

Include additional fields in the presentation to display more data.

Example:

presentation: {
  columns: [
    { heading: 'Portfolio', field: 'Portfolio' },
    { heading: 'Branch', field: 'branch' },
    { heading: 'Principal', field: 'principal' },
    { heading: 'Open Date', field: 'loan.open' },
  ],
},

5.3 Utilize Functions

If you have functions defined in your libraries, you can incorporate them into your formula to perform more complex operations.

Example:

formula: 'loan.open > "2020-10-31" && loan.open < "2024-11-03" ? loanPayment(loan.principal, loan.rate, loan.term) : null',

Here, loanPayment is a function that calculates the loan payment based on principal, rate, and term.

Conclusion

You've successfully built a simple Trwth application using the base template. By defining the appConfig, you configured how the application processes and presents data. Understanding each component of the configuration helps you harness the full power of Trwth to build more sophisticated applications.


Next Steps:


Need Help?

If you encounter any issues or have questions, consider:

Happy coding with Trwth!

App Configuration

Trwth Apps or (SPA) features include reference to a source in the presentation configuration whereby the source data can be used in the presentation and not be included in the formula processing.

const appConfig = { libraries: [ ], formula: 'loan.principal', groupBy: 'Portfolio', presentation: { columns: [ { heading: 'Branch', field: 'branch' }, { heading: 'Type', field: 'class' }, { heading: 'Zip', field: 'zip' }, { heading: 'Birth Year', field: 'birth' }, { heading: 'Gender', field: 'customer.gender' } ], } } };

Advanced Topics

core/ai.js

aiTranslater: accepts a data pipe's header or schema keys, and a word or indentifier to translate as arguments. This translator return it's educated guess on the precise header column or schema key that matches the target word. This is used by core Trwth.js code to allow app desginers the flexibility in designing and adapting their applications to multiple data sources. Show some examples of portfolio