Author Archives: ksbhaskar

Project Highlites: A Lightweight Open-Source Predictor for any Classifications, Trained with Data of Choice

We welcome Alain Descamps for his first guest blog post, and hope there are many more to follow. If you would like to post on the YottaDB blog please contact us at info@yottadb.com.

Introduction

My name is Alain, and I have been writing code in M since about 1984, except during weekends and holidays. For the last 25+ years, I have been working for the University of Antwerp in a team called Wander, that writes software, used for libraries, research data, heritage collections and various other stuff. They also provide services for other organisations, mostly in the Public Sector, like museums, archives and other libraries. Almost superfluous to say that Wander software is based on YottaDB.

After you have read this blog, you will probably have more questions and possible urgencies for extra stories: I kindly inform you that I warned you.

The Occasion

All publications from the University are registered in a M database, and – traditionally – subject codes are added to them, by means of harvesting from external sources or manually by the cataloger. One day, I was informed that the Flemish government had invented a new subject coding system, and would it be possible to assign these subject codes to publications, and oh, yes, also retroactively for the previous years. It was clear that this was not a job that could be achieved by the cataloger in a reasonable time: we needed extra tooling because of too many records.

So my idea was: instead of looking for some cloud-based AI solution, let me see if I can write something in M, hopefully useful to predict subject codes. I admit that I liked the challenge to try to kill a mosquito not with a cannon, but with something more appropriate.

The Resources

We had roughly five ‘locally available’ resources:

  1. The first resource was our database engine, the YottaDB M database, which I could talk about, but that would be a different story.
  2. The second resource was the programming language used to originally access the database: M. Talking about this would be another story.
  3. The third part involved expanding the M database to also be accessible from Lua: this project, now known as YDBLua, was sponsored by the University of Antwerp and made open-source. This made it possible to develop precisely those things in Lua where Lua is stronger than M. The M database has also since been integrated into other programming languages, including Python and Go. But again, that is another interesting story.
  4. The fourth part consisted of software pieces from our Wander repository, which had already proven their worth in our applications and each solved specific problems.
  5. The fifth (non-essential) part was our back-office application, that let us make some necessary forms and configurations.

The Challenge: a Fast and Useful Algorithm

Developing the algorithm itself was quite an adventure: it had to be lightweight. For practical reasons, guessing a classification had to be done within a reasonable timeframe – say, a second – and it shouldn’t consume a lot of computer power, which is shared with all other applications. Thanks to the M hierarchical database model, combined with bitmaps, driven by the $ZBIT extensions, we got the engine working. It would be a great story to talk about bitmap indexes in M globals.

The algorithm consisted of a few steps:

  1. During training:
    1. Extract tokens from a given text: the short version, tokens are words in the text, normalised somehow, like converted to lowercase. This works for any UTF-8 code. There is even a hidden possibility to chose the Unicode version. The long version is another story.
    2. Store a bitmap index between every token and the linked subject code.
  2. During prediction:
    1. Extract tokens from a given text, the same way as during training.
    2. Look for the tokens, that are linked to the fewest topics. Stop if these subjects are reasonably few.
    3. Intersect with the tokens, that are linked tot the second-fewest topics, … until you have (almost) nothing left.
    4. The resulting set of 1 or more subject codes is your prediction.

Remark: although there are a few tweaks added to this algorithm, the base idea stays. I will repeat myself, but I could write another story about this, too.

The Product

The project is currently available as an open-source beta version at https://gitlab.com/AlainDsc/highlites/. The final product of this project is not a ready-made application, but a piece of software that a developer can work with. Essentially, the software is accessible via 3 openings.

  • The first is a command-line interface that allows the necessary instructions to be executed via the prompt. These instructions consist of a ‘training’ component – to train the ‘know-how’ – and a ‘predict’ component, to calculate a classification proposal. This appears in standard output.
  • The second way is a Lua module. As the main engine is written in M, all ingredients are present to build a module in Python, Go, Javascript or Rust.
  • The third way is calling the M routines directly. For predictions, you only need the M part. If you really want, you could create something with only M available.

Please know that this is genuinely usable in a multi-task and multi-user environment: you can train multiple knowledge systems simultaneously and make use of them, and you can also train the same system via a number of parallel processes. You can train a system on literally thousands of different subject codes: that comes from the underlying database engine, which happens to be the most scalable database überhaupt.

The cases

In my article, I spend a lot of efforts to show a ‘good’ and a ‘bad’ case in practice. I can refer to the article itself, for details, but the short story goes like this : your prediction will be not better than the data that you have worked with. You cannot make any beauty from clutter.

Conclusions

Well, this Highlites project was a nice trip, and one is always surprised at how far you can jump. There were some other surprising conclusions, as side effects.

Surpassing ‘Classic’ AI Methods in Speed by a Factor

With predicting speeds between 36 and 910 predicts per second in our test, and with the possibility to launch parallel prediction sessions, one cannot help but conclude that, structurally, this is an order of magnitude faster than a ‘classic’ targeted AI. Long live MUMPS.

Fast, Economical, and Usable in Real Life

Although we were unable to take exact measurements of power consumption, the impact of the
Highlites processes on our servers was no greater than the impact of a standard process: one can therefore cautiously conclude that Highlites is an order of magnitude more consumer-friendly than ‘classic’ AI processes. Execution speeds were more than fast enough to support a real-life application.

Extra electricity consumption was not measurable.

Acceptable Prediction Rate, Bad Noise

Although prediction rates are highly dependent on the size and quality of the training data, one can conclude that the Highlites algorithm yields usable results in some cases. The disappointing part: in addition to predicting correct subject codes, there is a fair amount of noise from false positives.

Ceci N’est Pas un Remplaçant

Highlites is therefore certainly not a replacement for the cataloger. The contribution of the cataloger should never be underestimated either. However, it can play an assisting role in generating suggestions, and in reducing hundreds of subject codes to a manageable list from which one can easily choose.

One Cannot Prepare a Good Meal from Waste

Finally, I would like to briefly point out that predicting subject codes based on titles and abstracts has its limits: a title can be so general or misleading that any prediction using any algorithm fails. An example of a title: Obtaining more information from conjoint experiments by best-worst choices: Highlites found no code that stood out and predicted 8 (!) codes, from 61 (Human medicine) to 37 (Educational sciences). The correct subject code was not among them (681.3 Computer).

Viva la privacy

The whole Highlites training system and software resides on your computer: there is no data in the cloud, except if you put it there deliberately: so, sharing your training knowledge is controlled by you, dear local software engineer.

Live long and prosperous!

About Alain Descamps

Alain has talked about himself in the Introduction. He is also an aficionado of the Citroën 2CV “Deux chevaux”. You can reach him by e-mail.


Credits

  • Photo of Alain Descamps with his Citroën 2CV At Nordkapp, the Northernmost point in Europe reachable by road courtesy the author.
  • Blog roll photo of the University of Antwerp by K.S. Bhaskar.
Northwind and the Sensory Homunculus of Phantom Retail

We thank Alex Woodhead for his second blog post, and hope there are many more to follow. If you would like to comment on this post, or submit a guest post for the YottaDB blog please contact us at info@yottadb.com.

TL;DR

A Claude fueled exploration of your missing product features that are of high value and or high pain points for customers in competing products. Claude understands mermaid Entity Relation Diagrams and can use them to aid research to build out new features.

  • Cost: Less than $15 of tokens
  • Duration: About 3 hours prompt processing

Sources of Inspiration

The Sensory Humunculus

In 1937 Wilder Penfield along with Edwin Boldrey and Hortense Cantile, devised the sensory homunculus. It visually communicates relation of cortex surface area serving locations of sensory input.

To give the best support to a customer you have to understand their pain ~ Anon.

Thought: Are the emotional manifestations to interaction with an electronic product analogous to a logical sensory input?

Sensory Ghosts

In 1871 American physician Silas Weir coined the phrase “Phantom Limb”. He observed and documented a syndrome among civil war amputees describing sensations as “sensory ghosts”.

Ref: Lippincott’s Magazine, vol. VIII, no. 48, December 1871

Thought experiment: When a customer interacts with your product, are you aware of “what feelings they are missing”?

Prompt Method

Armed with a minimal schema of a Northwind database and a New Mexico piñon coffee, I sat down with Claude to investigate. Lets do this!

The project files Source_Database_Schema and concepts.py are shown in their initial state. Ghost_Database_Schema.md starts as an empty file. They serve as a pattern to follow on what information is to be collated and how to relate it.

# project

Expert with relational database schemas for e-commerce ( online shopping ) and logistics ( shipping inventory and parcel delivery )
Meaning:
* the name, meaning and purpose of SQL tables
* the name, meaning and purpose of SQL columns

For purpose of this project documentation:
The phrase '[Source Database]' means the 'Northwind Database'
The phrase '[Source Table]' means a table in the 'Northwind Database'
The phrase '[Source Column]' means a column in the 'Northwind Datbase'
The phrade 'concept' means a logical placeholder for a named table or named column of a database table

Capture information context to help match with a customer natural language enquiry with common functionality that is:
* present in the [Source Database].
* missing from the [Source Database].

## Out of scope of project implementation
Mentioned for orientation
For example consider:
The customer question: "How can I track my package?"
This maps to the answer:
Pseudo concept 'tracking' ( example for illustrative purpose )
"Unfortunately we currently don't have ability to track your package. But your requirement to do this has been noted."
Here illustrative concept generalization of 'tracking' is a ghost feature for the [Source Database].

## adding ghost features
Your expert e-commerce and logistics expertise is needed to know about important *common* and *productive* functionally for customer interaction, tables, columns and features that exist on real production e-commerce and logistics systems, but are missing in the [Source Database].
These missing tables will be called 'ghost tables', with a name prefix of 'ghost'.
These missing columns will be called 'ghost columns', with a name prefix 'ghost'
For example: Source table 'nwOrders' defines an 'OrderDate' but not a 'ShippedDate' or 'DeliveredDate'.
Example: The illustrative externally determined 'ShippedDate' and 'DeliveredDate' would thus be included as 'ghostShippedDate' and 'ghostDeliveredDate' respectively. If these ghost columns are added to [Source Database] table 'nwOrders', their new enumeration names would be 'nwOrders_ghostShippedDate' and 'nwOrders_ghostDeliveredDate' respectively.
Ghost columns can be added to and removed via file Ghost_Database_Schema.md and concepts.py. However do not remove non-ghost columns from [Source Database] tables. Do not remove non-ghost tables from the [Source Database].
The file 'Ghost_Database_Schema.md' is to be populated with a larger overlay schema containing tables from [Source Database] but with ghost columns and tables added. This gives a SQL database audience understanding and documentation. This is maintained in tandem with concepts.py which must always agree ( be synchronized ).

## development environment
This is a python3 environment.

### Setup
No setup is required.
Don't create virtual environments. Just use the current python3 directly.
The file 'requirements.txt' shows available python libraries already loaded in the environment.
If you think additional dependencies are need then ask and justify why. Rationale: the pre-built development context will be reused.

## File Structure

Source_Database_Schema.md - Read-only. Shows relationships between columns in original [Source Database]
Ghost_Database_Schema.md - Expressions to recreate target [Source Database] plus additional ghost columns and ghost tables.
concepts.py - file to capture, manage, score and relate database tables and names

## Rules
Don't suggest adding or removing tables from the [Source Database]
Don't suggest removing non-ghost columns from the [Source Database] tables.
Don't create an actual database. We are simply exploring to understand and populate concepts.py from the e-commerce and logistic domain information analysis.
Project File: Claude.md (terminal Claude)

 

An ER diagram deconstructed from the SQL statements below, based on the Northwind database adapted for Octo, is shown below them.

# Source Database Schema
Readonly. Do not modify information in this file.
Instead use for reference for when working on Ghost_Database_Schema.md
## Relationships between tables

```mermaid
%%{init: {
'theme': 'default',
'look': 'classic',
'layout': 'dagre'
} }%%
erDiagram
nwCustomers || --o{ nwOrders : nwOrders.CustomerID
nwOrders }| --|| Employees : nwOrders.EmployeeID
nwOrders }| --|| Shippers : nwOrders.ShipperID
nwOrders || --|{ OrderDetails : OrderDetails.OrderID
Products }| --|| Suppliers : Products.SupplierID
Products }| --|| Categories : Products.CategoryID
Products || --|{ OrderDetails: OrderDetails.ProductID

nwCustomers {
INTEGER CustomerID PK
VARCHAR(48) CustomerName
VARCHAR(32) ContactName
VARCHAR(64) Address
VARCHAR(32) City
VARCHAR(16) PostalCode
VARCHAR(32) Country
}
nwOrders {
INTEGER OrderID PK
INTEGER CustomerID
INTEGER EmployeeID
DATE OrderDate
INTEGER ShipperID
}
Shippers {
INTEGER ShipperID PK
VARCHAR(32) ShipperName
VARCHAR(14) Phone
}
Suppliers {
INTEGER SupplierID PK
VARCHAR(48) SupplierName
VARCHAR(32) ContactName
VARCHAR(64) Address
VARCHAR(32) City
VARCHAR(16) PostalCode
VARCHAR(32) Country
VARCHAR(15) Phone
}
Products {
INTEGER ProductID PK
VARCHAR(48) ProductName
INTEGER SupplierID
INTEGER CategoryID
VARCHAR(32) Unit
NUMERIC Price
}
OrderDetails {
INTEGER OrderDetailID PK
INTEGER OrderID
INTEGER ProductID
INTEGER Quantity
}
Categories {
INTEGER CategoryID PK
VARCHAR(32) CategoryName
VARCHAR(64) Description
}
Employees {
INTEGER EmployeeID PK
VARCHAR(32) LastName
VARCHAR(32) FirstName
DATE BirthDate
VARCHAR(16) Photo
VARCHAR(512) Notes
}

# SQL creating Northwind database tables and columns
```sql
CREATE TABLE nwCustomers (CustomerID INTEGER PRIMARY KEY, CustomerName VARCHAR(48), ContactName VARCHAR(32), Address VARCHAR(64), City VARCHAR(32), PostalCode VARCHAR(16), Country VARCHAR(32));
CREATE TABLE nwOrders (OrderID INTEGER PRIMARY KEY, CustomerID INTEGER, EmployeeID INTEGER, OrderDate DATE, ShipperID INTEGER);
CREATE TABLE Shippers (ShipperID INTEGER PRIMARY KEY, ShipperName VARCHAR(32), Phone VARCHAR(14));
CREATE TABLE Suppliers (SupplierID INTEGER PRIMARY KEY, SupplierName VARCHAR(48), ContactName VARCHAR(32), Address VARCHAR(64), City VARCHAR(32), PostalCode VARCHAR(16), Country VARCHAR(32), Phone VARCHAR(15));
CREATE TABLE Products (ProductID INTEGER PRIMARY KEY, ProductName VARCHAR(48), SupplierID INTEGER, CategoryID INTEGER, Unit VARCHAR(32), Price NUMERIC);
CREATE TABLE OrderDetails (OrderDetailID INTEGER PRIMARY KEY, OrderID INTEGER, ProductID INTEGER, Quantity INTEGER);
CREATE TABLE Categories (CategoryID INTEGER PRIMARY KEY, CategoryName VARCHAR(32), Description VARCHAR(64));
CREATE TABLE Employees (EmployeeID INTEGER PRIMARY KEY, LastName VARCHAR(32), FirstName VARCHAR(32), BirthDate DATE, Photo VARCHAR(16), Notes VARCHAR(512));
File: Source_Database_Schema.md

 
The below render of the Entity-Relationship diagram Claude was asked to work from starting with Source_Database_Schema.md shows only eight tables.
ER diagram of 8 tables of Northwind database

# This file holds enumeration placeholder definitions and descriptions (Config) for existing Northwind database tables and columns. To be extended with ghost columns and tables. The table and column names in Ghost_Database_Schema.md must always be synchronized with values in the Concept enumeration
# Naming relation convention:
# * Table name is equivalent to Enumeration name.
#   For example table 'nwCustomers' related to enumeration entry 'nwCustomers'.
# * Column name in table is equivalent to Enumeration name.
#   For example: column 'Address" in table 'nwCustomers' has corresponding enumeration entry 'nwCustomers_Address'
# Where the table name and column name are concatenated with underscore character

from enum import Enum,auto

# Holds concept names used as keys by dictionary 'Config'
# Note: Integer and GUID (UUID) Primary keys that join relational tables are not assigned a corresponding enumeration entry. Rationale: Customers would not enquire about database primary keys unless they have some informational value.
class Concept(Enum):
    nwCustomers=auto()
    nwCustomers_CustomerName=auto()
    nwCustomers_ContactName=auto()
    nwCustomers_Address=auto()
    nwCustomers_City=auto()
    nwCustomers_PostalCode=auto()
    nwCustomers_Country=auto()

    nwOrders=auto()
    nwOrders_OrderDate=auto()
    
    Shippers=auto()
    Shippers_ShipperName=auto()
    Shippers_Phone=auto()

    Suppliers=auto()
    Suppliers_SupplierName=auto()
    Suppliers_ContactName=auto()
    Suppliers_Address=auto()
    Suppliers_City=auto()
    Suppliers_PostalCode=auto()
    Suppliers_Country=auto()
    Suppliers_Phone=auto()

    Products=auto()
    Products_ProductName=auto()
    Products_Unit=auto()
    Products_Price=auto()
    
    OrderDetails=auto()
    OrderDetails_Quantity=auto()

    Categories=auto()
    Categories_CategoryName=auto()
    Categories_Description=auto()

    Employees=auto()
    Employees_LastName=auto()
    Employees_FirstName=auto()
    Employees_BirthDate=auto()
    Employees_Photo=auto()
    Employees_Notes=auto()


# Describes concepts used by base Nothwind Database plus ghost concepts
# Each [SourceDatabase] existing columns and tables have 'useful' set to one. Don't change these.
# Ghost Tables and Columns can be fully evaluated, compared and their 'useful' values
# elevated or decremented as new ghost tables and columns are added and compared.
# If a Ghost Table is removed then All of its corresponding Column entries would also be removed
# A Ghost table MUST have at least one Ghost Column entry
# Each ghost table or column MUST have a tangible 'useful' rating in the range from 1 to 20 inclusive, where:
# '1' means very useful and highest priority for direct customer interaction
# '20' means least useful and lowest priority for direct customer interaction
# Usefulness for customer interaction would be in customer scenarios:
# * buying a product from a website with their mobile phone or home computer
# * shipping product to the customer
# * tracking delivery of a dispatched product to a customer address
# * returning a defective product and asking for a refund
# * finding and viewing product details and features
# * requesting information about an order they made.
# * requesting a brochure about a product category
# These scenarios are illustrative and not exhaustive. Others can be suggested
Config={
    # Concept table Template by comments example
    Concept.nwCustomers:{
       # Mandatory. Type int
       # integer between 1 and 20
       'useful': 1,
       
       # Mandatory. Type String.
       # Capture rationale for 'useful score'
       'useful_justification':' In Northwind Database',

        # Use only if table is from Northwind database table
        'northwind_label': 'nwCustomers',

        # Type: list[tuple[str,str]]
        # List of table names use by other products for the same thing
        # Where type is ( [product_name], [column_name] 
        # Can accommodate multiple labels from a product if needed
        'ghost_label': [('ACME','Customer')],

        # Mandatory. Type list[str].
        # English language aliases in one or more words, with and without abbreviations, that are terms used commonly by general public to refer to this functionality.
        # Language aliases are free to overlap with terms and phrases used by other concepts
        # Aim to create between five and fifty variations.
        # Include negative and complaint phrasing customers use (e.g. 'Overcharged', 'Wrong item') where the complaint is about this concept.
        # The Quality of alias term is more important than maximizing the number of entries
        'generic_aliases':[
            'Customer', 'Customers', 'Client', 'Buyer', 'Purchaser'
            ],

        # Describe in one to four sentences precisely the functional intention of this table.
        'description':'Holds information about the customer making a purchase on an e-commerce site.'
    },

    # Concept column Template by comments example
    Concept.nwCustomers_Address:{
       # Mandatory. Type int
       # integer between 1 and 20
       'useful': 1,
       
       # Mandatory. Type String.
       # Capture rationale for 'useful score'
       'useful_justification':' In Northwind Database',

        # Use only if column is from Northwind database
        'northwind_label': 'Address',

        # Type: list[tuple[str,str]]
        # List of column names use by other products for the same thing
        # Where tuple type meaning is ( [product_name], [column_name] )
        # Can accommodate multiple labels from a product if needed
        'ghost_label': [('ACME','Street_name')],

        # Mandatory. Type list[str].
        # Generic aliases have one or more words, with and without abbreviations, that are terms or phrases used commonly by general public to refer to this functionality.
        # Language aliases are free to overlap with terms and phrases used by other concepts
        # Aim to create between five and fifty variations.
        # Include negative and complaint phrasing customers use (e.g. 'Overcharged', 'Wrong item') where the complaint is about this concept.
        # The Quality of alias term is more important than maximizing the number of entries
        'generic_aliases':[
            'Address', 'Street address', 'Address line 1'
            ],

        # Optional. Type list[str]. Columns only, not tables.
        # Around ten example values the column holds. For columns with a fixed set of values
        # (e.g. a status) list the canonical values; otherwise give realistic examples.
        'values':[
            ],

        # Mandatory. Type String.
        # Describe in one to four sentences precisely the functional intention this column.
        'description':'Home or delivery address information the customer making a purchase on an e-commerce site.'
    },

}
Project File: concepts.py

 

Outputs

Filtered on usefulness scores 1 to 4. These are the maximum importance and or pain areas to the customer.
Northwind Sensory Homunculus Heat map

Northwind Sensory Homunculus Heat map

How to understand the heat map: The more sensitive the “information area” the brighter the color will be.

 

Claude generated 11 additional tables and enhanced the 8 existing tables to model features from competing products.

End ER diagram
 

Northwind Sensory Homunculus in Tabular format

Useful level 1

Table Linked to Justification for usefulness priority Description
nwOrders ghostOrderStatus “Where is my order / what is the status of my order” is the top support topic in every source (18-50% of tickets); every platform and schema.org has an order status.

  • Pending payment
  • Awaiting fulfilment
  • Processing
  • On hold
  • Partially shipped
  • Shipped
  • Delivered
  • Completed
  • Cancelled
  • Refunded
The current stage of the order, from payment through dispatch to completion. Answers the most common customer question: where is my order and what is happening to it.
ghostShipments ghostTrackingNumber Customers ask for, and complain about, tracking numbers; held by every platform and shipping tool researched. The carrier’s reference number for the parcel, used to follow its progress on the carrier’s website. Shown to the customer in dispatch emails and order history.
ghostShipmentStatus Delivery status is what WISMO customers want to know; AfterShip, EasyPost, Shippo, Shopify and Amazon all normalise to the same ten stages.

  • Label created
  • In transit
  • Out for delivery
  • Delivery attempted
  • Ready for collection
  • Delivered
  • Exception
  • Returning to sender
  • Cancelled
  • Unknown
The current stage of the parcel in the carrier network, from label created to delivered, or an exception such as a failed delivery.
ghostShippedDate “When will you ship / has it been dispatched” is a core WISMO question; WooCommerce, ShipStation, Shopify and Magento record the ship date. The date the parcel was handed to the carrier.
ghostEstimatedDeliveryFrom “When will it arrive / ETA” is a core WISMO question (Bitext delivery_period); Amazon, eBay and schema.org hold a delivery window. The earliest date the parcel is expected to arrive; the start of the delivery window shown to the customer.
ghostEstimatedDeliveryUntil Late delivery is the top delivery complaint (Citizens Advice; Which? 56% not arrived when expected); Amazon A-to-z claims open 3 days after the latest delivery date. The latest date the parcel is expected to arrive; after this the delivery is late.
ghostDeliveredDate “It says delivered but I have not got it” is a distinct high-volume complaint (Lorikeet, Royal Mail, USPS, Amazon); carriers record the delivery date. The date the carrier recorded the parcel as delivered, or empty if not yet delivered.

Useful level 2

Table Linked to Justification for usefulness priority Description
OrderDetails ghostQuantityShipped Partly shipped orders are a common cause of “items missing” contacts; Amazon (QuantityShipped, PartiallyShipped), eBay (IN_PROGRESS) and Shopify (partial) model them. How many units of this order line have been shipped so far. When less than the quantity ordered, the rest is still to come or on back order.
ghostShipments ghostTrackingUrl Customers use the tracking link to self-serve; Shopify, WooCommerce, Salesforce and schema.org store a tracking URL. A web link to the carrier’s tracking page for this parcel.
ghostShipmentEvents ghostEventStatus Scan wording (“arrived at hub”, “out for delivery”, “card left”) is what customers quote back; AfterShip sub-statuses give the standard list.

  • Label created
  • Collected by carrier
  • Arrived at sorting centre
  • Departed facility
  • Arrived in destination country
  • Out for delivery
  • Delivery attempted
  • Delivered
  • Exception
  • Returning to sender
The stage recorded at this scan, such as collected, arrived at a sorting centre, out for delivery or delivered.
ghostExceptionReason Delivery problems are the second biggest complaint area: late, lost, damaged, left unsafe, wrong address, refused (Citizens Advice, Which?, FTC, Trustpilot); AfterShip Exception and AttemptFail codes give the standard reasons.

  • Recipient not available
  • Business closed
  • Address incorrect
  • Customer moved
  • Refused by recipient
  • Damaged in transit
  • Lost in transit
  • Customs delay
  • Weather delay
  • Not collected from pickup point
Why delivery could not be completed at this scan, such as nobody available, address incorrect, damaged or lost.
ghostReturns ghostReturnStatus Customers chase returns (“did you get my return?”); Shopify, Adobe Commerce RMA and eBay all track return status. The progress of the return, from requested through received and inspected to refunded, exchanged or denied.
ghostReturnReason Return reasons are customers’ own complaint wording; Shopify ReturnReason, eBay ReturnReasonEnum, Adobe Commerce RMA and Amazon’s return menu all list them. Why the customer is returning the item. Reasons where the seller is at fault (damaged, wrong item, not as described) usually mean free return postage.
ghostRefunds ghostRefundAmount Customers dispute partial refunds and missing postage refunds; every refund model records an amount. The amount of money refunded to the customer.
ghostRefundStatus Refund chasing is a top post-purchase contact (Bitext track_refund); Shopify financial_status and WooCommerce statuses show refund progress.

  • Pending
  • Approved
  • Processing
  • Issued
  • Completed
  • Failed
  • Declined
  • Reversed
  • Cancelled
  • On hold
The progress of the refund, from pending to issued and completed, or failed.

Useful level 3

Table Column Justification for usefulness priority Description
nwCustomers ghostEmail Needed for order confirmations, dispatch notices and every contact request; held by all platforms researched. The email address of the customer contact. Used for order confirmations, dispatch and delivery notices, invoices and account login.
ghostPhone Needed by carriers for delivery contact and by staff for queries; held by all platforms researched. The telephone number of the customer contact. Used by the courier to arrange delivery and by staff to resolve order queries; mobile numbers can receive SMS delivery updates.
ghostRegion State / county / province is part of every address model researched (Shopify, WooCommerce, Magento, Amazon, schema.org) and is required for US addresses, tax and shipping zones. The state, county or province part of the customer address. Required for US addresses and used for delivery zones, sales tax and correspondence.
nwOrders ghostShipName Every platform stores a ship-to name separate from the customer (gifts, staff receiving deliveries); part of the original full Northwind Orders table. The name of the person or business the order is delivered to. May differ from the customer, for example a gift recipient or a member of staff receiving goods.
ghostShipAddress Wrong-address and change-address requests are frequent (Bitext address intents, Trustpilot complaints); all platforms store a shipping address on the order. The street address the order is delivered to. Copied from the customer at the time of ordering so it can differ from the account address and can be changed for one order.
ghostShipCity Part of the order shipping address in every platform researched. The city or town of the order shipping address.
ghostShipRegion Part of the order shipping address in every platform researched; required for US deliveries. The state, county or province of the order shipping address.
ghostShipPostalCode Part of the order shipping address in every platform researched; used for delivery routing. The postcode (UK) or ZIP code (US) of the order shipping address.
ghostShipCountry Part of the order shipping address in every platform researched; decides domestic vs international delivery and customs. The country of the order shipping address. Decides whether delivery is domestic or international and whether customs applies.
ghostCancelledDate Order cancellation is a frequent intent (Bitext cancel_order; 17% “order changes” in one store); Shopify, WooCommerce, Magento, Amazon, eBay and ShipStation all record cancellation. When the order was cancelled, or empty if it has not been. A cancelled order will not be dispatched and any payment should be refunded.
ghostCancelReason Customers ask why an order was cancelled; Shopify and eBay record a cancel reason. Why the order was cancelled, whether requested by the customer or by the business (for example out of stock or payment declined).
ghostShipmentEvents ghostEventDate “Tracking has not updated in days” is a common complaint (AfterShip Expired_001 / Pending_005). When the carrier recorded this tracking event.
ghostReturns ghostResolution Customers ask for a refund, replacement or exchange and complain about store credit; Adobe Commerce RMA resolution, schema.org RefundTypeEnumeration and Shopify exchanges model it. The outcome of the return: a refund, an exchange or replacement, or store credit.
ghostRefunds ghostRefundDate Customers ask how long refunds take; refund records carry a date (Shopify Refund.created_at). When the refund was issued.
ghostPayments ghostPaymentStatus “Did my payment go through / why was my card declined” are common (Bitext payment_issue); Shopify financial_status, eBay orderPaymentStatus and schema.org PaymentStatusType model it.

  • Pending
  • Authorised
  • Paid
  • Partially paid
  • Declined
  • Failed
  • Refunded
  • Partially refunded
  • Voided
  • Overdue
Whether the payment has been authorised, completed, declined or refunded.
ghostReturnPolicies ghostReturnable Perishable food is often non-returnable; customers ask “can I return food”; schema.org MerchantReturnNotPermitted models it. Whether products in this category can be returned at all.
‘Yes’, ‘No’
ghostReturnWindowDays “How long do I have to return it” is a common question; schema.org merchantReturnDays models it; UK 14-day cooling-off rules apply to online orders. How many days after delivery the customer has to start a return.

Useful level 4

Table Linked to Justification for usefulness priority Description
nwOrders ghostRequiredDate Customers ask whether an order will arrive in time (“I need it by Friday”); part of the original full Northwind Orders table and important for trade customers. The date by which the customer needs the order delivered. Used to choose a delivery service and to warn the customer if the date cannot be met.
ghostOrderTotal Customers ask what an order cost and dispute totals; every platform stores an order total. The total amount for the order including products, delivery and tax, after any discount.
ghostShippingCost Delivery charges are a frequent pre- and post-purchase question; every platform stores the shipping charge on the order. The delivery charge the customer paid for this order.
ghostTaxAmount VAT / sales tax is on every invoice and asked about by trade customers; stored by Magento, ShipStation and Amazon. The tax (VAT in the UK, sales tax in the US) charged on the order.
ghostShippingService Customers who paid for faster delivery ask about it; Shopify, WooCommerce, ShipStation and Amazon store the chosen service. The delivery service the customer chose for this order, such as standard, express or next day.
Products ghostAvailability “Is it in stock / when is it back” is a common pre-sales question (Gorgias); schema.org ItemAvailability, WooCommerce, Magento and Shopify all model it. Whether the product can be ordered now, and if not why: out of stock, on back order, pre-order or discontinued.
ghostStockLevel Trade customers ask whether there is enough stock for a quantity; Shopify, WooCommerce, Magento and schema.org hold a stock quantity. How many units of the product are currently in stock and available to order.
ghostDescription Product detail questions are 10-15% of tickets (vendor estimate) and “not as described” is a top return reason; every platform has a product description. Text describing the product for customers: what it is, what it tastes like and what makes it different.
ghostIngredients Northwind sells only food; GS1 ingredientStatement is the industry standard field and food labelling law requires it. The full list of ingredients as printed on the pack, in descending order of weight. Used to answer diet questions such as vegan, gluten free or halal.
ghostAllergens Allergen questions are safety-critical for a food seller; GS1 allergenStatement and allergen code lists are the industry standard. The allergens the product contains or may contain, as declared on the label. UK law names 14 allergens and US law 9, so wording differs by market.
ghostDietType Diet questions (vegan, gluten free, halal, kosher) are common for food; GS1 dietCode with 10 DietTypeCode values is the industry standard field.

  • Coeliac
  • Dietetic
  • Free From Gluten
  • Halal
  • Kosher
  • Organic
  • Vegan
  • Vegetarian
  • Without Beef
  • Without Pork
The special diets the product is suitable for, such as vegan, vegetarian, gluten free, halal, kosher or organic, as certified or claimed on the label. Values follow the GS1 diet type codes.
ghostShipmentEvents ghostEventLocation Customers ask where the parcel is now and why it has sat at a depot; every tracking source records a scan location. Where the parcel was when this event was recorded.
ghostCarrierMessage Customers quote tracking messages and ask what they mean; every tracking source keeps the carrier’s raw message. The carrier’s own wording for this tracking event, as shown on its tracking page.
ghostReturns ghostReturnQuantity Customers return part of an order line; Shopify Return.totalQuantity and eBay return line quantities record it. How many units of the order line are being returned.
ghostRequestedDate Return windows are counted from dates and customers dispute them; every returns model records when the return was requested. When the customer asked to return the item.
ghostReturnTrackingNumber Customers prove they posted a return and ask whether it arrived; return shipping fees and reverse fulfilment are modelled by Shopify. The tracking number of the parcel the customer sends back.
ghostRefunds ghostRefundMethod Customers ask where a refund will go and object to store credit; schema.org RefundTypeEnumeration and Adobe Commerce resolutions distinguish methods. How the refund is paid back: to the original payment method, as store credit, or by another method.
ghostPayments ghostPaymentMethod “How can I pay / do you accept…” is a frequent pre-sales question (Bitext check_payment_methods); stored by WooCommerce, ShipStation, Amazon and schema.org. How the customer paid, or will pay, for the order.
ghostAmountPaid Double charges and overcharges are recurring complaints (retailer help pages); ShipStation and Shopify record the amount paid. The amount taken from the customer for this payment.
ghostShippingOptions ghostServiceName Delivery speed options are asked about before ordering; Amazon ShipServiceLevel, ShipStation serviceCode and Shopify shipping lines name them. The name of the delivery service, describing its speed or type.
ghostShippingRate “How much is delivery” is a frequent pre-sales question and high delivery cost a common complaint; schema.org shippingRate and all platforms price delivery. The price of this delivery service.
ghostTransitDays “How long does shipping take” is a top pre-sales question (Branvas); schema.org ShippingDeliveryTime.transitTime models it. How many working days the service usually takes from dispatch to delivery.
ghostDestinationCountry “Do you ship to…?” is a typical pre-sales question (Branvas); schema.org shippingDestination and doesNotShip model coverage. A country this delivery service covers.
ghostReturnPolicies ghostReturnFees “Who pays return postage” is asked often and disputed (Amazon seller forums; eBay seller pays for not-as-described); schema.org ReturnFeesEnumeration models it. Who pays to send a return back and whether any fee is deducted from the refund.
ghostRefundType Customers ask whether they get money back or only credit; schema.org RefundTypeEnumeration models FullRefund, ExchangeRefund, StoreCreditRefund. What the customer receives for a return under this policy: a full refund, an exchange or store credit.

Conclusions

Logistics information domain area played a large part in usefulness weighting for the customer experience.
The starting project is a fairly generic prompt tool that can be reconfigured to give a different emphasis or explore different product information domains.

Further Observations

  • For research oriented tasks ask Claude to “plan the work” before doing the work.
  • After the plan is hatched, direct Claude to “Think harder about aliases” – This is more tokens but quality above quantity.
  • Early on in our project I needed to direct Claude to ignore that there were duplicate generic aliases between concepts and to stop de-duplicating them.
  • I told Claude I had a great plan in a subsequent project where the duplication will be very useful.

  • Giving a “future goal” modulates reward behavior. It is more effective in quality of output than simply directing to “stop duplicating aliases”.
  • I directed Claude to focus on customer feedback made in the US and UK product markets
  • I needed to correct some assumptions for example “US zipcode” and “UK postcode” mean the same concept in our scenario.
  • Direct Claude to “search for real sources information” instead of relying on “from memory” (training).
  • When Claude outputs large amounts of text to read through, in order to make for decisions reply immediately “it will take me while to read though this” to stop Claude jumping ahead to do things in parallel in auto-mode.
  • When Claude suggests the option of doing stages of work in parallel say “No. Do it sequentially”.
  • So subsequently when Claude recommends processing a list of 20 website sources you can interject and suggest “lets process only the first 3rd of items in the list and then decide whether to continue”. Most times Claude reflected that the usefulness of reviewing all sources had diminishing returns after processing the first group of items and was valid decision to skip on to the next plan step.
  • Having at least some project information in a python source file gets interesting in that Claude automatically works out how to write unit tests on the evolving information collation process. This can be rules on expected values for columns and also keeping information in sync between different project files.
  • I was impressed that Claude followed my example of labeling both the table and column name involved in the mermaid Entity Relationship diagrams. For me it removes ambiguity when thinking about these UML diagrams.

There once was a company that one day directed employees to “work smarter”. Somehow possibly through HR?, the local policy became to dress smarter. For example no trainers or jeans, maybe a shirt and tie for Project Managers. I have a suspicion in similar sense maybe the lead of an AI company with a background in physics, one day observed “be kind to the AI”. The implicit reasoning here, is that this games the context reward feedback to give better quality generative results. Somewhere I think the recent media hyper-cycle has whipped up another talking point for AI sentience. Well its all free advertising. So let that sucker spin.

So on my final point:

    Be kind with your prompt input and acknowledge good work at important steps in the context or when useful information is volunteered or alternative enhancements become apparent. Its all reward driven!! So without a new and deserved “great job on that…” the default stochastic expression of prompt metabolism seems simply to complete tasks faster.

About Alex Woodhead

An M programmer with almost a quarter century of experience, Alex Woodhead has worked on projects relating to clinical information system projects on multiple continents. Now living in Southern California, he is focused on synthetic data pipelines for generative AI for novel tools and automation, and is incubating genput.

Contact: info@genput.com

Credits

Faster Index Block Searches

YottaDB databases have a tree structure between blocks, but store records sequentially within a block, with the key of each record except the first stored as the differing end bytes from the preceding record’s key. For example, consider a block whose first record has the key ^X(1,2,3), the second has ^X(1,2,4), and the third has ^X(1,2,5):

  • The first record stores the complete key, “^X(1,2,3)”
  • The second record stores “4” as its key, and a “compression count” that specifies use of “^X(1,2,” from the previous record.
  • The third record stores “5” as its key, and a compression count that specifies use of “^X(1,2,” from the previous record.

While this is efficient for storage, records within a block must be scanned linearly, which is less efficient than searching a tree structure. Since index blocks typically pack more records within a block than data blocks, searching within index blocks can consume a material percentage of an application’s CPU usage, especially for large databases, which can have many levels of index blocks.

This enhancement reduces the time spent searching index blocks by allocating a number of slots, called SEARCH_INDEX_SLOTS, each of SEARCH_INDEX_SIZE bytes. Each slot contains a sorted list of the expanded keys corresponding to a subset of records at different offsets within the corresponding block, so that linear scanning can start with the expanded key immediately preceding the key being sought while using a faster binary search to find that expanded key. For example:

  • A block has index records whose first key is ^X(1,2,3) and the last is ^X(7,12,297).
  • When traversing the block, there is space in the slot to store the offset of every twentieth record, say ^X(1,9,255), ^X(5,3,1), ^X(5,4,236), etc.
  • When searching for ^X(5,4,1), YottaDB would use binary search in the slot to find the offset of ^X(5,3,1) and then linear searching from there for ^X(5,4,1).

As an analogy, consider a key ring with many similar keys. Instead of going through them one at a time to find a key, you could insert labeled tags between the keys, so you only need to find a tag and then go through a smaller number of keys one at a time.

The GDE segment qualifiers SEARCH_INDEX_SLOTS and SEARCH_INDEX_SIZE are used to specify values used by MUPIP CREATE to set values in the database fileheader. The MUPIP SET qualifier SEARCH_INDEX_SIZE=<bytes>[,<slots>] is used to change the values in existing database files. The qualifiers SEARCH_INDEX and NOSEARCH_INDEX can be used to turn the feature on and off. Both GDE and MUPIP treat SEARCH_INDEX_SIZE=0 as instructing YottaDB to use the default values, of 1024 slots, each one quarter of the block size; so, for a database file with 4KiB blocks, the slots use 1MiB of shared memory. Changing the size or number of slots for an existing database file requires standalone access.

DSE DUMP FILEHEADER reports the values as “Search Index Slots” and “Search Index Size”.

In a large database file, the number of index blocks will almost certainly exceed the number of slots. A pessimal strategy would be to expand and cache an index block as soon as it is read into a global buffer – in an active database region, this would churn the slots, force each index block to incur the cost of expanding and caching, only to have this work discarded, resulting in slower performance than no caching. A heuristic attempts to prevent churning of the slots by reserving them for heavily used index blocks.

The enhancement works with both BG and MM access methods.

If you have a database file with very large global variables (e.g., four levels or more), and you feel some tuning might improve performance, you can empirically adjust the number of slots. A good starting point would be the sum number of index blocks above level 1 for the global variables in the database region. You can use MUPIP SIZE or MUPIP INTEG to determine that number. This would also be a good value to use for existing databases from prior YottaDB releases or GT.M versions.

MUPIP REORG disables the optimization when it runs, as it is likely to churn the slots.

Note that global variables that store cross references may pack more records in data blocks than index blocks. However, as cross references are often traversed in order when accessing data, using an optimization called “clues”, block searching in data blocks of cross reference global variables is not likely to benefit by extending this optimization to data blocks.

The table below summarizes the results of the threeen1gE.m program. This is a database stressing program to calculate the lengths of 3n+1 cycles which we use for evaluating database performance. You can see that the code that includes the new functionality has a trivial impact on performance when the feature is not used, but has a definite benefit when the feature is turned on with its default settings – we made no attempt to tune the settings for optimal performance.

Results – times in seconds; smaller is better
Access Method Global Buffers Jobs Master Feature Disabled Feature Enabled
BG 1024 1 53.677 54.152 45.837
BG 1024 16 22.106 22.240 20.475
BG 10000 1 53.241 53.931 45.555
BG 10000 16 14.664 14.782 13.930
MM – 1 47.301 47.726 39.977
MM – 16 11.096 11.169 10.586

 

Not unexpectedly, the enhancement had no impact on the simulated interest posting benchmark. This is because the performance of that benchmark is sensitive to critical section performance, as discussed in our blog post Critical Section Performance in r2.04.

The functionality is now merged into the code base, and will be in the next release. If you would like to try it before the next release, download ydbinstall.sh make it executable and run it with the command sudo ydbinstall.sh --from-source --branch=master. If you do, please share your opinion with us. Thank you.


Credits

  • Images generated by Google Gemini in response to prompting by the author.
R Statistics on a Live VistA Instance

TL;DR

This is a post about connecting R to VistA via Octo and generating interesting statistical analysis and diagrams. At least look at the diagrams, which were all directly generated from R!

Introduction

I learned Statistics in college 20 years ago. I hoped to specialize in the area, but I eventually found that you must have a stomach for sitting for hours at a screen examining data and cleaning it up. No data ever comes clean.

Back then, the most popular software was SAS and SPSS. I learned SAS in school, but I barely remember any of its syntax. Fast-forward 15 years — my work with OSEHRA, WorldVistA, and the National Library of Medicine (NLM) got me in contact with a remarkable Open Source community called OHDSI. I first met them at an RxNorm conference at NLM. OHDSI was most remarkable because it was a functional open-source community. I had conversations with great people on how the community worked, but that’s a discussion for another time.

This community used a software package for statistics called “R”. I learned more about R over the years — it’s extremely capable (as you will see later in this blog post) — but it famously has very obscure syntax: assignment is <-, piping %>%. Any operator can be overloaded, so you can embed surprises for your users. And you have to get used to think of your variables as “vectors” — natural in statistics, as that is how you have to think.

Today, R is (depending on the industry) the first/second most commonly used statistics package in the world. A thriving ecosystem of academics who use it to conduct studies but whose pay is not tied to the software itself means that maintainers can be easily found, sidestepping a common problem in open-source where people who maintain software are often never paid for it.

The object of the post is connecting R to VistA. Before we jump in, a brief introduction to VistA is in order: VistA is an Electronic Medical Record (EMR) originally developed by the Veterans Administration of the US Government, and was a leader for a long time in usability and innovation. It found some commercial success in the private sector in the US between 2005 to 2020, but has found its usage wane recently in favor of Epic and Cerner in line with the rest of the EMR industry. In Jordan, it is successfully used to run the health care system of the entire country. VistA code is public domain.

Statistics using R from VistA

I created 1,160 patients using Synthea, and loaded them into a VEHU image. Then, I used R with the PostgreSQL connector to connect to a Rocto listener. Rocto is part of Octo, YottaDB’s SQL-to-globals mapping software. VistA globals are “projected” to SQL tables using the scripts in YDBOctoVistA, including the new lab_chem_result.sql which makes lab data in VistA accessible from SQL.

I came in with specific ideas on which statistics to run. I used Claude Code to connect to the VistA database and run various ad hoc analyses on the data. I will refer to Claude directly when the work done is its own rather than mine.

I broke down this long post into the following sections:

These are synthetic patients. The cohort was generated by Synthea and loaded into a full VistA instance. Except for the blogroll image and featured image (above), which were generated from a public domain dataset, no real patient data appears anywhere in this post.

Connecting to the data

R connects to a PostgreSQL database — the Octo protocol emulates PostgreSQL; the Octo documentation covers this under Connecting from R:

library(DBI)

con <- dbConnect(RPostgres::Postgres(),
                 dbname = "octo", host = "localhost", port = 1338,
                 user = "admin", password = "admin")
Listing 1. Connecting to Octo from R.

Getting select vitals for analysis

After connection, this query gets vitals from VistA and joins it to the patient file, restricted to Synthea patients. It returns 48,493 rows of blood pressures, heights and weights.

# One row per measurement, read straight from VistA's vitals global.
vitals <- dbGetQuery(con, "
  SELECT v.patient, v.vital_type, v.rate, v.date_time_vitals_taken,
         p.sex, p.date_of_birth
  FROM   gmrv_vital_measurement v, patient p
  WHERE  v.patient = p.patient_id                      -- vitals to demographics
    AND  v.patient >= 101076 AND v.patient <= 102235   -- the Synthea cohort
    AND  v.vital_type IN (1,8,9)                       -- BP, height, weight
")
Listing 2. Fetching the vitals: one row per measurement, joined to the patient file and restricted to the Synthea cohort and to the three vital types the analysis needs. 48,493 rows.

 
VistA stores each measurement as text in a single field: blood pressure as "120/80", height in inches, weight in pounds.

The listing below massages the vitals data: a patient’s age is computed for every reading, and the systolic and diastolic blood pressures are split apart.

library(dplyr)

# Still one row per measurement. Add the fields the analysis needs:
vitals <- vitals %>% mutate(
  # how old the patient was, in years, when this reading was taken
  age_at = as.numeric(as.Date(date_time_vitals_taken) -
                      as.Date(date_of_birth)) / 365.25,
  # a blood pressure arrives as one string, "120/80", so split it in two
  sys    = as.numeric(ifelse(vital_type == 1, sub("/.*", "", rate), NA)),  # systolic
  dia    = as.numeric(ifelse(vital_type == 1, sub(".*/", "", rate), NA)),  # diastolic
  # height and weight are already a single number: keep it unqualified
  val    = as.numeric(ifelse(vital_type == 1, NA, rate)))
Listing 3. Computing age at each measurement and splitting the blood pressure text. Every later step works from these columns.

Analyzing the growth of children (chart, t-test)

Claude analyzes here the difference between boys and girls. Two statements of R produce the chart:

library(ggplot2)

# Every height reading (vital_type 8) taken before the patient turned 18.
peds <- vitals %>% filter(vital_type == 8, age_at < 18)

# Height against age, one curve per sex.
ggplot(peds, aes(age_at, val, colour = sex, fill = sex)) +
  geom_smooth(method = "loess", span = 0.4) +   # fitted curve + 95% band
  labs(x = "Age (years)", y = "Height (inches)")
Listing 4. The LOESS growth curves behind Figure 1.

 

Line chart of mean height in inches against age from 0 to 18, for girls and boys, with confidence bands. The curves track together until about 13, after which the boys' curve rises above the girls'.
Figure 1. Mean height for age, by sex, with 95% confidence bands, from 4,029 height measurements on 392 patients, taken while the patient was under 18. The literature the title refers to is Marshall and Tanner.1

 
The curves for boys and girls track each other through childhood and then separate in the mid-teens, which is what the literature describes: the adolescent growth spurt arrives “on the average, nearly 2 years later in boys than in girls”,1 while girls are briefly the taller group; boys grow for longer, overtaking girls. At 17, boys average 69.4 inches and girls 64.4 — a difference of 5.0 inches. The Welch two-sample t-test below shows that the height difference at 17 is statistically significant.

> # every height reading taken during the patient's 17th year
> h17 <- peds %>% mutate(age_yr = floor(age_at)) %>% filter(age_yr == 17)
>
> # compare the sexes, without assuming their variances match
> t.test(val ~ sex, data = h17, var.equal = FALSE)

	Welch Two Sample t-test

data:  val by sex
t = -11.437, df = 162.73, p-value < 2.2e-16
alternative hypothesis: true difference in means between group F and group M is not equal to 0
95 percent confidence interval:
 -5.870369 -4.141760
sample estimates:
mean in group F mean in group M
       64.35644        69.36250
Listing 5. Testing the height difference at 17. var.equal = FALSE asks for Welch’s version rather than Student’s, which suits two groups of unequal size (101 girls, 80 boys) with no reason to assume matching variances.

Analyzing hypertension diagnoses vs BMI (chart, chi-square)

Does a hypertension diagnosis go with high body-mass index (BMI)? First, the diagnosis: A VistA problem can be coded in ICD-9, ICD-10 or SNOMED CT. This query asks for all three:

htn <- dbGetQuery(con, "
  SELECT DISTINCT pr.patient_name AS patient
  FROM   problem1 pr, icd_diagnosis i
  WHERE  pr.diagnosis = i.icd_diagnosis_id
    AND  pr.patient_name >= 101076 AND pr.patient_name <= 102235
    AND  i.code_number IN ('401.0','401.1','401.9',   -- ICD-9  essential hypertension
                           'I10.','I15.0')            -- ICD-10 same, VistA spelling
  UNION
  SELECT DISTINCT pr.patient_name AS patient
  FROM   problem1 pr
  WHERE  pr.patient_name >= 101076 AND pr.patient_name <= 102235
    AND  pr.snomed_ct_concept_code IN ('59621000',    -- SNOMED essential hypertension
                                       '38341003')    -- SNOMED hypertensive disorder
")
Listing 6. Finding the hypertensive patients. Note that SNOMED codes are not pointers, so they don’t need a join.

 
Now the BMI. The chi-square test is by patient, not by reading, as the unit of analysis. The measurements are collapsed into one row per adult carrying a mean height, weight and systolic pressure, with the BMI computed from height and weight:

# Collapse to one row per adult patient, averaging their repeated readings.
pat <- vitals %>% filter(age_at >= 18) %>%
  group_by(patient) %>%
  summarise(sex    = first(sex),
            height = mean(val[vital_type == 8], na.rm = TRUE),   # inches
            weight = mean(val[vital_type == 9], na.rm = TRUE),   # pounds
            sys    = mean(sys, na.rm = TRUE)) %>%                # mmHg
  mutate(bmi = 703 * weight / height^2,   # 703 converts lb/in^2 to metric BMI
         # attach the diagnosis found by the query above
         htn = factor(ifelse(patient %in% htn$patient,
                             "Hypertension coded", "Not coded"),
                      levels = c("Not coded", "Hypertension coded")))
Listing 7. Reducing 48,493 measurements to one row per adult patient, carrying a mean height, weight, systolic pressure and the BMI derived from height and weight.

 
Cross-tabulating diagnosis against BMI class gives six cells:

Table 1. The counts the chi-square test in Listing 8 consumes: adults classified by BMI class vs. hypertension diagnosis.
BMI class Hypertension coded Not coded Total
Normal (< 25) 2 152 154
Overweight (25–30) 131 508 639
Obese (30+) 21 104 125

 
A chi-square test of independence is the correct statistical test here: both variables (BMI and Hypertension Diagnosis) are categorical, and every expected cell count comfortably exceeds five. In R that is one line:

> # sort each adult into a BMI class at the standard cut-points
> pat$bmi_class <- cut(pat$bmi, c(-Inf, 25, 30, Inf),
+                      labels = c("Normal", "Overweight", "Obese"))
>
> # cross-tabulate class against diagnosis, and test for independence
> chisq.test(table(pat$bmi_class, pat$htn))

	Pearson's Chi-squared test

data:  table(pat$bmi_class, pat$htn)
X-squared = 32.773, df = 2, p-value = 7.646e-08
Listing 8. Banding adults by BMI and testing the result against the coded hypertension diagnosis, with R’s console output.

 
The same counts, as a chart:

Bar chart showing the percentage of adults with a coded hypertension diagnosis in three BMI classes: 1.3% for normal weight, 20.5% for overweight, 16.8% for obese.
Figure 2. Share of adult patients carrying a coded hypertension diagnosis, by BMI class.

 
The striking cell is the first one in Table 1: only 2 of 154 normal-weight adults carry a hypertension diagnosis. Independence predicts about 26 — the expected count for a cell is its row total times its column total, divided by the grand total, so 154 normal-weight adults × 154 coded hypertensives ÷ 918 adults = 25.8. That gap, repeated across the six cells, is what the chi-square statistic measures.

Analyzing blood pressure measurements vs BMI (chart, Pearson’s coefficient)

So weight predicts the diagnosis of hypertension; does it predict the actual blood pressure?

No. A Pearson correlation asks whether two continuous measures move together in a straight line. Between BMI and systolic pressure, it finds no association:

> # is there a straight-line relationship between BMI and systolic pressure?
> cor.test(pat$bmi, pat$sys)

	Pearson's product-moment correlation

data:  pat$bmi and pat$sys
t = 0.36357, df = 916, p-value = 0.7163
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.05273312  0.07665606
sample estimates:
       cor
0.01201175
Listing 9. Pearson’s correlation between mean BMI and mean systolic pressure across 918 adults.

 
An r of 0.012 means no association worth the name; an r of 1 would be a perfect one. The confidence interval straddles zero, so the data show no evidence of a straight-line link at all. Plotting one against the other makes it plain:

Scatter plot of systolic blood pressure against BMI for adult patients, with a fitted regression line that is essentially horizontal. Annotated r = 0.012, p = 0.72.
Figure 3. Mean BMI against mean systolic blood pressure, one point per adult patient.

 
This is an artifact of Synthea; in real populations BMI and blood pressure are linked: a meta-analysis of 25 randomized trials covering 4,874 participants found that every kilogram of weight lost lowers systolic pressure by about 1 mmHg.2

Distribution of HbA1c (chart)

Claude plotted the distribution of HbA1c — the standard three-month measure of blood-sugar control. A surprise was lurking in the data:

Histogram of mean HbA1c per patient, coloured by whether the patient is on diabetes medication. A cluster near 3% is entirely orange (on medication), a large cluster near 6% is mostly purple. A dashed line at 4% is labelled physiologically impossible.
Figure 4. Mean HbA1c per patient, split by whether the patient is on insulin or metformin.

 
An HbA1c below 4% does not occur in living people. Fifty-nine patients here have one; and all 59 are on insulin or metformin. Treated diabetics, the very patients whose HbA1c matters most, have impossible values. The other 88% of the cohort looks entirely normal.

Here’s how Claude chased the impossible data down:

# Mean HbA1c per patient. lab_data maps LRDFN to DFN via name field to allow us to limit to only Synthea patients
a1c <- dbGetQuery(con, "
  SELECT d.name AS patient, AVG(CAST(r.result_value AS NUMERIC)) AS a1c
  FROM   lab_chem_result r, lab_data d
  WHERE  r.lrdfn = d.lrdfn AND d.parent_file = 2
    AND  d.name >= 101076 AND d.name <= 102235
    AND  r.test = 462 AND r.result_value IS NOT NULL
  GROUP BY d.name")

# Who is on insulin (VA drug class HS501) or an oral hypoglycaemic (HS502)?
rx <- dbGetQuery(con, "
  SELECT p.patient, g.va_drug_class_code
  FROM   prescription p, drug g
  WHERE  p.drug = g.drug_id
    AND  p.patient >= 101076 AND p.patient <= 102235")

on_drug <- unique(rx$patient[grepl("^HS50[12]", rx$va_drug_class_code)])
a1c$treated <- a1c$patient %in% on_drug
table(impossible = a1c$a1c < 4.0, treated = a1c$treated)
          treated
impossible FALSE TRUE
     FALSE   384   49
     TRUE      0   59
Listing 10. The whole finding, in one contingency table. Of 492 patients with an HbA1c, every one of the 59 impossible values belongs to a patient on diabetes medication, and not one untreated patient has one. Reading Synthea’s source confirmed why: each diabetes medication subtracts a fixed amount from the patient’s HbA1c with nothing holding the result above zero, so combination therapy drives it below what a living person can have — reported as synthea#1693.

 
Of note, the glucose values for the same patients were all physiologically normal, which brings us to the next section.

Correlation of glucose and HbA1c (chart, Pearson’s coefficient)

Blood glucose and HbA1c measure the same underlying reality on different timescales, and the relationship between them is well established: the ADAG study3 gives estimated average glucose = 28.7 × HbA1c − 46.7. In real life, glucose and HbA1c should be somewhat correlated. How do they correlate in the data?

Scatter plot of measured glucose against the glucose implied by each patient's HbA1c. A dashed diagonal marks perfect agreement; the fitted line is horizontal and far from it.
Figure 5. Glucose implied by each patient’s HbA1c, against the glucose actually measured. The dashed diagonal is perfect agreement.

 
Clearly, there is no correlation: r = 0.027, p = 0.56 across 492 patients, showing that Synthea data again doesn’t produce realistic data in this scenario. Examination of the Synthea source shows the issue: it selects a glucose at random from a range and derives their HbA1c separately, so the two never have to agree — reported as synthea#1694.

Trying all the analyses for yourself

I published the Docker image with VistA containing 1,160 Synthea patients (1,000 live ones) and Octo ready to go. Run it like this:

docker run -d -p 127.0.0.1:2222:22 -p 127.0.0.1:8001:8001 -p 127.0.0.1:9430:9430 \
    -p 127.0.0.1:8089-8090:8089-8090 -p 127.0.0.1:1338:1338 \
    --name=vehu yottadb/octo-vehu:2026-08-synthea1000
Listing 11. Starting the image I ran everything above against. The last published port, 1338, is ROcto’s.

 
ROcto comes up with the container, so port 1338 is serving as soon as it starts. That is the connection Listing 1 opens, and from there every query in this post works as printed.

Then run analysis.R, the script used to generate the results for this post. It needs R with DBI, RPostgres, dplyr and ggplot2, and it regenerates every figure and every number quoted here — the chi-square, the t-tests, the correlations and all five charts — in a few seconds.

Software used

I used Synthea to generate 1,000 live patients, then imported them into VistA; the instructions are in VistA-FHIR-Data-Loader.

The OSEHRA VistA repo scripts exported the data, which docker-vista reassembled into a new, smaller image yottadb/octo-vehu:2026-08-synthea1000.

The VistA image includes the SQL DDLs from YDBOctoVistA — notably lab_chem_result.sql, which lets you read lab data in VistA, which is not stored in a traditional FileMan format.

YottaDB r2.06 and Octo 1.1.0 inside that image project the M globals to SQL and serve them over the PostgreSQL wire protocol.

I ran the yottadb/octo-vehu:2026-08-synthea1000 image with Docker. It includes R 4.3.1, with sub-modules DBI 1.2.3, RPostgres 1.4.10, dplyr 1.2.1, and ggplot2 4.0.3.

I used Claude Code to investigate the database for potential stories for this blog, to write the R scripts and to prepare the diagrams. It is much better at statistics than I am. I only included statistical concepts I learned in college 20 years ago, including Pearson’s r coefficient, chi-square, and t-tests.

Documentation:


References

1. Marshall WA, Tanner JM. Variations in the pattern of pubertal changes in boys. Arch Dis Child. 1970 Feb;45(239):13–23. Boys reached peak height velocity at a mean age of 14.1 ± 0.14 years, “on the average, nearly 2 years later in boys than in girls”. doi:10.1136/adc.45.239.13. PMID: 5440182. PMCID: PMC2020414. The companion paper for girls is Marshall WA, Tanner JM. Variations in pattern of pubertal changes in girls. Arch Dis Child. 1969 Jun;44(235):291–303, doi:10.1136/adc.44.235.291, PMID: 5785179. ↩

2. Neter JE, Stam BE, Kok FJ, Grobbee DE, Geleijnse JM. Influence of weight reduction on blood pressure: a meta-analysis of randomized controlled trials. Hypertension. 2003 Nov;42(5):878–84. Across 25 randomized trials and 4,874 participants, blood pressure fell by −1.05 mmHg systolic (95% CI −1.43 to −0.66) and −0.92 mmHg diastolic (95% CI −1.28 to −0.55) per kilogram of weight lost. doi:10.1161/01.HYP.0000094221.86888.AE. PMID: 12975389. ↩

3. Nathan DM, Kuenen J, Borg R, Zheng H, Schoenfeld D, Heine RJ; A1c-Derived Average Glucose (ADAG) Study Group. Translating the A1C assay into estimated average glucose values. Diabetes Care. 2008 Aug;31(8):1473–8. The reported regression is AG (mg/dl) = 28.7 × A1C − 46.7, R2 = 0.84, P < 0.0001. doi:10.2337/dc08-0545. PMID: 18540046. PMCID: PMC2742903. ↩


Credits

Access VistA Lab Chemistry Data from Octo

We recently received a feature request for Octo to natively support “Piece of Piece”; e.g., to declare a column in Octo corresponding to a construct like $PIECE($PIECE(^A,"|",3),"^",2). Although Octo could previously represent such a use case with a computed column, a computed column cannot be indexed; so a query will be expensive. Octo now allows such a column to be defined and indexed.

As part of this work, I took the opportunity to implement the extraction of Lab Chemistry Data in VistA. What’s the connection? VistA data is almost always stored as ^ delimited pieces (e.g., A^B^C) or as Extract ranges (ABCXYZ range 1-3 = ABC). Only in the storage of Chemistry Data in the Lab Package do we get a sub-piece: A^B^C1!C2!C3. To make it concrete, here is some made-up Chemistry Data from VistA:

^LR(314452,"CH",6879595.9,0)="3120403.1^1^3120403.110048^111346^73^CH 0403 350^^CBS A^^184920^6D^^1738;SC(^648"
            41)="66^H^82550.0000!82550.0000!2157!4151!!!197^111346^73!28!181!!!!IU/L^^^^648^1"
        "NPC")=3
        "ORU")=1120940350

Notice how under the 41 node, the third ^ separated piece has ! delimited data within it.

Fileman to this day cannot read this data except using computed fields because it cannot represent “piece of piece”. But if you have the latest Octo, you can grab lab_chem_result.sql from YDBOctoVistA to unlock your Lab Data. Here’s how some of the data (the third ^ delimited piece above) is represented in Octo:

 -- Piece 3 (workload) -- "!"-sub-delimited:
  NATIONAL_LAB_CODE`      VARCHAR DELIMS ("^","!") PIECES (3,1), -- 3.1 National Lab Code
  RESULT_NLT_CODE`        VARCHAR DELIMS ("^","!") PIECES (3,2), -- 3.2 Result National Lab Code (+suffix)
  LOINC_CODE`             VARCHAR DELIMS ("^","!") PIECES (3,3), -- 3.3 LOINC (no checksum char)
  WORKLOAD_SUFFIX`        VARCHAR DELIMS ("^","!") PIECES (3,4), -- 3.4 Workload Suffix
  TEST_IEN_FILE_60`       INTEGER DELIMS ("^","!") PIECES (3,7), -- 3.7 IEN pointer to file 60 ^LAB(60,

Here is a sample query and results from fictitious data:

OCTO> select * from LAB_CHEM_RESULT WHERE LRDFN=27 AND RESULT_FLAG='H*';
lrdfn|invdt|test|result_value|result_flag|national_lab_code|result_nlt_code|loinc_code|workload_suffix|test_ien_file_60|verifying_tech|site_specimen|reference_low|reference_high|critical_low|critical_high|units|delta_check_type|delta_value|default_value|therapeutic_low|therapeutic_high|institution|equipment_id
27|6949291.8968|2|350|H*|84330.0000|||3096|175|11743|72|60|110|50|300|mg/dL||||||500|
27|6949681.984076|2|310|H*|84330.0000|||3096|175|11748|72|60|110|50|300|mg/dL||||||500|
27|6949681.984076|132|17.5|H*|81323.0000|||3096|440|11748|72|0|8.9||15|U/L||||||500|
27|6969570.894999|2|321|H*||||3096||20364|72|60|123|50|300|mg/dL||||||500|
27|6999477.92|2|400|H*|84330.0000|||||11748|72|60|123|50|300|mg/dL||||||500|
(5 rows)
OCTO>

Credits

Nimetic – Zero-JS Single Page Applications with Nim, Datastar and YottaDB

We again welcome Lothar Jöckel to the YottaDB blog, with his second guest post, based on a talk he gave at NimConf2026 about his software, Nimetic.

Modern web development is drowning in JavaScript fatigue, but there is a powerful alternative that allows you to build Single Page Applications (SPAs) with zero user client-side JavaScript. In our recent virtual presentation, Nimetic – Building Zero-JS SPAs with Nim, Datastar, and YottaDB, we showcased how to fuse a lightning-fast backend with a robust, hierarchical NoSQL database engine. By combining the hyper-efficient Nim programming language, the real-time event streaming of Datastar, and the battle-tested, daemonless power of YottaDB, developers can completely bypass heavy frontend frameworks without sacrificing reactivity.

Why This Stack Changes Everything

Modern SPAs usually require a massive node_modules folder, complex build pipelines, and heavy hydration steps. Nimetic changes the paradigm by handling state logic on the backend and streaming targeted HTML updates over Server-Sent Events (SSE).

Here is how the three core components interact:

  • Nim Backend: Serves as the hyper-performant backbone using the multi-threaded MummyDS HTTP server. Nim gives us the raw compilation performance of C paired with the clean, elegant readability of Python.
  • Datastar Frontend: A lightweight hypermedia framework (an 11.76KiB file) that uses simple HTML attributes to handle frontend reactivity, using SSE to patch the DOM automatically.
  • YottaDB Storage: The ultimate language-agnostic NoSQL database. It is an ultra-low latency, in-memory, hierarchical key-value store that eliminates the typical database bottlenecks found in real-time web applications.

The Superpower of YottaDB in Nimetic

Integrating a database into a high-performance web app often means dealing with heavy daemons and network latency. YottaDB eliminates these hurdles via its unique architecture. Several key advantages of utilizing YottaDB are:

  • Zero Cost Abstractions via Metaprogramming: Nim’s powerful macro system allowed us to build seamless, zero-cost abstractions on top of the official nim-yottadb language binding. This lets developers access hierarchical globals, native transactions, and database iterations using clean, idiomatic Nim syntax with no runtime performance penalty
  • Daemonless Architecture: Unlike traditional databases, YottaDB runs directly in the process address space of the application. There is no separate daemon process to configure, maintain, or tune. The first process opens the database structures, and the last one cleans them up. This eliminates inter-process and network overhead, making data operations blazingly fast.
  • Rock-Solid ACID Transactions: Even though it scales perfectly down to embedded hardware like a Raspberry Pi (while scaling up to the largest real-time core-banking and electronic health record systems), YottaDB delivers strict, enterprise-grade ACID transactions. For real-time applications handling rapid user state changes, this guarantees absolute data integrity under heavy concurrent loads.
  • Session Persistence: Since the session state is stored in the database, a session can be resumed virtually instantaneously.

Curious About Nim? Check Out These NimConf 2026 Highlights!

If Nimetic has sparked your interest in the Nim programming language, you are not alone. Nim offers a unique blend of systems-level control, Python-like syntax, and an expressive compile-time macro system.

To see what else the Nim ecosystem is capable of, we highly recommend checking out these fantastic sessions from this year’s conference:

You can also look at other talks in the Social & Workflow and Project tracks on YouTube

Get Started Today!

The code and concepts shown at NimConf 2026 prove that backend-driven hypermedia is a viable, high-performance future for web development.

Ready to build your own high-speed, daemonless applications?

I hope you enjoy Nim and YottaDB as much as I do!

Credits

A Visit To Jordan

I spent the week of June 7, 2026 in Amman, Jordan with the DevOps team of Electronic Health Solutions (EHS). We monitored the health of the servers, reorganized the database, brought up a new server, and did training. YottaDB and EHS also signed an extension of our support agreement.

Unlike the slow-moving VistA replacement effort at the US Department of Veterans Affairs (VA), EHS has continued to invest in and modernize VistA, transforming it into Hakeem – a true Jordanian digital health success story. While the VA has largely underinvested in maintaining and evolving VistA, allowing it to be characterized as outdated, EHS has leveraged the platform as a foundation for innovation. Examples include the My Hakeem mobile app for patients, and the Dr@Hakeem app for healthcare providers which enables clinicians to manage appointments, access patient medical records, and support clinical decision-making from anywhere.

Today, several Hakeem implementations are operated or supported by EHS across Jordan.

  • All Jordanians are entitled to free or low cost healthcare, through the Ministry of Health (MoH). The MoH Hakeem system is the largest healthcare information system in the country, connecting all public hospitals and most public clinics through a single VistA-based platform. As a result, a patient from Aqaba receiving treatment in Amman can have their complete medical history accessed instantly. During my visit, I observed peak usage of around 9,000 concurrent users with the infrastructure handling the load effortlessly. This may well be the largest VistA deployment in the world. As the rollout expands to additional clinics, the number of concurrent users is expected to grow further.
  • Members of the Jordanian armed forces, military retirees, and their families receive care through the Jordanian Royal Medical Services (RMS), which operates its customized and integrated Hakeem system. Whie smaller than the MoH deployment, it serves a large and important patient population.
  • The King Hussein Cancer Centre, one of the leading cancer institutions in the Middle East, also operates its own specialized and integrated Hakeem implementation tailored to the unique needs of oncology case.
  • In addition, several smaller, specialized healthcare organizations across Jordan operate Hakeem systems designed to support their specific clinical and operational requirements.

It was not all work and no play. One evening after we were done in the office, my hosts took me to the Dead Sea, about an hour’s drive from Amman. The altimeter on my watch registered 330m below sea level. In comparison, it showed the parts of Amman I was in at around 1000m above sea level – since I did not calibrate it for ambient air pressure, the difference in height is more meaningful than the actual readings.

My hosts were the epitome of graciousness, especially when it came to food. They took me out to wonderful dinners at Khashoka, Alia and Fakhreldin restaurants, and a take-out lunch from one of my personal favorites, Abu Jbara. Jordan has the world’s best falafel in my opinion – you can’t go wrong ordering falafel anywhere, from a hole-in-the-wall to the finest restaurant. It is always crisp outside, soft inside, and tastes delicious. Some places have interesting embellishments such as sesame seeds on the crust. When he learned that I liked mujadara, one of my hosts brought in home-cooked mujadara for my lunch the next day.

Were there any clouds in the silver lining? Yes, two.

  • Since seven out of ten Jordanian men, and almost a third of women, smoke, it’s hard to get away from the odor of tobacco. With a few exceptions, it would not be uncommon for diners at the next table to light up, often ordering shishas from the restaurant. Fortunately, my room at the Grand Hyatt Amman was on a non-smoking floor, and there was no smoking in any of the indoor public areas or at breakfast.
  • From time to time, air-raid sirens would go off as missiles and drones flew through Jordanian airspace, followed by the all-clear a few minutes later. I had not heard air-raid sirens since my college days in India, at the time of the 1971 birth of Bangladesh. People in Amman ignored the sirens and life went on as normal, but they were upsetting to the young son of one of my hosts.

EHS and YottaDB have more than a vendor-customer relationship. We are proud to be a partner in the journey of EHS and Hakeem, the most successful VistA implementation I have seen. It was simultaneously exhilarating and sobering to realize that the medical records of almost everyone I set eyes on resided in a YottaDB database. I always enjoy Jordan, and look forward to my next visit.

Credits

  • Photographs by the author’s camera.
YottaDB as a Creative Platform: Experimental Video Art at Scale

We thank Jordan Lenchitz for his first guest blog post, and hope there are many more to follow. If you would like to post on the YottaDB blog please contact us at info@yottadb.com.

When it comes to experimental video art the database you choose shapes what is possible, what is fast, and what is sustainable.

My Creative Process

Step one: global generation. I build MUMPS routines that encode my compositional ideas into global subscripts. These routines embody the algorithmic decisions that define a unique work of experimental video art. Each run of a MUMPS routine generates thousands of nodes representing frequencies, timings, spatial coordinates, color values, and whatever my experimental video art requires.

Step two: replication filters. My generated globals flow through replication filters to apply the “business logic” for the experimental video art on SI replicas.

Step three: relationalization. SQL queries run on the replicas to map the global subscript structure onto relational tables. This is where the raw algorithmic output becomes queryable: I can ask “give me all frequencies between 400 and 500 hertz” or “find the points where two voices intersect” without regenerating any globals.

Step four: connection to Pure Data. I connect to the SQL database from Pure Data, the realtime visual programming environment, using its PostgreSQL connector. Pure Data reads the relationally mapped data and renders it, synthesizing the audio, driving the visuals, creating the final artwork. The database becomes the bridge between algorithmic conception and sensory experience.

Why YottaDB

I could have used a relational database for steps three and four and stopped there (and many people do!) but then I would have lost steps one and two. I would have written the algorithms in some other language, serialized them into SQL, and given up the expressiveness of MUMPS for algorithmic composition. YottaDB gives me the whole stack. MUMPS is extraordinarily good at manipulating hierarchical data, which is what deeply nested algorithmic composition actually looks like. Global subscripts are how these systems want to be written, not a workaround for something else. The replication layer means I don’t have to choose between computational power and queryability. I can generate at full speed in one environment and expose relational views to Pure Data without exporting or rebuilding anything. The separation between the algorithmic engine and the consumer interface happens at the database layer, not in application code. Performance matters too; generating thousands of data points, running replication filters across all of them, then querying subsets in real time as Pure Data renders is not a trivial workload and YottaDB has no trouble with it.

The Why Behind the Why

Databases are opinionated because they encode assumptions about what data looks like, how you access it, what’s fast, and what’s slow. Most of them assume relational structure from the start but YottaDB assumes you might want hierarchical algorithmic structure first and relational views of that same data later. For my creative work, this is the whole ballgame. Algorithmic composition lives in the hierarchical world where relations come later (as a view!). A database that forces you to think relationally first takes away the tools that make algorithmic thinking natural. YottaDB lets MUMPS be MUMPS and SQL be SQL in the same system, without translation layers or duplication. That has shaped every work of experimental video art I’ve made since 2023. If you’re building systems where algorithmic or hierarchical data generation matters and you need relational queryability later, YottaDB is worth a serious look. It trusts you to think in the structures that actually fit your problem and it will let you make strange and beautiful things.

About Jordan Lenchitz

Jordan Lenchitz is a MUMPS programmer and experimental video artist based in Verona, Wisconsin. He holds degrees in mathematics, French, and music composition from Indiana University and is completing a PhD in music theory and composition at Florida State University. (His dissertation examines listening to a cappella vocal musics as an extension of Eleanor Gibson‘s ecological approach to perception.) His creative work centers on extended just intonation and algorithmic composition as well as contributions to open source projects. You can listen to his video work and contact him through his website.

Credits

Koalas, JSON, r2.04, and AIM

Koalas are some of the cutest animals around, but are listed as vulnerable by the International Union for Conservation of Nature and Natural Resources and listed as endangered by the Australian Department of Climate Change, Energy, the Environment and Water.

I wanted to explore a JSON dataset with the ZYDECODE command introduced in YottaDB r2.04. I found a JSON dataset of Koala records for twenty years to 2014 in Noosa Shire in Queensland, downloaded it, and renamed the file to NoosaShireKoalaRecordsto2014.json. I then loaded the raw data into the line local variable from which I parsed the JSON into the ^koala global variable. Note that ZYDECODE expects the top level of line to be the count of lines that make up the JSON file, which is one less than i, since the last value of i corresponds to when YottaDB encountered the end-of-file.

YDB>set file="/Distrib/Datasets/NoosaShireKoalaRecordsto2014.json" open file use file

YDB>for i=1:1 read line(i) quit:$zeof

YDB>use $principal set line=i-1 zydecode ^koala=line

YDB>

With some knowledge of the schema of the dataset, I used AIM to cross reference the number of koalas seen at each sighting, and determine the maximum number of these asocial animals that were observed at a sighting (which turns out to be 4).

YDB>kill sub set sub(1)="""features""",sub(3)="""properties""",sub(4)="""NUMBER_SEE"""

YDB>set koalanumx=$$XREFDATA^%YDBAIM("^koala",.sub,,,,,,1)

YDB>write $order(@koalanumx@(0,""),-1)
4
YDB>set x="" for  set x=$order(@koalanumx@(0,4,x)) quit:""=x  write x,!
480
744

YDB>

So what are these locations at which four koalas were sighted at a time?

YDB>for x=480,744 write ^koala("features",x,"properties","TOWN"),!
Doonan
Noosa Heads

YDB>

So, if I want to see koalas in Noosa Shire, Doonan and Noosa Heads are the places I should visit!

More importantly, I hope you can see how useful YottaDB r2.04’s ZYDECODE is when used with AIM to explore and analyze JSON datasets. YottaDB r2.04 also has a complementary ZYENCODE command to convert global and local [sub]trees to JSON, using an encoding that allows [sub]trees with values at roots to be converted to JSON and back without data loss using ZYDECODE. We look forward to hearing from you as you try the functionality


Credits

r2.04 – Our Biggest Release Yet

Although it has been over a year since we released r2.02, we have not been idle. Unlike Santa’s elves, who must be ready in time for Christmas no matter what, r2.02 was such a robust release that we had the luxury of taking our time to get things into r2.04 that we wanted to. We couldn’t get everything in – in the software world, there is always something that has to be deferred – but we believe r2.04 was worth the wait.

We originally intended r2.04 to focus on performance, and it does. We blogged about critical section performance in Critical Section Performance in r2.04. But performance took on a life of its own, and we did so much more. Every release adds functionality, and the major functionality added in r2.04 is the ability to convert between M and JSON. And, as with performance, there is so much more in the release than that. You can read the release notes and see the development details. With everything in it, r2.04 is our biggest release yet, reminiscent of the Antonov An-225 Mriya above, which at 253 metric tons had the largest carrying capacity of any aircraft ever built.

Performance

In addition to the critical section performance enhancement, performance related enhancements in r2.04 include:

Below are two graphs to demonstrate the performance improvements in r2.04. The benchmarks were run on a Red Hat Enterprise Linux 10 system using the default garbage collection, i.e, with sorting. In our testing, we did not observe any material difference in performance between ext4 and xfs filesystems.

The benchmarks compare performance on the following YottaDB releases and GT.M versions:

  • YottaDB r2.02, our previous release.
  • GT.M V7.1-002, which has been merged into r2.04.
  • GT.M V7.1-010, the latest GT.M version as of the r2.04 release. Although V7.1-010 is not merged into r2.04, you can compare the performance of r2.04 against V7.1-010.
  • YottaDB r2.04.

In both cases, the y axis is runtime in seconds, i.e., less is better.

The first benchmark simulates interest posting on accounts by a real-time core-banking application.

The second benchmark uses cooperating concurrent processes to calculate the lengths of 3n+1 sequences for integers from 2 through one million.

Observations

  • Both benchmarks show that GT.M V7.1-002 and V7.1-010 perform comparably.
  • Both benchmarks show that with large numbers of processes, many times the number of CPUs, both GT.M versions scale better than YottaDB r2.02, i.e., GT.M V7.1-002 has improved scalability compared to V7.0-005, the GT.M version merged into YottaDB r2.02.
  • The interest posting benchmark clearly shows YottaDB r2.04 outperforming r2.02 and both GT.M versions.
  • The 3n+1 benchmark shows r2.04 outperforming both GT.M versions at all loads, and at the high end scaling up  better than GT.M versions and r2.02 (i.e., having a lower slope).

Even as they highlight the performance of r2.04, the graphs illustrate an important fact about benchmarking: performance characteristics can vary widely between workloads.

Functionality

The most significant functional enhancement in r2.04 is the ability to export (encode / serialize / stringify) [sub]trees as JSON and to import (decode / deserialize / parse) JSON strings into [sub]trees. Since [sub]trees can have values at their roots as well as their own [sub]trees, which JSON does not support, the encoding format allows for such M [sub]trees (i.e., with a $DATA of 11) to be encoded and for the JSON to be re-decoded flawlessly, without any data loss. There are both C and M APIs (see example below); JSON parsing is done using the Jansson library. There are numerous additional enhancements to functionality, including:

Fixes

Every YottaDB release must pass all the tests of predecessor YottaDB releases and more. We find and fix bugs and misfeatures, for example:

Since the upstream GT.M team only releases the source code for each version, but not the automated tests, we create our own automated tests when merging a GT.M version into YottaDB. During the process, we find and fix GT.M bugs and misfeatures, for example:

Note that the titles of issues describing fixes to bugs and misfeatures reflect the correct behavior after we fix the issues, and not issues as originally reported (since a fix may only be indirectly connected with original symptoms reported).

JSON Example

Here is an example of decoding a 29MB JSON string into a global variable, and encoding the global variable back into JSON.

YDB>set jsonfile=$zsearch("work/github/test-data/large-file.json") open jsonfile:readonly

YDB>use jsonfile for i=1:1 read line quit:$zeof  set json(i)=line

YDB>use $principal close jsonfile set json=$order(json(""),-1) write json
11356
YDB>set begin=$zut zydecode ^m=json set end=$zut write $fnumber(end-begin/1000,",")," msec"
553.165 msec
YDB>set begin=$zut zyencode jsonout=^m set end=$zut write $fnumber(end-begin/1000,",")," msec"
847.974 msec
YDB>

The above was executed on a laptop with an Intel i7-1260P CPU.

In Conclusion

Sorry to keep you waiting, but all good things take time. YottaDB r2.04 has landed, and we look forward to hearing from you as you use it.


Credits