Monday, 30 November 2026

Snowstorm Snomed C# MinimalApi and Blazor Client Demo

I created a Snowstorm C# Minimal API and a Blazor Client Demo using Snowstorm Snomed local server to query after Snomed CT codes and display hierarhical relations, that is descendants and ancestors of a Snomed Clinical Term , abbreviated Snomed CT. The Github repository of mine for the source code in this article is available here:

https://github.com/toreaurstadboss/Snowstorm.Snowmed.CSharp

The Minimal Api also retrieves descriptions and synonyms for Snomed CT. A generated client to consume the local Snomed Snowstorm server is available in the file `Snowstormclient.cs` in the Minimal Api. Note : The ISnowstormClient is the generated client using NSwagstudio pointing against the Open API page for the Swagger page of the Snomed Snowstorm server running locally. You can download NSwagstudio from here: https://github.com/RicoSuter/NSwag/wiki/NSwagStudio This file is generated by running the Snomed Snowstorm server using this command in the Server folder:


docker compose up -d


The docker-compose.yml YAML file is available here: https://github.com/toreaurstadboss/Snowstorm.Snowmed.CSharp/blob/5508d03918aacb34554fb30bccfe2337ca7add3e/Server/docker-compose.yml

Docker-compose.yml for Snowstorm Snomed server


# https://github.com/IHTSDO/snowstorm/blob/master/docker-compose.yml

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.19.8
    container_name: elasticsearch
    environment:
      - discovery.type=single-node
      - xpack.security.enabled=false
      - node.name=snowstorm
      - cluster.name=snowstorm-cluster
      - "ES_JAVA_OPTS=-Xms4g -Xmx4g"
    volumes:
      - elastic:/usr/share/elasticsearch/data
    networks:
      elastic:
        aliases:
         - es
    healthcheck:
      test: ["CMD", "curl", "-f", "http://es:9200"]
      interval: 1s
      timeout: 1s
      retries: 60
    ports:
      - 127.0.0.1:9200:9200
    mem_reservation: 4g

  snowstorm:
    image: snomedinternational/snowstorm:latest
    depends_on:
      elasticsearch:
        condition: service_healthy
    environment:
      - elasticsearch.urls=http://elasticsearch:9200
      - JAVA_TOOL_OPTIONS=-Xms2g -Xmx4g --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED
    command: [
      "--elasticsearch.urls=http://es:9200",
    ]
    networks:
      elastic:
        aliases:
         - snowstorm
    ports:
      - "8080:8080"
    volumes:
      - ./rf2:/rf2

networks:
  elastic:
    name: elastic

volumes:
  elastic:



Minimal Api

The Concepts methods for the Snomed CT is gathered in a Minimal Api endpoints are gathered in the IEndpointRouteBuilder extension methods shown below. Note : The ISnowstormClient is the generated client using NSwagstudio pointing against the Open API page for the Swagger page of the Snomed Snowstorm server running locally.

ConceptEndpoints.cs



using Microsoft.AspNetCore.Http.HttpResults;
using System.ComponentModel;

namespace Snowstorm.Snomed.Csharp.MinimalApi;

/// <summary>
/// Maps concept search and lookup endpoints.
/// </summary>
public static class ConceptEndpoints
{
    /// <summary>
    /// Maps the concept search and lookup endpoints.
    /// </summary>
    /// <param name="app">The endpoint route builder.</param>
    /// <param name="branch">The Snowstorm branch to query.</param>
    /// <returns>The endpoint route builder.</returns>
    public static IEndpointRouteBuilder MapConceptEndpoints(this IEndpointRouteBuilder app, string branch = "MAIN")
    {

        //GET: Search concepts by name : /api/concepts
        app.MapGet(
         "/api/concepts/{conceptId}/parents",
         [EndpointName("GetConceptParentsById")]
        [EndpointSummary("Get direct parents of a concept")]
        [EndpointDescription("Returns the direct parents of a SNOMED CT concept.")]
        async Task<Results<Ok<IReadOnlyList<ConceptResponse>>, BadRequest<string>>> (
             [Description("The SNOMED CT concept identifier.")] string conceptId,
             ISnowstormClient snowstormClient,
             IEndpointUtil endpointUtil,
             CancellationToken cancellationToken) =>
         {
             return await endpointUtil.GetListAsync(
                 conceptId,
                 (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptParentsAsync(
                     snowstormClient,
                     branch,
                     searchTerm,
                     token),
                 cancellationToken);
         });

        app.MapGet(
                "/api/concepts",
                [EndpointName("SearchConcepts")]
        [EndpointSummary("Search concepts by name")]
        [EndpointDescription("Returns matching active SNOMED CT concepts with their preferred name and concept identifier.")]
        async Task<Results<Ok<IReadOnlyList<ConceptResponse>>, BadRequest<string>>> (
                    [Description("The concept name or term to search for.")] string? term,
                    ISnowstormClient snowstormClient,
                    IEndpointUtil endpointUtil,
                    CancellationToken cancellationToken) =>
                {
                    return await endpointUtil.GetListAsync(
                        term,
                        (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptsAsync(
                            snowstormClient,
                            branch,
                            searchTerm,
                            token),
                        cancellationToken);
                });

        //GET: Search concepts by identifier : /api/concepts/{conceptId}
        app.MapGet(
                "/api/concepts/{conceptId}",
                [EndpointName("GetConceptById")]
        [EndpointSummary("Get a concept by identifier")]
        [EndpointDescription("Returns an active SNOMED CT concept with the requested identifier.")]
        async Task<Results<Ok<ConceptResponse>, NotFound>> (
                    [Description("The SNOMED CT concept identifier.")] string conceptId,
                    ISnowstormClient snowstormClient,
                    CancellationToken cancellationToken) =>
                {
                    var concept = await ConceptEndpointsImplementation.GetConceptByIdAsync(
                        snowstormClient,
                        branch,
                        conceptId,
                        cancellationToken);

                    return concept is null
                        ? TypedResults.NotFound()
                        : TypedResults.Ok(concept);
                });

        app.MapGet(
            "/api/concepts/{conceptId}/descriptions",
            [EndpointName("GetConceptDescriptionsById")]
        [EndpointSummary("Get concept descriptions by identifier")]
        async Task<Results<Ok<IReadOnlyList<ConceptDescriptionResponse>>, BadRequest<string>>> (string conceptId,
            ISnowstormClient snowstormClient,
            IEndpointUtil endpointUtil,
            CancellationToken cancellationToken) =>
            {
                var concepts = await endpointUtil.GetListAsync(
                    conceptId,
                    (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptDescriptionsAsync(
                        snowstormClient,
                        branch,
                        searchTerm,
                        token),
                    cancellationToken);
                return concepts;
            });

        app.MapGet(
            "/api/concepts/{conceptId}/descendants",
            [EndpointName("GetConceptDescendantsById")]
        [EndpointSummary("Get conceptdescendants by identifier")]
        async Task<Results<Ok<IReadOnlyList<ConceptResponse>>, BadRequest<string>>> (string conceptId,
            ISnowstormClient snowstormClient,
            IEndpointUtil endpointUtil,
            CancellationToken cancellationToken) =>
            {
                var descendants = await endpointUtil.GetListAsync(
                    conceptId,
                    (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptDescendantsAsync(
                        snowstormClient,
                        branch,
                        searchTerm,
                        token),
                    cancellationToken);

                return descendants;
            });

        app.MapGet(
         "/api/concepts/{conceptId}/ancestors",
         [EndpointName("GetConceptAncestorsById")]
        [EndpointSummary("Get conceptancestors by identifier")]
        async Task<Results<Ok<IReadOnlyList<ConceptResponse>>, BadRequest<string>>> (string conceptId,
         ISnowstormClient snowstormClient,
         IEndpointUtil endpointUtil,
         CancellationToken cancellationToken) =>
         {
             var ancestors = await endpointUtil.GetListAsync(
                 conceptId,
                 (searchTerm, token) => ConceptEndpointsImplementation.SearchConceptAncestorsAsync(
                     snowstormClient,
                     branch,
                     searchTerm,
                     token),
                 cancellationToken);

             return ancestors;
         });

        return app;
    }
}



The ConceptEndpointsImplementation static class contains the static methods that implement the retrieval of Concepts using the generated client for the local Snowstorm Snomed CT server.

ConceptEndpointsImplementation.cs



using System.Text.Json;

namespace Snowstorm.Snomed.Csharp.MinimalApi;

/// <summary>
/// Provides helper operations for concept endpoints.
/// </summary>
internal static class ConceptEndpointsImplementation
{
    internal static async Task<ConceptResponse?> GetConceptByIdAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        CancellationToken cancellationToken)
    {
        var searchResult = await QueryConceptsAsync(
            snowstormClient,
            branch,
            term: null,
            conceptIds: [conceptId],
            limit: 1,
            cancellationToken);

        var concept = searchResult.Items.FirstOrDefault();
        return concept is null ? null : MapConcept(concept);
    }

    private static Task<ItemsPage> QueryConceptsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string? term,
        IEnumerable<string>? conceptIds,
        int limit,
        CancellationToken cancellationToken)
    {
        return snowstormClient.FindConceptsAsync(
            branch,
            activeFilter: true,
            definitionStatusFilter: null,
            module: null,
            term: term,
            termActive: true,
            descriptionType: null,
            language: ["en"],
            preferredIn: null,
            acceptableIn: null,
            preferredOrAcceptableIn: null,
            ecl: null,
            effectiveTime: null,
            isNullEffectiveTime: null,
            isPublished: null,
            statedEcl: null,
            includeLeafFlag: null,
            form: null,
            conceptIds: conceptIds,
            returnIdOnly: false,
            offset: 0,
            limit: limit,
            searchAfter: null,
            accept_Language: "en",
            cancellationToken);
    }

    private static Task<ItemsPageDescription_Component> QueryDescriptionsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        IEnumerable<string>? conceptIds,
        int? limit,
        int? offset,
        CancellationToken cancellationToken)
    {
        return snowstormClient.FindDescriptionsAsync(
            branch,
            conceptIds: conceptIds,
            conceptId: conceptId,
            limit: limit,
            descriptionIds: null,
            offset: offset,
            cancellationToken: cancellationToken);
    }

    internal static async Task<IReadOnlyList<ConceptResponse>> SearchConceptDescendantsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        CancellationToken token,
        bool? stated = null,
        int? offset = null,
        int? limit = null,
        string? acceptLanguage = null
        )
    {
        var descendants = await snowstormClient.FindConceptDescendantsAsync(branch, conceptId, stated, offset, limit, acceptLanguage, token);
        return descendants.Items.Select(MapConcept).OrderBy(c => c.Name).ToArray();
    }

    internal static async Task<IReadOnlyList<ConceptResponse>> SearchConceptParentsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        CancellationToken cancellationToken)
    {
        var parents = await snowstormClient.FindConceptParentsAsync(
            branch, conceptId, form: null, includeDescendantCount: null, accept_Language: "en", cancellationToken);

        return parents
            .Select(parent => new ConceptResponse(parent.Pt.Term, parent.ConceptId))
            .OrderBy(parent => parent.Name)
            .ToArray();
    }

    internal static async Task<IReadOnlyList<ConceptResponse>> SearchConceptAncestorsAsync(
      ISnowstormClient snowstormClient,
      string branch,
      string conceptId,
      CancellationToken token,
      Form4? form = null,
      string? acceptLanguage = null
      )
    {
        var descendants = await snowstormClient.FindConceptAncestorsAsync(branch, conceptId, form, acceptLanguage, token);
        return descendants.Select(MapConcept).OrderBy(c => c.Name).ToArray();
    }

    internal static async Task<IReadOnlyList<ConceptDescriptionResponse>> SearchConceptDescriptionsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string conceptId,
        CancellationToken cancellationToken)
    {
        var searchResult = await QueryDescriptionsAsync(
            snowstormClient,
            branch,
            conceptId: conceptId,
            conceptIds: null,
            limit: 100,
            offset: 0,
            cancellationToken: cancellationToken);

        return searchResult.Items
            .Select(MapConceptDescription)
            .ToArray();
    }

    internal static async Task<IReadOnlyList<ConceptResponse>> SearchConceptsAsync(
        ISnowstormClient snowstormClient,
        string branch,
        string term,
        CancellationToken cancellationToken)
    {
        var searchResult = await QueryConceptsAsync(
            snowstormClient,
            branch,
            term,
            conceptIds: null,
            limit: 100,
            cancellationToken);

        return searchResult.Items
            .Select(MapConcept)
            .OrderBy(c => c.Name)
            .ToArray();
    }

    private static ConceptResponse MapConcept(object item)
    {
        var concept = item switch
        {
            ConceptMini conceptMini => conceptMini,
            JsonElement jsonElement => jsonElement.Deserialize<ConceptMini>()
                ?? throw new InvalidOperationException("Snowstorm returned an empty concept."),
            _ => throw new InvalidOperationException("Snowstorm returned a concept in an unexpected format.")
        };

        return new ConceptResponse(concept.Pt.Term, concept.ConceptId);
    }

    private static ConceptDescriptionResponse MapConceptDescription(object item)
    {
        var conceptDescription = item switch
        {
            Description_Component description => description,
            JsonElement jsonElement => jsonElement.Deserialize<Description_Component>()
                ?? throw new InvalidOperationException("Snowstorm returned an empty concept."),
            _ => throw new InvalidOperationException("Snowstorm returned a concept in an unexpected format.")
        };

        return new ConceptDescriptionResponse(conceptDescription.Term, conceptDescription.DescriptionId, conceptDescription.Type, conceptDescription.ConceptId);
    }

}



Please note the tailored deserialization of ConceptMini done above here to get concepts and concept description. Most often we do type safe access to Snowstorm Snomed Ct objects, but now and then we have to resort to tailored Json deserializaton shown above in the code snippet. The EndpointUtil contains some helper methods for Minimal Api to retrieve list objects or BadRequest, similar to a Maybe monad. It is often used in Minimal Api

EndpointUtil.cs



using Microsoft.AspNetCore.Http.HttpResults;

namespace Snowstorm.Snomed.Csharp.MinimalApi;

/// <summary>
/// Provides common behavior for search endpoints.
/// </summary>
public interface IEndpointUtil
{
    /// <summary>
    /// Validates a search term and returns the matching results.
    /// </summary>
    /// <typeparam name="TResponse">The response item type.</typeparam>
    /// <param name="term">The search term supplied by the request.</param>
    /// <param name="searchAsync">The search operation to execute for a valid term.</param>
    /// <param name="cancellationToken">The token used to cancel the search.</param>
    /// <returns>A bad request for a missing term or the search results.</returns>
    Task<Results<Ok<IReadOnlyList<TResponse>>, BadRequest<string>>> GetListAsync<TResponse>(
        string? term,
        Func<string, CancellationToken, Task<IReadOnlyList<TResponse>>> searchAsync,
        CancellationToken cancellationToken);
}

/// <summary>
/// Implements common behavior for search endpoints.
/// </summary>
public sealed class EndpointUtil : IEndpointUtil
{
    public async Task<Results<Ok<IReadOnlyList<TResponse>>, BadRequest<string>>> GetListAsync<TResponse>(
        string? term,
        Func<string, CancellationToken, Task<IReadOnlyList<TResponse>>> searchAsync,
        CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(searchAsync);

        if (string.IsNullOrWhiteSpace(term))
        {
            return TypedResults.BadRequest("A search term must be provided in the 'term' query parameter.");
        }

        var results = await searchAsync(term, cancellationToken);
        return TypedResults.Ok(results);
    }
}



Blazor client using the Minimal Api consuming the local Snowstorm Snomed CT server

Here are some screenshots showing a Blazor client using the Minimal Api consuming the local Snowstorm Snomed CT server.
Screenshots for the Blazor client

Monday, 9 November 2026

Snowstorm - Local Snomed CT terminology server

If you want to do some development against Snomed CT terminology server, you can download Snowstorm, an open source terminogy server with support for Snomed CT. It is primarily written in Java and built on top of ElasticSerach. The easiest way of getting Snowstorm running in your local development server (or on an actual server if desired), is to download the Docker images for Elasticsearch and Snowstorm. I have added a Yaml file on my Github repo for installing both Elasticsearch and Snowstorm here:

docker-compose.yml
docker-compose.yml

The Yaml file sets up the following for Elastsearch and Snowstorm :

Elasticsearch

  • Sets up Elasticsearch as a service that Snowstorm depends upon on port 9200
  • Pulls Elasticsearch version 8.19.8. You obviously want to test out even newer versions of Elasticsearch later on
  • Sets up a durable volume for Elasticseachon elastic:/usr/share/elasticsearch/data
  • Snomed depends upon Elasticsearch and the condition must be healthy of Elasticsearch from the healthchecks
  • Memory reservation is set to 4 GB for ElasticSearch
  • Since in this example Elasticsearch is set up to run in LocalDEV, xpack.security.enabled is set to false. This turns off authorization, authentication, TLS and audit since the example setup in this docker compose file is meant for development environments, not for production.

Snowstorm

  • Sets up Snowstorm to use Elasticsearch as a service on port 9200
  • Snowstorm is set up to run on 8080 (HTTP)
  • A bind mount is set up on ./rf2 that is on the host computer and mapped to the ./rf2 folder in the container. We use this bind mount to import the Rf2 file later on

docker-compose.yml



# https://github.com/IHTSDO/snowstorm/blob/master/docker-compose.yml

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.19.8
    container_name: elasticsearch
    environment:
      - discovery.type=single-node
      - xpack.security.enabled=false
      - node.name=snowstorm
      - cluster.name=snowstorm-cluster
      - "ES_JAVA_OPTS=-Xms4g -Xmx4g"
    volumes:
      - elastic:/usr/share/elasticsearch/data
    networks:
      elastic:
        aliases:
         - es
    healthcheck:
      test: ["CMD", "curl", "-f", "http://es:9200"]
      interval: 1s
      timeout: 1s
      retries: 60
    ports:
      - 127.0.0.1:9200:9200
    mem_reservation: 4g

  snowstorm:
    image: snomedinternational/snowstorm:latest
    depends_on:
      elasticsearch:
        condition: service_healthy
    environment:
      - elasticsearch.urls=http://elasticsearch:9200
      - JAVA_TOOL_OPTIONS=-Xms2g -Xmx4g --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED
    command: [
      "--elasticsearch.urls=http://es:9200",
    ]
    networks:
      elastic:
        aliases:
         - snowstorm
    ports:
      - "8080:8080"
    volumes:
      - ./rf2:/rf2

networks:
  elastic:
    name: elastic

volumes:
  elastic:


A component diagram (UML) of the Rf2 format is shown below. Note that RefsetItem is extensible and contain additional fields depending on the refset type.

Obtaining Rf2 files with Snomed Ct for Snowstorm

One way of obtaining Snomed Ct Rf2 files is to head over to National Clinical Terminology Service (NCTS) in Australia. They offer individual access to Snomed CT Rt2 files after a quick registration.
The Digital Health Implementer Hub has a Native Snomed Ct Rf2 file page here. Note that this comes with the Australian Snomed CT-AU bundle, but includes the International core terminology data set. https://implementer.digitalhealth.gov.au/ncts/native-snomed-ct-rf2-files This page has an entity relationship diagram shown below for the Rf2 data: One tip concerning uploading a backup of the Rf2 file to Github is to use 7-zip and split up the volume into multiple files. You can upload 100 MB in maximum file sizes to Github. The Snomed Ct-AU file is about 890 MB as of November 2026. When you have the Rf2 files uploaded to the folder Rf2, a subdir of where you started the docker compose yaml file, make sure the Rf2 folder contains the .Zip file with the Rf2 file containing the Snomed CT file to import into the Snowstorm service running with Elasticsearch.


Starting up Snowstorm

Navigate to the folder where we have the docker-compose.yml file and just start up the Docker compose file. Start up Docker for Desktop to be sure Docker service is running.

Please note that when doing the import, it can be easier to view all the logs if running the docker command from the command line. You can see the Logs inside Docker Desktop, but the commandline will be more verbose. As noted, make sure you have the Rf2 subfolder. The bat file below contains a small script that will copy the extracted ALL zip file (you will have to obtain the Rf2 file yourself due to the fact it requires registration), so adjust the folder and file.

CopySnomedInternationalRf2.bat



mkdir rf2
cd rf2
xcopy C:\src\Snowstorm.Snowmed.Rf2_International_Distribution\NCTS_SCT_RF2_DISTRIBUTION_32506021000036107-20261031-ALL.zip .



To get Snowstorm up and running with Elasticsearch, just run this command (note that the first time, Docker images will be pulled for Snowstorm and Elasticsearch, so it will take some time until they are downloaded :




docker compose up



The containers are spinning up rather quickly and you can switch over to Docker Desktop via the "v" shortcut.

Opening up the Swagger page for Snowstorm


The Swagger page is opened up at http://localhost:8080 when the containers are running. The next step now is to import the Snomed Ct Rf2 file. The following Powershell script can be used to import the Rf2 file. Adjust it with the Rf2 file you got. But we have downloaded the FULL Snomed-CT AU file here , so make sure you set the 'type' to FULL !

StartImportNctsSctRf2.ps1

The Powershell script below POST the Rf2 file to the imports/start-local-file-import endpoint. The upload will usually take 15-30 minutes. Since the docker-compose.yml has set up a volume, you do not have to do this everytime. The container got a volume for persistence.


$body = @{
    branchPath = "MAIN"
    filePath = "/rf2/NCTS_SCT_RF2_DISTRIBUTION_32506021000036107-20261031-ALL.zip"
    type = "FULL"
    createCodeSystemVersion = $true
} | ConvertTo-Json

Write-Host $body

Write-Host Starting import...

$response = Invoke-RestMethod `
    -Uri "http://localhost:8080/imports/start-local-file-import" `
    -Method Post `
    -ContentType "application/json" `
    -Body $body


Write-Host Retrieving response from the start-local-file-import
$response | ConvertTo-Json -Depth 10


Saturday, 31 October 2026

Snomed Ct Codes - Validation using Verhoeff algorithm

In this article, an algorithm for validating Snomed Ct codes using a control digit will be presented. The source code in this article is available in my Github repo here :
🕸️https://github.com/toreaurstadboss/SnomedCtTools

Snomed Ct stands form Systemized Nomenclature Of MEDicine - Clinical Terms It is an international standard of terminology used in Electronic Health Records (EHR), also known as patient journals. It has also national extensions in addition to its shared 370,000 items. Norway for example has 16,000 national (local) items.

To validate Snomed Ct codes we use the Verhoeff algorithm.

The Verhoeff algorithm calculates a checksum for error detection. Snomed Ct codes use the algorithm for the checksum, which is the last digit in its code. It was first published in 1969 by Dutch matematician Jacobus Verhoeff. It was also discovered much later by German matematician Peter Gumm in 1985, which then included a formal proof
in addition. The theory is based upon Group theory. The algorithm detects all single digit errors (one digit wrong) or format errors, one digit inserted or left out or transpositions (interchanging two adjacent digits). The research paper is here:

👉🏻 https://www.researchgate.net/publication/3084126_A_new_class_of_check-digit_methods_for_arbitrary_number_systems_Corresp

An easier overview of the algorithm is exaplained on the Wikipedia article of Verhoeff algorithm: 📖 https://en.wikipedia.org/wiki/Verhoeff_algorithm

First off we consider a multiplication table for the algorithm, D. It is also called the Cayley table, more description on that in the following Wikipedia page:

📗 https://en.wikipedia.org/wiki/Cayley_table. The Cayley table of the Dihedral group D5 is used in the Verhoeff algorithm.

VerhoeffValidator.cs - Multiplication matrix P - Cayley table D of Dihedral (5 sided polygon) Group D5



  private static readonly int[,] D =
  {
      { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
      { 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 },
      { 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 },
      { 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 },
      { 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 },
      { 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 },
      { 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 },
      { 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 },
      { 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 },
      { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }
  };



The permutations table P is applying permutations for the numbers 0-9 iteratively with the permutation (1 5 8 9 4 2 7 0)(3 6) We end up with an iterative mapping of permutations for each row

1 -> 5 -> 8 -> 9
^              |
|              v
0 <- 7 <- 2 <- 4

3 <-> 6

VerhoeffValidator.cs - Permutations matrix P


  private static readonly int[,] P =
  {
      { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
      { 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 },
      { 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 },
      { 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 },
      { 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 },
      { 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 },
      { 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 },
      { 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 }
  };




The Verhoeff validation check then becomes the following method, where we perform an algorithm that does the following calculation for the checksum c :
VERHOEFF ALGORITHM - CHECKSUM CALCULATION

1. Create an array n from the digits of the number, read right to left (rightmost digits become n_0 and so on) - i.e. reversal of the digits
2. Initialize the checksum c to zero :    c = 0.
3. For each index i of the array n, starting at zero, replace c with the following : 
   D(c, P(i mod 8, n_i))          
Note that the calculations here uses array lookup of D and P. The mod here is the standard modulo operator, % , n_i is the n-th element. 4. Check that the final value of c is 0 : c = 0


  /// <summary>
    /// Checks whether a number has a valid Verhoeff check digit.
    /// </summary>
    /// <param name="number">The numeric identifier, including its check digit.</param>
    /// <returns><see langword="true" /> when the number passes the Verhoeff check.</returns>
    public static bool IsValidVerhoeff(string code)
    {
        int[] digits = code
            .Select(character => int.Parse(character.ToString()))
            .Reverse()
            .ToArray();
        int checksum = 0;

        for (int index = 0; index < digits.Length; index++)
        {
            checksum = D[checksum, P[index % 8, digits[index]]];
        }

        return checksum == 0;
    }


A more mathematical formulation :
VERHOEFF CHECKSUM VALIDATION

Let n = (n₀, n₁, ..., nₖ₋₁) denote the digits of the identifier in reverse order,
where n₀ is the rightmost digit.

Initialize

    c₀ = 0

For each position i = 0, ..., k − 1 compute

    cᵢ₊₁ = D(cᵢ, P(i mod 8, nᵢ))

where

    D : {0,...,9} × {0,...,9} → {0,...,9}

is the Cayley table derived from the dihedral group D₅, and

    P : {0,...,7} × {0,...,9} → {0,...,9}

is the position-dependent digit permutation.

The identifier is valid if and only if

    cₖ = 0.

Snomed Ct validator

Snomed Ct codes validates in addition that the code is numerical (only digits) and has a length between 6 to 18 digits. Our validator will accept whitespace and normalizes the code be removing whitespace.

using System.Text.RegularExpressions;

namespace SnomedCtTools.Lib.Validation;


public static class SnomedCtValidator
{

    /// <summary>
    /// Checks if a Snomed Ct Code is valid.
    /// It should be :
    /// - 6 to 18 digits
    /// - All numerics (this method washes away whitespace anyways)
    /// - Passes the Verhoeff's dihedral check, which is checked by this 
    /// method internally.
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns>
    public static bool IsValidSnomedCt(string code)
    {
        if (string.IsNullOrWhiteSpace(code))
        {
            return false;
        }
        //normalize whitespace to allow flexibility concerning whitespace
        string normalizedCode = Regex.Replace(code, @"\s+", "");
        if (!normalizedCode.All(c => char.IsDigit(c)))
        {
            return false;
        }

        if (normalizedCode.Length < 6 || normalizedCode.Length > 18)
        {
            return false;
        }

        bool isValid = VerhoeffValidator.IsValidVerhoeff(normalizedCode);
        return isValid;
    }

}


Some unit tests validates well known Snomed Ct codes and also checks that erroneous codes are flagged as not valid code. This is done by looking at the last digit, which is the checksum and using the Verhoeff algorithm and checking we are between 6-18 digits in length as noted. And also, we normalize and remove whitespace to offer some flexibility.


using FluentAssertions;
using NUnit.Framework;
using SnomedCtTools.Lib.Validation;

namespace SnomedCtTools.Tests.Validation
{

    [TestFixture]
    public class SnomedCtValidatorTests
    {

        [Test]
        [TestCase("44054006", true, Description = "diabetes type 2")]
        [TestCase("440540006", false, Description = "not a snomed ct code")]
        [TestCase("67148009", true, Description = "Podagra")]
        [TestCase("671480091", false, Description = "not a snomed ct code")]
        public void SnomedCtValidationCheckForWellknownDiseases(string code, bool expected)
        {
            SnomedCtValidator.IsValidSnomedCt(code).Should().Be(expected);
        }

        [Test]
        [TestCase("24700007", true)]
        [TestCase("2470", false)]
        [TestCase("2470000000000000000000000000007", false)]
        public void SnomedCtValidationChecksLengthCorrect(string code, bool expected)
        {
            SnomedCtValidator.IsValidSnomedCt(code).Should().Be(expected);
        }

        [Test]
        [TestCase("24700007", true)]
        [TestCase(" 24700007", true)]
        [TestCase("24700007 ", true)]
        [TestCase("2470 0007  ", true)]
        [TestCase("2  470 00  07  ", true)]
        public void SnomedCtValidationAcceptsWhiteSpace(string code, bool expected)
        {
            SnomedCtValidator.IsValidSnomedCt(code).Should().Be(expected);
        }

        [Test]
        [TestCase("24700007", true)]
        [TestCase("k24700007", false)]
        [TestCase("24700007#", false)]
        [TestCase("2470@k0007kk", false)]
        [TestCase("2kk3k#@!470###00kk07ll", false)]
        public void SnomedCtValidationCheckIlleagalChars(string code, bool expected)
        {
            SnomedCtValidator.IsValidSnomedCt(code).Should().Be(expected);
        }

    }

}


Generating a checksum for an arbitrary new Snomed code

The updated version of VerhoeffValidator.cs below includes another method that calculates the control digit. The Algorithm for the Verhoeff control digit is as follows.
VERHOEFF CHECKSUM GENERATION

Given input n of length k, n_k, append the digit 0 at the end to give 
a new input of n_k+1

Let n_k+1 = (n₀, n₁, ..., nₖ) where n_k = 0 ,  denote the digits of the identifiers, the elements are then 
reversed in order,
where n₀ is the rightmost digit (0)

Initialize

    c₀ = 0

For each position i = 0, ..., k − 1 compute

    cᵢ₊₁ = D(cᵢ, P(i mod 8, nᵢ))

where

    D : {0,...,9} × {0,...,9} → {0,...,9}

is the Cayley table derived from the dihedral group D₅, and

    P : {0,...,7} × {0,...,9} → {0,...,9}

is the position-dependent digit permutation.

The identifier is valid if and only if

    cₖ = 0.
    
The generated checksum digit then is the lookup using c of the multiplicative inverse of a digit in J.
    

As shown earlier, this is similar to the Verhoeff validation algorithm, but we append 0 at the end and then run the Verhoeff algorithm to yield the Verhoeff control digit at the end. It is this checksum that then is to be appended to the code with the Verhoeff control digit to get the correct Snomed code. The updated code below shows some additional optimizations of using byte and char datatypes and the added method to generate Verhoeff control digit.



namespace SnomedCtTools.Lib.Validation;

/// <summary>
/// Validates numeric identifiers using the Verhoeff check digit algorithm.
/// </summary>
public static class VerhoeffValidator
{
    /// <summary>
    /// Checks whether a number has a valid Verhoeff check digit.
    /// </summary>
    /// <param name="number">The numeric identifier, including its check digit.</param>
    /// <returns><see langword="true" /> when the number passes the Verhoeff check.</returns>
    public static bool IsValidVerhoeff(string code)
    {
        int checksum = CalculateChecksum(code);
        return checksum == 0;
    }  

    /// <summary>
    /// Generates the Verhoeff digit, which is the check digit to be appended to code
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns>
    public static char GenerateVerhoeff(string code)
    {
        string normalizedCode = code + "0";
        int checkSum = CalculateChecksum(normalizedCode);
        string checkDigit = J[checkSum].ToString();
        return checkDigit[0];
    }

    private static readonly byte[,] D =
    {
        { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        { 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 },
        { 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 },
        { 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 },
        { 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 },
        { 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 },
        { 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 },
        { 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 },
        { 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 },
        { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }
    };

    private static readonly byte[,] P =
    {
        { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        { 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 },
        { 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 },
        { 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 },
        { 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 },
        { 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 },
        { 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 },
        { 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 }
    };

    private static readonly int[] J =
    {
        0,4,3,2,1,5,6,7,8,9
    };

    private static byte CalculateChecksum(string code)
    {
        byte[] digits = code
                    .Select(character => byte.Parse(character.ToString()))
                    .Reverse()
                    .ToArray();
        byte checksum = 0;

        for (int index = 0; index < digits.Length; index++)
        {
            checksum = D[checksum, P[index % 8, digits[index]]];
        }
        return checksum;
    }

}


We also have some tests that then can test the control digit generation.


using FluentAssertions;
using NUnit.Framework;
using SnomedCtTools.Lib.Validation;

namespace SnomedCtTools.Tests.Validation
{

    [TestFixture]
    public class SnomedCtValidatorTests
    {

        [Test]
        [TestCase("44054006", true, Description = "diabetes type 2")]
        [TestCase("440540006", false, Description = "not a snomed ct code")]
        [TestCase("67148009", true, Description = "Podagra")]
        [TestCase("76148009", false, Description = "not a snomed ct code")]
        public void SnomedCtValidationCheckForWellknownDiseases(string code, bool expected)
        {
            SnomedCtValidator.IsValidSnomedCt(code).Should().Be(expected);
        }

        [Test]
        [TestCase("4405400", "44054006", Description = "diabetes type 2")]
        [TestCase("4405k40006", null, Description = "not a valid snomed ct code")]
        [TestCase("6714800", "67148009", Description = "Podagra")]
        [TestCase("-671480091", null, Description = "not a snomed ct code")]
        [TestCase("5079700", "50797007", Description = "Bubonic plague")]
        [TestCase("2807200", "28072004", Description = "Cauliflower ear / Blomkåløre")]
        public void SnomedCtValidationAppendsCorrectCheckDigit(string code, string expected)
        {
            SnomedCtValidator.GenerateSnomedCtCode(code).Should().Be(expected);
        }

        [Test]
        [TestCase("24700007", true)]
        [TestCase("2470", false)]
        [TestCase("2470000000000000000000000000007", false)]
        public void SnomedCtValidationChecksLengthCorrect(string code, bool expected)
        {
            SnomedCtValidator.IsValidSnomedCt(code).Should().Be(expected);
        }

        [Test]
        [TestCase("24700007", true)]
        [TestCase(" 24700007", true)]
        [TestCase("24700007 ", true)]
        [TestCase("2470 0007  ", true)]
        [TestCase("2  470 00  07  ", true)]
        public void SnomedCtValidationAcceptsWhiteSpace(string code, bool expected)
        {
            SnomedCtValidator.IsValidSnomedCt(code).Should().Be(expected);
        }

        [Test]
        [TestCase("24700007", true)]
        [TestCase("k24700007", false)]
        [TestCase("24700007#", false)]
        [TestCase("2470@k0007kk", false)]
        [TestCase("2kk3k#@!470###00kk07ll", false)]
        public void SnomedCtValidationCheckIlleagalChars(string code, bool expected)
        {
            SnomedCtValidator.IsValidSnomedCt(code).Should().Be(expected);
        }

    }

}



The tests passes !