Introduction KRANE™ Knowledge Base
Working version v2.17.1 - App version 1.30
Working version v2.17.1 - App version 1.30 English Dutch

Guide: Custom Questionnaire scoring and processing

In this guide we will subscribe to questionnaire answers, process the answers, and return (and save) a result based on the answers. This guide will assume that Python is used and that the script is run locally or on your own infrastructure.

Before you start

In order to use this guide it is recommended to be be familiar with https://pulsar.apache.org/.

The message bus in KRANE is mainly used for internal communication. As such we don’t guarantee the stability of this internal async API. Message types, schemas, topics and namespaces can change at any time.

In the future we expect to expose certain namespaces and topics in a stable matter using either gRPC, MQTT or native Pulsar connections.

Step-by-step

Connect to Pulsar

You will start by subscribing to the Pulsar topic where questionnaire answers are published.

To subscribe to commands, events and other messages on KRANE you will first need to connect to the Pulsar broker on pulsar+ssl://pulsar.krane.one. An authentication taken needs to be passed to be able to successfully connect.

Note that at this time, Pulsar tokens cannot be generated automatically. If you need access to Pulsar please contact Orikami support and we will review you request and generate a token with the appropriate permissions.

For this guide we will assume the token has consume permissions on the krane/questionnaires/answers-in-{ORG_NAME} topic and produce,consume permissions on krane/experiments/{ORG_NAME}-events.

Subscribe to questionnaire answers

First we will create the Pulsar connection and the consumer (subscription):

Python
import pulsar

TOKEN = ""
ORG_NAME = ""

pulsar_client = pulsar.Client("pulsar+ssl://pulsar.krane.one", authentication=pulsar.AuthenticationToken(TOKEN))

questionnaire_consumer = pulsar_client.subscribe(f"krane/questionnaires/answers-in-{ORG_NAME}", "my_subscription")

By default subscriptions are Shared subscriptions. This means that multiple clients can subscribe on the topic using the same subscription name (my_subscription is this example) and messages will be delivered in a round robin fashion. Exclusive and more advanced subscriptions types are also available.

Whenever a questionnaire is answered an event is published on `krane/questionnaires/answers-in-{ORG_NAME}` which will look like this. The exact contents depend on the used questionnaire.

JSON
{
  "id": "5a0beb60-68a8-401a-b798-0868346b5882",
  "name": "answers",
  "operationType": "insert",
  "collection": "answers",
  "entity": {
    "_version": 0,
    "_id": "6529052bed80223630597ae3",
    "createdAt": "2023-10-13T08:51:55.313Z",
    "updatedAt": "2023-10-13T08:51:55.313Z",
    "type": "questionnaire",
    "studyId": "62a0639fe722db00135e9caa",
    "result": {
      "questionnaireId": "632327809e2988cbd6eebaf4",
      "answers": [
        {
          "questionId": "632327809e2988cbd6eebaf5",
          "timestamp": "2023-10-13T08:51:50.621Z",
          "value": 0,
          "questionName": "geteten",
          "index": 0
        },
        {
          "questionId": "632327809e2988cbd6eebaf8",
          "timestamp": "2023-10-13T08:51:51.833Z",
          "value": 0,
          "questionName": "gemoedstoestand",
          "index": 0
        },
        {
          "questionId": "632327809e2988cbd6eebaf7",
          "timestamp": "2023-10-13T08:51:52.997Z",
          "value": 0,
          "questionName": "pijn",
          "index": 0
        },
        {
          "questionId": "632327809e2988cbd6eebaf6",
          "timestamp": "2023-10-13T08:51:54.092Z",
          "value": 0,
          "questionName": "gelopen",
          "index": 0
        },
        {
          "questionId": "632327809e2988cbd6eebaf9",
          "timestamp": "2023-10-13T08:51:55.206Z",
          "value": 0,
          "questionName": "fit",
          "index": 0
        }
      ],
      "questionnaireName": { "en_US": "hackathon" }
    },
    "userId": "6527a81258139c1e1494c4bc",
    "status": "completed",
    "partialStatus": {
      "632327809e2988cbd6eebaf8": "completed",
      "632327809e2988cbd6eebaf9": "completed",
      "632327809e2988cbd6eebaf5": "completed",
      "632327809e2988cbd6eebaf7": "completed",
      "632327809e2988cbd6eebaf6": "completed"
    }
  },
  "reply": false,
  "timestamp": 1697187115366
}


Now that we have a consumer (questionnaire_consumer), we need to wait until we receive a message:

Python
while True:
    msg = questionnaire_consumer.receive()
    try:
        message = json.loads(msg.data().decode('utf-8'))
        results_id = message["entity"]["_id"]
        questionnaire_id = message["entity"]["result"]["questionnaireId"]
        
        print("Received message rid='{}' qid='{}'".format(results_id, questionnaire_id))
        # Acknowledge successful processing of the message
        questionnaire_consumer.acknowledge(msg)
 
    except Exception:
        # Message failed to be processed
        questionnaire_consumer.negative_acknowledge(msg)


Let’s go through it in detail:

questionnaire_consumer.receive() will block until a new message is available. After we received the message we can read the contents:

Python
message = json.loads(msg.data().decode('utf-8'))
results_id = message["entity"]["_id"]
questionnaire_answers = message["entity"]["result"]
questionnaire_id = questionnaire_answers["questionnaireId"]

Pulsar expects each message to be acknowledged:

Python
questionnaire_consumer.acknowledge(msg)

If no acknowledgement is sent Pulsar will try to redeliver the message. It’s also possible to explicitly send a negative acknowledgement:

Python
questionnaire_consumer.negative_acknowledge(msg)

Processing

Once we have the questionnaire answers we can use them to generate some result. For the purposes of this guide we will just count the number of answers (which usually is the same as the number of questions expect if routing is used in the questionnaire).

In practice you would want to make sure that you are processing answers from the correct questionnaire. Make sure to check the questionnaireIdand/or questionnareName.

To count the number of answers we simply get the length of the answersarray:

Python
answer_count = len(questionnaire_answers["answers"])

Store the results

Questionnaire answers can be enriched with a score and additional metadata. While there is no public API yet to post these scores, it can be done today by publishing a QuestionnaireScoreGenerated message with the following structure:

JSON
{
    "id": "5b575440-a025-4ff2-9fcb-a8a825e28d8c",
    'name': "QuestionnaireScoreGenerated",
    'version': "0.0.1",
    'tenant': "orikami",
    'data': {
        "error_message": None, 
        "warning_message": None, 
        "experimentResultId": 6529052bed80223630597ae3, 
        "questionnaireId": 632327809e2988cbd6eebaf4, 
        "score": 5, 
        "interpretation": "Count",
        "metadata": {
            "title": "Complex metadata",
            "description": "This is a complex metadata object",
            "data": [1, 2, 3, 4],
            "bmi": 21
        }
    }
}

id should be a unique UUID.

Make sure to set the correct questionnaireResultId ( entity.result.questionnaireId from the answers message ) and experimentResultId ( entity._id from the answers )

scoreand interpretation will be visible in the questionnaire results in the Orikami App. For additional results the metadata field can be used. It can contain any valid JSON type but will not be displayed in the app (it will be visible through the API).

First let’s create a producer for the KRANE/experiments/{ORG_NAME}-eventstopic:

Python
questionnaire_score_producer = pulsar_client.create_producer(f"krane/experiments/{ORG_NAME}-events")

Construct and send the message as bytes:

Python
const score_message_bytes = json.dumps({
      "id": uuid.uuid4().hex,
      'name': "QuestionnaireScoreGenerated",
      'version': "0.0.1",
      'tenant': "orikami",
      'data': {
          "error_message": None, 
          "warning_message": None, 
          "experimentResultId": results_id, 
          "questionnaireId": questionnaire_id, 
          "score": answer_count, 
          "interpretation": "Count",
          "metadata": {
              "title": "Complex metadata",
              "description": "This is a complex metadata object",
              "data": [1, 2, 3, 4],
              "bmi": 21
          }
      }
  }).encode('utf-8')

questionnaire_score_producer.send(score_message_bytes)

The score and metadata will now be saved as part of the questionnaire answers and can be accessed through the API as described in MP-04 Download data through API.

Full script


Python
import pulsa
import json
import uuid

TOKEN = ""
ORG_NAME = ""

pulsar_client = pulsar.Client("pulsar+ssl://pulsar.krane.one", authentication=pulsar.AuthenticationToken(TOKEN))

questionnaire_consumer = pulsar_client.subscribe(f"krane/questionnaires/answers-in-{ORG_NAME}", "my_subscription")
questionnaire_score_producer = pulsar_client.create_producer(f"krane/experiments/{ORG_NAME}-events")

while True:
    msg = questionnaire_consumer.receive()
    try:
        message = json.loads(msg.data().decode('utf-8'))
        results_id = message["entity"]["_id"]
        questionnaire_answers = message["entity"]["result"]
        questionnaire_id = questionnaire_answers["questionnaireId"]
        
        answer_count = len(questionnaire_answers["answers"])
        
        print("Received message rid='{}' qid='{}'".format(results_id, questionnaire_id))

        questionnaire_score_producer.send(json.dumps({
            "id": uuid.uuid4().hex,
            'name': "QuestionnaireScoreGenerated",
            'version': "0.0.1",
            'tenant': "orikami",
            'data': {
              "error_message": None, 
              "warning_message": None, 
              "experimentResultId": results_id, 
              "questionnaireId": questionnaire_id, 
              "score": answer_count, 
              "interpretation": "Count",
              "metadata": {
                  "title": "Complex metadata",
                  "description": "This is a complex metadata object",
                  "data": [1, 2, 3, 4],
                  "bmi": 21
              }
          }
        }).encode('utf-8'))

        # Acknowledge successful processing of the message
        questionnaire_consumer.acknowledge(msg)

    
    except Exception as e:

        print(e)
        # Message failed to be processed
        questionnaire_consumer.negative_acknowledge(msg)