A method and system for state-gated recording and file protection of multi-source neural signals
By verifying the identity of the data stream and the status of the recorder before the experiment starts, and combining this with a recording redundancy protection mechanism, the problems of missed recordings and file corruption in multi-source neural signal recording are solved, ensuring data integrity and reliability.
Patent Information
- Application Number
- CN202611257354.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-19
- Publication Date
- 2026-11-20
AI Technical Summary
Existing methods for recording multi-source neural signal data streams lack state gating and fault tolerance mechanisms during the start and end phases of experiments, leading to problems such as missed recordings at the beginning, data truncation at the end, and data file corruption.
By forcibly verifying the identity of the data stream before the experiment starts, comprehensively checking the recorder process status and file status, ensuring that recording is ready, and maintaining the data stream operation and recording redundancy protection after the experiment ends until the file integrity is confirmed, a multi-dimensional inspection mechanism is adopted to prevent data loss and file corruption.
It achieves alignment of the first and last stages of multi-source neural signal recording and anomaly handling, solving the problems of missed recordings, truncation, and file corruption, and ensuring data integrity and reliability.
Smart Images

Figure CN123138071A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of neural engineering and physiological signal acquisition technology, specifically to a method and system for state-gated recording and file protection of multi-source neural signals. Background Technology
[0002] In brain-computer interface and cognitive neuroscience experiments, researchers need to simultaneously collect multi-source neurophysiological signals from subjects, such as electroencephalograms (EEG), eye movements, and electromyograms (EMG). To accurately correlate the subjects' physiological responses with external stimuli, the data acquisition system needs to combine event markers generated by the experimental stimulus paradigm and save various data streams to local computer storage devices in real time and synchronously for subsequent data reconstruction and feature analysis.
[0003] Currently, conventional data recording methods mainly rely on the operating system's underlying network interface and file stream writing mechanism. In a typical operating procedure, after receiving the experiment start command, the system will directly issue a command to start the recording process and receive the data stream; when it receives the experiment end signal, the system will usually immediately send a process termination command, close the data stream connection, and complete the file saving action.
[0004] In such hardware and software collaboration processes based on the underlying operating system, existing recording mechanisms lack mandatory alignment and anomaly protection for data stream states. During the experiment's initiation phase, if the underlying network stream is not fully stable or the recording pipeline is not yet ready, forcibly writing data can cause timestamp misalignment or omissions in the initial signal recording. At the experiment's end, directly blocking the communication connection can easily lead to data truncation at the end due to the operating system's caching mechanism or transmission delays. Furthermore, if the recording process experiences timeouts or freezes during operation, existing systems typically lack process-level takeover and maintenance mechanisms, which can easily cause system crashes, resulting in the destruction of all data from a single experiment. Simultaneously, due to the operating system's asynchronous disk writing mechanism, conventional methods struggle to confirm whether the file has truly been physically written to disk, and the lack of an objective verification process for the internal logical structure of the generated file often leads researchers to discover structural corruption only in later analysis stages. Summary of the Invention
[0005] To address the shortcomings of existing technologies, this invention provides a state-gated recording and file protection method and system for multi-source neural signals. This solves the problem that existing systems lack state gating and fault-tolerant takeover mechanisms at the beginning and end stages of multi-source neural signal data stream recording and when processes are abnormal, which easily leads to problems such as missed recordings at the beginning, truncation of data at the end, and data file corruption caused by asynchronous disk writing and process freezing.
[0006] To achieve the above objectives, the present invention provides the following technical solution: The first aspect of this invention provides a method for state-gated recording and file protection of multi-source neural signals, comprising the following steps: Obtain the experiment configuration, generate the experiment identifier, establish the experiment context, and divide the data stream set, which includes required streams and optional streams; Perform a data stream discovery operation, compare the measured identity description vector with the target identity description vector, and determine whether the required stream meets the continuous stability condition. This step ensures that the physical and logical connection of the data source is in a stable state by forcibly verifying the identity of the data stream before the underlying communication is established. Based on the results of the real-time processing enable flag and continuous stability conditions in the experimental configuration, a real-time processing process is created and started, and a processing readiness determination is performed. The unified recorder process is started, and the running status of the unified recorder process, the status of the standard input control channel, and the status of the target recording file are checked to comprehensively determine whether recording is ready. This step establishes a recording ready gate to eliminate potential risks such as pipe breakage or lack of file system permissions. The experiment configuration is sent to the experimental paradigm process, and the experiment start control signal is sent. The first planned experiment event flag is written. A unified recorder is used to synchronously write the continuous neural signal stream and experimental event marker stream into the target recording file until the end-of-experiment marker is written. Keep the data stream generating end running, and the unified recorder continuously records for the preset time redundancy protection duration; use the time redundancy mechanism to completely capture the tail signal at the moment the experiment ends; Send a unified recorder stop control command, and if the system fails to exit within the timeout period, send a forced termination command or control system enters an abnormal hold state. After confirming the exit of the unified recorder process, read and confirm the size of the target recording file, parse the target recording file and calculate the recording file acceptance flag; through physical layer size verification and logical layer structure parsing, investigate file truncation and corruption caused by system asynchronous write delay; Clean up the experiment-level resources used by a single experiment, and retain the session-level resources.
[0007] Furthermore, determining whether the necessary flows meet the continuous stability condition specifically includes: cyclically executing data flow discovery detection within a preset single discovery waiting time and a preset adjacent discovery period; extracting the measured identity description vectors corresponding to the current network nodes and process ports, and performing a one-by-one comparison and matching with each component of the target identity description vector; when the values of the five components—flow name, flow type, source identifier, number of channels, and nominal sampling rate—are all the same, a single match is considered successful; subsequently, within a previously set continuous period, performing a logical AND operation on the matching status of all necessary flows in both time and space dimensions. If all necessary flows are accurately ready at the current moment and have maintained a single match success within the previously set number of consecutive periods, then the continuous stability condition is calculated to be met. This design filters out transient flows caused by network fluctuations.
[0008] Furthermore, the creation and initiation of the real-time processing process and the determination of processing readiness specifically include: When the real-time processing enable flag is read and the required preceding streams meet the continuous stability condition, a child process for performing real-time processing is created and the real-time processing loop is started. Within the preset processing readiness time limit, listen for the readiness events output by the real-time processing process; The experiment identifier and real-time processing process identifier within the ready event are parsed. When the parsing result matches the current experiment context, the ready-to-process determination result is calculated.
[0009] Furthermore, checking the running status of the unified recorder process, the status of the standard input control channel, and the status of the target recording file, and comprehensively determining whether recording is ready, specifically includes: Check the status of the unified recorder process handle to confirm that the unified recorder process has not exited. Perform a zero-byte write test operation to the standard input handle of the unified recorder process to verify that the underlying pipe buffer is not broken and that the standard input control channel is writable. In the file system, confirm that the target recording file has been created and can be opened in write mode; when the three conditions of the unified recorder process not exiting, the standard input control channel being writable, and the target recording file being open are met simultaneously, calculate the result of recording ready.
[0010] This multi-dimensional inspection mechanism prevents data from being blindly sent to stagnant processes or broken pipelines.
[0011] Furthermore, the process of issuing experimental configurations and sending experimental start control signals to the experimental paradigm process, and writing the first planned experimental event marker specifically includes: After determining that recording is ready, the serialized experimental configuration is sent to the standard input of the experimental paradigm process; After maintaining the preset control interval and confirming that the experimental paradigm process is alive, send an experiment start control signal to the experimental paradigm process; The time span from the recording ready moment to the moment the first planned experimental event marker is written is called the recording preparation interval. This recording preparation interval covers the process of the unified recorder performing discovery and subscription feedback processing for all necessary streams, and its duration is not less than the sum of the preset control interval, the duration of the prompt tone, the no-event interval, and the time occupied by the warm-up screen.
[0012] This mechanism reserves ample timing space for the subscription of the underlying data stream.
[0013] Furthermore, using a unified recorder to synchronously write the continuously existing neural signal stream and experimental event marker stream into the target recording file specifically includes: Based on the experimental phase sequence parameters and corresponding durations, a planned experimental event marker sequence is generated and combined with an independently preset set of running marker codes; Relying on the unified time base of the system's underlying layer, the continuously connected neural signal stream and experimental event tagging stream are timestamped; Multi-source data, after being calibrated with a unified timestamp, are synchronously written to the same target recording file in real time until the experimental paradigm process completes all stages of execution and writes a unique experiment end marker.
[0014] Furthermore, sending a unified recorder stop control command and, if the system fails to exit within a timeout period, sending a forced termination command or controlling the system to enter an abnormal hold state specifically includes: After the preset time redundancy protection period expires, if it is determined that the standard input of the unified recorder process is writable, a unified recorder stop control command is sent to the unified recorder process. If no unified recorder process exit event is received after the preset unified recorder process exit waiting time limit expires, a forced termination command is sent to the unified recorder process and the preset forced termination exit waiting time limit is re-entered. If the process exit is not confirmed by the expiration of the preset forced termination exit waiting time limit, the control system enters an abnormal hold state, skips the recorded file acceptance process and the experimental resource cleanup process, and retains the current unified recorder process handle and the underlying current data stream connection.
[0015] This mechanism provides the ability to preserve the state in the event of a process deadlock, preventing data from being incorrectly overwritten or destroyed.
[0016] Furthermore, confirming the target recording file size after the unified recorder process exits includes: Upon receiving the unified recorder process exit event, the size of the disk space currently occupied by the target recording file in bytes is read multiple times at preset sampling time intervals; When the file size is obtained continuously for the same number of preset consecutive samplings, it is determined that the disk write operation of the target recording file has been completed and the file size is confirmed to no longer change. If the cumulative number of reads reaches the preset maximum number of reads and still no consecutive files of the same size are obtained, the file system is determined to be abnormal, the subsequent parsing process is skipped and the result of failing the acceptance test is recorded.
[0017] This step isolates the latency effect of the operating system cache being asynchronously flushed to disk.
[0018] Furthermore, parsing the target recording file and calculating the recording file acceptance criteria specifically includes: The parser is invoked to read the target recording file sequentially, and a recovery scan strategy is executed for corrupted data areas that cannot be parsed normally, and the recovery scan byte range is recorded; From six dimensions—existence of physical structure, completeness of full file reading, completeness of required stream, order of timestamp sequence, existence of experiment end marker, and consistency of experiment event markers—state flags are extracted and logically ANDed to calculate six pass flags. The recovery positioning time of each recovery scan byte interval is traced in reverse, and the recovery scan judgment quantity is calculated based on the timing relationship between the recovery positioning time and the time when the experiment end mark is written; By combining the above six checkpoints with the recovery scan criteria, a logical AND operation is performed to calculate the recorded file acceptance mark. This process achieves an objective evaluation of the file's logical structure.
[0019] A second aspect of the present invention provides a state-gated recording and file protection system for multi-source neural signals, comprising: A controller module used to control collaborative operations based on system state variables; The Experiment Context Establishment Module is used to obtain experiment configuration, generate experiment identifiers, establish experiment context, and divide the data stream set containing required and optional streams. This multi-source data stream discovery module is used to perform data stream discovery operations, compare the measured data with the target identity description vector, and determine whether the necessary stream meets the continuous and stable condition. A real-time processing startup module used to create and start a real-time processing process based on experimental configuration and judgment results, and to determine the processing readiness. The unified recorder startup module is used to start the unified recorder process, check the running and channel status, and comprehensively determine whether recording is ready. The experiment run triggering module is used to distribute experiment configurations, send experiment start control signals, and write the first planned experiment event marker. This is used to synchronously write neural signal streams and experimental event marker streams to the target recording file and to the signal and marker recording module that writes the experiment end marker; A time redundancy protection module used to keep the data stream generating end running and continuously record for a preset time redundancy protection duration; The unified recorder stop module is used to send a unified recorder stop control command and, if the system fails to exit within a timeout period, send a forced termination command or control the system to enter an abnormal hold state. The recording file acceptance module is used to parse the file and calculate the recording file acceptance pass flag after confirming process exit and file size. A resource cleanup module used to clean up experiment-level resources used by a single experiment while retaining session-level resources.
[0020] This invention provides a method and system for state-gated recording and file protection of multi-source neural signals. It has the following beneficial effects: 1. This invention achieves the technical effect of forcibly aligning the hardware and software pre-states in the early stage of multi-source neural signal recording by comparing the identity description vector of the data stream before triggering the experimental paradigm to determine the necessary continuous and stable conditions of the stream, and by comprehensively checking the process state of the unified recorder, the state of the control channel, and the state of the file. This solves the problem of missed or incorrect recording of neural signals in the experimental opening stage caused by the data stream not being ready or the underlying recording pipeline being abnormal.
[0021] 2. This invention achieves complete data capture of the tail end of the experiment and fault-tolerant takeover of process-level anomalies by maintaining the data source running and continuously recording for a preset time redundancy protection duration after the experiment ends and by controlling the system to enter an abnormal hold state and retaining the underlying connection when the unified recorder stops without exiting after a timeout. This solves the problems of loss of tail signals caused by direct truncation at the end of the experiment in traditional recording methods, as well as system crashes caused by abnormal freezing of the recording process, which destroys the recorded data.
[0022] 3. This invention achieves objective verification of the physical layer writing and logical layer structure of the generated file by continuously reading the size of the target recording file in multiple rounds after confirming the exit of the unified recorder process to confirm the completion of the disk writing action, and parsing the file structure to extract multi-dimensional status flags and then calculating the acceptance flag of the recording file. This solves the problems of file truncation and damage caused by the asynchronous disk writing delay of the operating system, and the inability to systematically evaluate the data integrity and tag consistency after the file is generated. Attached Figure Description
[0023] Figure 1 This is a system architecture diagram of the present invention; Figure 2 This is a flowchart of the method steps of the present invention. Detailed Implementation
[0024] The technical solutions in the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0025] Please see the appendix Figure 1 This invention provides a state-gated recording and file protection system for multi-source neural signals, including a lifecycle state controller, and associated experimental context establishment module, multi-source data stream discovery module, real-time processing startup module, unified recorder startup module, experimental run triggering module, signal and tag recording module, time redundancy protection module, unified recorder stop module, recording file acceptance module, and resource cleanup module.
[0026] The lifecycle state controller controls the above ten modules to work collaboratively according to preset conditions and sequence, based on the experiment identifier, real-time processing enable flag, various gating variables, process status, and process exit events. When the real-time processing enable flag is 0, the lifecycle state controller does not call the real-time processing startup module.
[0027] Please see the appendix Figure 2 This invention provides a method for state-gated recording and file protection of multi-source neural signals, comprising the following steps: S1: Obtain the experiment configuration, generate the experiment identifier, establish the experiment directory and target recording file path, and define the required and optional streams.
[0028] S2, perform data flow discovery operation according to preset period, compare the measured identity description vector with the target identity description vector, and determine whether the necessary flow meets the continuous stability condition.
[0029] S3: When the real-time processing enable flag indicates that it is enabled, a real-time processing process is created and the real-time processing process is waited for the real-time processing process to output a ready event. After confirming that the conditions are met, the processing is determined to be ready.
[0030] S4 creates a unified recorder process based on the experiment identifier and data stream set, checks the running status of the unified recorder process, the status of the standard input control channel, and the status of the target recording file, and comprehensively determines that recording is ready.
[0031] S5 sends the experimental configuration to the experimental paradigm process, sends the experimental start control signal after maintaining the preset control interval, and allows the writing of the first planned experimental event flag.
[0032] S6 uses a unified recorder to synchronously write the continuous neural signal stream and experimental event marker stream into the target recording file until the experiment end marker is written.
[0033] S7, after the experiment ends and the marker is written, keep the data stream generating end running, and the unified recorder continues to record for the preset time redundancy protection duration.
[0034] S8, after the time redundancy protection is completed, sends a unified recorder stop control command through the standard input of the unified recorder process, and sends a forced termination command or controls the system to enter an abnormal hold state if it does not exit within the timeout period.
[0035] S9: After confirming that the unified recorder process has exited, read the file size. When the same file size is obtained a preset number of times, parse the target recording file and calculate the recording file acceptance flag.
[0036] S10 cleans up the processes and handles, experimental paradigm-related resources and entry buffers used by a single experiment, while retaining controller sessions, database connections and local data forwarding services.
[0037] The following section will provide a detailed explanation of the implementation details, gating mechanisms, and exception handling logic of each functional step of this invention, based on the aforementioned system architecture and macro-process.
[0038] The lifecycle state controller calls the experimental context establishment module to execute step S1 to establish the experimental context and divide the data stream set according to the current state transition rules. Then, it calls the multi-source data stream discovery module to execute step S2 to discover multi-source data streams and perform stream admission determination.
[0039] For the processing logic of establishing the experimental context and dividing the data stream set, step S1 specifically includes the following sub-steps: S11, Obtain the experiment configuration and establish the context environment. The lifecycle state controller obtains the configuration information for this experiment, such as generating a unique and non-repeating independent experiment identifier within the current controller session scope using a system timestamp or a universally unique identifier generation algorithm. The controller uses this experimental identifier. To provide a basis for retrieval and classification, a one-to-one correspondence is established in the file system for experimental directories, target recording file paths, and related experimental record entries. For the creation of experimental directory files and the concatenation of system paths, those skilled in the art can utilize standard operating system application programming interfaces (APIs) combined with a general file management tree structure. The specific implementation mechanism is well-known in the field and will not be elaborated upon here.
[0040] S12 defines the data flow identifier set and flow category. The controller categorizes data flows based on the attributes of physical devices and logical data flows. Let the data flow identifier set declared in the experimental configuration be expressed as follows: ; In the formula, A set of data stream identifiers; This is the first data stream; For the second data stream; For the first One data stream; The total number of data streams is a positive integer.
[0041] Define based on specific implementation scenarios For brainwave signal flow, For functional near-infrared spectral signal stream, The experimental events are labeled with streams. Based on the experimental task requirements, the controller divides the overall data flow into a required stream set and an optional stream set. Let the required stream set be... The set of optional streams is Two sets satisfy the relation condition. .
[0042] In a specific implementation scenario of a combined experiment using electroencephalogram (EEG) signals and functional near-infrared spectroscopy (FIR) signals, a necessary set of flows is defined. Optional stream set In a specific implementation scenario of a pure EEG signal experiment, a necessary set of flows is defined. Optional stream set .
[0043] S13, construct the target identity description vector and the measured identity description vector. The principle behind setting the above identity description vector is to uniquely anchor various data streams broadcast in the network through multi-dimensional feature information, so as to ensure that the data source of subsequent recording is accurate and avoid introducing irrelevant or misconfigured signals.
[0044] Set time The lifecycle state controller obtains the data stream set through the data stream discovery operation as follows: For the set of identifiers Any data stream in ,index The value ranges from 1 to The experiment was configured for each A single target identity description vector is uniquely specified. This target identity description vector consists of five key configuration parameters, expressed in the following formula: ; In the formula, For the first The target identity description vector of each data stream; Name of the stream; It is a stream type; For source identifier; Number of channels; This is the nominal sampling rate.
[0045] In actual monitoring operations, at all times The formula for the measured identity description vector obtained by the data flow discovery operation for the current network endpoint and process port is expressed as follows: ; In the formula, For a moment Actual identity description vector; For a moment Measured Flow Name; For a moment Measured flow type; For a moment Measured source identifier; For a moment Actual number of channels; For a moment Actual nominal sampling rate.
[0046] Taking the parameters of a specific embodiment of the joint experiment as an example, the experimental context establishment module specifies that the components of the target identity description vector of the EEG signal stream are EEGStream, EEG, EEGLite, 2, and 250, respectively; the components of the target identity description vector of the functional near-infrared spectral signal stream are FNIRSStream, FNIRS, FNIRSLite, 16, and 100, respectively; and the components of the target identity description vector of the experimental event marker stream are MarkersStream, Markers, adhd_vis_script, 1, and 0, respectively. The nominal sampling rate is measured in Hertz.
[0047] S14, Define the experimental configuration component rules. The overall experimental configuration is composed of variables from multiple dimensions, which together determine the operational paradigm. The formula for the composition structure of the experimental configuration is expressed as follows: ; In the formula, Configured for the experiment; Subject identifier; This is an experimental type; To display width; To display the height; For refresh rate; This is the experimental phase sequence; This represents the duration vector for each experimental phase. Enable flag for real-time processing; A set of data stream identifiers.
[0048] In the configuration parameters and Limited to positive integers, A real value greater than zero. Real-time processing enabled flag. The range of values is limited to 0 or 1. When When, it indicates that the pre-processing mechanism should be activated for this experiment; when At this time, it indicates that real-time processing will not be enabled in this experiment. The experimental phase sequence and its duration vector expansion association representation is as follows: ; ; In the formula, This is the experimental phase sequence; This is the first experimental phase; This is the second experimental phase; For the first One experimental phase; This represents the total number of experimental phases and is a positive integer. This represents the duration vector for each experimental phase. The duration of the first experimental phase; The duration of the second experimental phase; For the first The duration of each experimental phase.
[0049] Experimental Phase Index The continuous values of are 1 to 1. . No. Experimental phase The actual running duration is limited to a positive number. Any stage The functional attribute values are limited to five defined types: open-eye stage, closed-eye stage, task stage, buffer stage, or rest stage. The specific values of each parameter can be preset by the operator through the configuration interface, based on the paradigm design requirements of the specific experiment.
[0050] Based on the specific configuration and implementation of the joint experiment, subject identifiers Generated by input from an external interactive interface; Experiment type The experiment was set up as a combined experiment of electroencephalogram (EEG) signals and functional near-infrared spectroscopy signals, displaying the width. Set to 1920 pixels, display height Set to 1080 pixels, refresh rate Configured to 60 frames per second. Real-time processing enabled flag. The value is 1. Total number of experimental phases. The configuration is set to 20.
[0051] In the experimental phase sequence middle, Refers to the stage of opening eyes. Refers to the closed-eye phase. Set the cycle block number to... And take integers from 1 to 6 in sequence, stage , and They respectively refer to the first The first task phase, the first The first buffer phase and the first There are rest phases. Regarding the assignment of the duration vector parameters... and All are set to 60 seconds. Set to 20 seconds. and Both are set to 10 seconds. In addition, the recovery phases of opening and closing the eyes are not included in the planned experimental event marker sequence of the main timeline. The corresponding data markers are classified into the category of the running marker code set, and each of the two recovery phases lasts for 15 seconds.
[0052] After establishing the experimental context and configuring the parameters, the controller calls the multi-source data stream discovery module to execute step S2, which detects network streams and performs availability gating. Step S2 specifically includes the following sub-steps: S21, polling to discover data streams and comparing them with identity description vectors. The multi-source data stream discovery module can listen to or subscribe to the data stream transmission protocol interface of networked physiological devices via LAN broadcast to detect live data streams in current network nodes and process ports. The multi-source data stream discovery module relies on a preset single discovery waiting time. Preset adjacent detection cycle and preset maximum number of polling times Three timing control parameters are used to perform cyclical data flow discovery and probing within the local area network. In each polling of the probe node, for each required flow defined in the required flow set RR... The module describes the actual identity description vector. With the given target identity description vector Each component within the system is compared and matched one by one. When the values of the five components—stream name, stream type, source identifier, number of channels, and nominal sampling rate—are all the same, the identity matching status value at that moment is set. If any one or more components are offset or missing, the match is considered to have failed, and the identity matching status value is reset. The underlying data detection and monitoring, as well as the multi-dimensional feature vector extraction and comparison logic, can be implemented by those skilled in the art based on the underlying network communication polling protocol and conventional structure data verification algorithm. The specific implementation mechanism is a well-known technology in this field and will not be elaborated here.
[0053] S22, calculates the continuous stability of the input flow control. To isolate unstable signal flows caused by network jitter and device startup transients, the control logic has a built-in parameter for the number of continuous stability checks, which is fixed as a preset positive integer. In practical applications, a preset adjacent detection period is used. The configuration is typically set to be greater than or equal to the single discovery wait time, and the maximum number of polls (NANA) can be determined based on the user's acceptable maximum system startup time. The multi-source data stream discovery module aggregates all component matching results within a previously set continuous period, calculates and outputs the stream admission feature. The stream admission calculation formula is expressed as follows: ; In the formula, For beginners; For the required flow set; For the first A necessary flow; The number of consecutive and stable determinations; This is the periodic offset index, with values ranging from 0 to... ; For the first The necessary flow is in the backward deduction time. The corresponding identity matching status value; The preset adjacent detection cycle is used.
[0054] The above formula is, in principle, equivalent to performing a logical AND operation on the matching status of all necessary streams in both time and space dimensions. This means that the data streams of all necessary devices must not only be accurately ready at the current moment, but also continuously ready in the past. It maintains a stable online connection throughout the cycle, thereby effectively filtering out brief false connections caused by network jitter or devices not being fully powered on.
[0055] In a specific polling implementation of the system, a preset single discovery waiting time is configured. The preset adjacent detection period is 1 second. The polling interval is 1.5 seconds, with a preset maximum number of polls. The maximum number of times is 8, and the number of consecutive stable judgments is determined. The threshold is 2. The mathematical product is non-zero only when the three necessary flows—EEG signal flow, functional near-infrared spectral signal flow, and experimental event labeling flow—perfectly match their respective target identity description vectors at both the current and previous discovery cycle times, thus yielding the flow threshold. The value is 1.
[0056] S23, Admission State Flow Control. The lifecycle state controller calculates and returns the flow admission threshold based on the multi-source data stream discovery module. And the real-time processing enable flag in the experimental configuration. This determines the branch of flow for the currently idle node. When the conditions combine to form a flow threshold... And process the activation flag in real time. When the necessary channel is stable and the processing requirement is enabled, the lifecycle status controller enters the real-time processing startup phase corresponding to the subsequent step S3.
[0057] When the conditions are combined to form a flow standard entry And process the activation flag in real time. When the underlying flow conditions are ready and there are no pre-processing requirements, the lifecycle state controller controls the execution timing to skip step S3 and directly enter the unified recorder startup environment configuration corresponding to step S4.
[0058] S24, Admission Anomaly Interception and Blocking Handling. During the continuous network and in-process polling performed by the multi-source data stream discovery module, if a physical connection is lost causing any necessary stream to disappear, or if a configuration mutation causes a change in its measured identity description vector, the multi-source data stream discovery module will reset the accumulated historical consecutive match count for that specific necessary stream, making the continuous stability condition no longer valid. The lifecycle state controller synchronously calculates the detection cycle, and when the preset maximum polling count is exhausted... After the corresponding 8 iterations, if the extracted flow standard is... The value remains 0. The controller intercepts the data and outputs it to the upper-layer interface through logic, and persistently records the specific necessary flow blocking information that does not meet the continuous stability condition.
[0059] In this abnormal state, the lifecycle state controller stops generating and sending control signals to start subsequent experiments, forcing the entire system to stop the flow of operating states and remain in the flow admission phase, thus avoiding the risk of data aliasing and record omissions caused by unreliable local links.
[0060] After completing the preliminary flow admission determination phase, the lifecycle state controller, based on the current experimental operating conditions and gating parameters, calls the real-time processing process startup and readiness determination module and the unified recorder startup and readiness determination module, respectively. For specific operations, refer to S3 and S4 below: S3, Start the real-time processing process and determine processing readiness. This step is executed by the real-time processing process startup and readiness determination module, and its operation logic specifically includes the following sub-steps: S31, Condition determination and real-time processing process establishment. The module reads the real-time processing enable flag from the experimental configuration. And the flow standard introduction output from the previous stage Only when the conditions are combined as follows: and When this occurs, the processing logic for this step is triggered. The lifecycle state controller spawns child processes by calling the operating system's underlying process management application interface to execute the specified real-time processing executable file and assigns it an independent process identifier. For process spawning and resource allocation at the operating system level, those skilled in the art can call standard system functions to implement it; the specific mechanisms are well-known in the field and will not be elaborated upon here.
[0061] S32, Process internal environment initialization and task loop startup. After being loaded into memory, the created real-time processing process sequentially executes target neural signal stream parsing, data entry point establishment, target channel selection, and current entry point buffer clearing operations, finally starting the real-time processing loop. During this stage, the data entry point establishment process involves allocating data stream subscription object space in memory and binding the corresponding networked physiological device data transmission port. Regarding the target channel selection mechanism, the process performs feature matching on the input stream based on channel names, for example, prioritizing prefrontal cortex channels. and If the preset channel name mapping is not found in the currently detected EEG channel list, the process can trigger a fault-tolerant rollback mechanism to directly extract the underlying data columns of channel number zero and channel number one according to the index position, so as to ensure that the signal channel will not cause data sampling interruption due to name labeling differences.
[0062] S33, Ready Event Listening and Extraction. After the real-time processing loop starts, the real-time processing process outputs ready events to the outside. The lifecycle state controller continuously listens for and captures this event information through inter-process communication mechanisms or standard output redirection pipes. The message structure formula for a ready event is expressed as follows: ; In the formula, For ready events; For experimental identifiers; For real-time processing process identifier; This is a status message; To enable real-time processing of ready moments.
[0063] Regarding the status messages The actual character content is fixed by the system as "processing loop has started".
[0064] S34, Readiness Timeout Arbitration and State Transition. The controller maintains a preset processing readiness timeout, which is set based on the criterion of being greater than the maximum statistical time required for a process to load data from disk into memory, complete network port binding, and acquire the first data block. In a specific embodiment, this preset processing readiness timeout is configured to be 20 seconds.
[0065] The controller receives the ready event within this preset processing ready time limit. And verify the parsed experimental identifier I with the real-time processing process identifier. When all conditions are met and the context of this experiment is satisfied, the processing is ready gate is activated. In the formula, To process ready gates.
[0066] If the process state is abnormal, the control logic triggers the following dead-zone prevention control: when the real-time processing process exits prematurely before outputting a ready event that meets the conditions, the controller records the failure information, confirms that the process has exited, and then the control system jumps to step S10 to perform experimental resource cleanup.
[0067] If no matching ready event is received by the time the preset processing ready time limit expires, the controller also records the failure information and sends a process termination command to the real-time processing process. The system then simultaneously switches to the real-time processing process exit waiting state.
[0068] In the exit waiting state, the system starts a preset exit waiting time countdown, which is configured to be 5 seconds in a specific embodiment. If the controller confirms that the real-time processing process has exited within the preset exit waiting time, it proceeds to step S10 to perform experimental resource cleanup.
[0069] If the process exit is not confirmed by the expiration of the preset exit waiting time limit, the system will continue to remain in the current real-time processing process exit waiting state, without cleaning up other experimental resources or returning to the standby stage, in order to prevent blind reset under unknown underlying memory or port usage conditions from causing more serious cascading failures.
[0070] During this abnormal period, if the controller subsequently receives a delayed real-time processing process exit event, the system proceeds to step S10 to clean up experimental resources; if the controller is restarted, the system follows the initialization process after the restart.
[0071] Then, step S4 begins, launching the unified recorder and determining recording readiness. This step is executed by the unified recorder's startup and readiness determination module, and specifically includes the following sub-steps: S41, Unified recorder start threshold determination and process derivation. The controller evaluates the logical relationship of optional conditions for real-time processing, and the determination formula is expressed as follows: ; In the formula, Enable flag for real-time processing; To process ready gates.
[0072] The above judgment formula achieves logical decoupling between the experimental configuration branch and the processing stage state: when real-time processing is not enabled, i.e. The result of the calculation on the left side of the formula is always 1, indicating that the system crosses pairs. Parameter validation constraints; when real-time processing is enabled. The formula degenerates into a requirement This formula mechanism ensures that persistent recording of the underlying code is only allowed to begin when the required logical branch is fully ready.
[0073] When the flow is introduced Furthermore, when the aforementioned real-time processing options are met, the controller determines the processing based on the experiment identifier I, the target recording file path, and the required stream set. and optional stream set Execute the creation command for the unified recorder process. In the formula, This is an introduction to flow; I is the experiment identifier; For the required flow set; This is an optional set of streams. After the unified recorder process starts, it subscribes to the set. The current data stream in the process. Simultaneously, the controller provides targeted security isolation for the input and output streams of the unified recorder process: it configures its standard input as a writable control channel, ignores and discards its standard output, and continuously listens for and reads its standard error output.
[0074] S42, Unified Recorder State Vector Scan Probe. The controller extracts three dimensions reflecting the health and connectivity of the recording components, assembling them to form a unified recorder state vector, expressed by the following formula: ; In the formula, To unify the recorder state vector; To unify the running status of the recorder process; The standard input controls the channel status; Record the file status for the target.
[0075] The rules for determining the values of each state component are as follows: When the unified recorder process handle is not closed, the controller successfully queries the process status through this handle, and the system returns a result indicating that the unified recorder process has not exited, the controller instructs... ; Orders in other situations For components The controller performs a zero-byte write test operation to the standard input handle, and restricts the writing of newline characters, thereby non-destructively probing whether the underlying pipeline buffer is broken. When the standard input handle is not closed and the write test does not return an error, let In other cases, an order is issued. .
[0076] For components When the target recording file has been created in the file system and the controller can successfully open the file in write mode, then... In other cases, an order is issued. In addition, the controller sets a unified recorder process exit confirmation threshold. When the controller receives a unified recorder process exit event or the underlying query result clearly indicates that the process has exited, it will... If the exit is not confirmed, then... In the formula, To standardize the number of confirmations required for the recorder process to exit.
[0077] S43, Recording Readiness Aggregation Determination. Based on the extracted 3D state components, the module calculates the recording readiness gate for global state transition, expressed by the following formula: ; In the formula, For recording ready gate; To unify the running status of the recorder process; The standard input controls the channel status; Record the file status for the target.
[0078] Only when That is, when all three conditions are met simultaneously—the underlying process is alive, the communication channel is open, and the media file is writable—the controller determines that the recording end is in place and proceeds to step S5. For possible abnormal branches: when... At this point, the indicator process has prematurely failed, the controller records the unified recorder startup failure information, and returns to step S10 to perform experimental resource cleanup. and But at the same time, there exists or In this situation, the indicator process is idling but the input / output environment is blocked. The controller records the failure information that the unified recorder has not reached the recording ready state, sends a process termination command to the process, and enters the unified recorder process exit waiting state. When and When the system fails to establish a monitoring connection with the process table entry, the controller records a failure message indicating that the unified recorder process status cannot be determined, and also enters a unified recorder process exit waiting state.
[0079] S44, Unified Recorder Exit Waiting Period Control. After the system enters the unified recorder process exit waiting state, the controller loads a preset exit waiting time countdown according to the configuration, which can be set to 5 seconds. If the controller confirms that the unified recorder process has exited within the preset waiting period, it proceeds to step S10 to perform experimental resource cleanup.
[0080] If the preset waiting time limit expires without confirmation of process exit, the system blocks the state transition and remains in the unified recorder process exit waiting state. During this period, it does not perform recording file acceptance, clean up experimental resources, or return to the standby stage. If a belated unified recorder process exit event is received while in the waiting state, it will then proceed to step S10 to clean up resources. If the controller restarts, it will take over again according to the initialization process. Furthermore, the unified recorder's discovery and handshake subscription behavior for necessary streams is covered by the recording preparation interval time margin corresponding to subsequent steps; therefore, its actual subscription feedback is not included in the calculation of the aforementioned recording ready gate parameter.
[0081] Based on the collaborative management of the lifecycle state controller, the process of experimental configuration distribution, operation triggering, and recording of multi-source neural signals and experimental event tags is implemented according to the following steps.
[0082] S5. Call the experiment configuration distribution and execution trigger module to execute the experiment configuration distribution operation and control the execution trigger of the multi-source neural signal experiment program.
[0083] S51. When the controller determines that the recording ready gate is set to 1, it serializes the system-generated experiment identifier and experiment configuration into a configuration message according to the preset message format. The serialization format is specifically set to a field concatenation mechanism.
[0084] The fields in the configuration message are arranged in the following order: experiment identifier, subject identifier, experiment type, display width, display height, refresh rate, experiment phase sequence, duration of each experiment phase, real-time processing enable flag, and data stream identifier set.
[0085] Adjacent fields are separated by semicolons, and field names and corresponding field values are connected by equal signs. The entire serialized string is encoded in UTF-8. The controller then writes the serialized configuration message to the standard input of the experimental paradigm process, thereby distributing the configuration to the experimental generator.
[0086] In the specific implementation process, regarding the data interaction between the controller and the experimental paradigm process based on standard input, those skilled in the art can use the operating system's native pipe communication technology. The aforementioned cross-process communication method is a conventional approach in this field.
[0087] S52. After the configuration message is successfully written, the controller maintains a preset control interval. In this embodiment, the preset control interval is 0.5 seconds. When the preset control interval has elapsed and the experimental paradigm process remains alive, the controller sends an experiment start control signal to the experimental paradigm process.
[0088] After receiving the experiment start control signal, the experimental paradigm process is usually configured to perform a series of preparatory operations, which include creating a display window for visual stimulus display, measuring the current hardware refresh rate, presenting a warm-up screen with a preset number of frames, such as 20 frames, and playing a prompt tone with a preset duration, such as 4.25 seconds.
[0089] After the above preparatory operations are completed, the system maintains a no-event interval, preset to 0.5 seconds. After this no-event interval, the experimental paradigm process writes the first planned experimental event marker into the experimental event marker stream. The creation of the display window and the measurement of the hardware layer refresh rate can usually be accomplished by directly calling the system's underlying graphics application programming interface; the implementation details of this part are conventional techniques in this field.
[0090] S53. For a normal startup path where the system does not experience interruptions or errors, in order to ensure that the data stream has been stably admitted and the processing process and unified recorder are fully ready before the first experimental event marker is generated, and to avoid the omission of initial data, the occurrence of each stage of the experimental process is controlled by the state of the real-time processing enable flag and meets specific relational conditions.
[0091] When the real-time processing enable flag is set to 1, the time corresponding to each operation node in the system satisfies: ; In the formula, For the time of flow access; To enable real-time processing of ready moments; This is the moment when recording is ready; Configure the confirmation completion time; This refers to the moment when the experiment start control signal is issued; Mark the writing time for the first planned experimental event.
[0092] When the real-time processing enable flag is set to 0, the time corresponding to each operation node in the system satisfies: ; In the formula, For the time of flow access; This is the moment when recording is ready; Configure the confirmation completion time; This refers to the moment when the experiment start control signal is issued; Mark the writing time for the first planned experimental event.
[0093] Based on the above normal startup process, the controller defines the time span from recording readiness to the marking of the first experimental event as the recording preparation interval. The recording preparation interval encompasses the process of the unified recorder performing discovery and subscription feedback processing for all necessary streams, and its duration is determined by the following formula: ; In the formula, The duration of the preparation period for recording; Mark the writing time for the first planned experimental event; This is the recording ready moment.
[0094] The duration of the recording preparation interval is limited by the configured interaction parameters. Specifically, its lower limit is formed by the sum of various delays in the control interaction. Based on the specific configuration of the disclosed embodiment, this lower limit is determined by the preset control interval of 0.5 seconds, the time occupied by 20 frames of warm-up footage, the duration of the 4.25-second prompt tone, and the 0.5-second no-event interval, thus deriving the following relationship: ; In the formula, The duration of the recording preparation interval, in seconds; This is a constant representing the sum of the preset control interval, the duration of the prompt tone, and the time between no events, expressed in seconds. The preset number of frames for the warm-up screen; The actual refresh rate measured by the system, in frames per second.
[0095] S54. Abnormal situations may occur during the distribution and triggering process. Abnormal situations include configuration message writing failure, premature exit of the experimental paradigm process before the first planned experimental event flag is written, or failure to respond to the experimental start control signal.
[0096] Normally, when any of the above anomalies is detected, the controller stops sending all subsequent control signals for the current experiment and records the failure information at the time of the corresponding anomaly. To ensure that system resources are not blocked, the controller sends a carriage return and line feed character to the standard input of the unified recorder process to issue a stop control command to the unified recorder, requiring it to terminate its operation and start an exit wait timer with a time limit of 15 seconds.
[0097] S55. During the 15-second exit wait timer, the controller monitors the exit feedback status of the unified recorder process. Upon confirming a normal exit of the unified recorder process, the controller writes a status judgment indicating that the recorded file acceptance was not performed to the experimental log and transfers the process to the experimental resource cleanup module. If the unified recorder process exit event is not received within the 15-second exit wait timer, the controller issues a forced termination command through the system management interface and starts an additional 5-second exit wait timer. If the unified recorder process exit is still not confirmed after these 5 seconds, the controller determines that the system has entered an abnormal hold state. The file size confirmation and recorded file acceptance processes are not executed, experimental resource cleanup is aborted, and the current unified recorder process handle and underlying data stream connection handle are retained.
[0098] S6. Call the multi-source neural signal and experimental event labeling recording module, and coordinate with the unified recorder to record the continuous data stream and discrete labeling stream to the recording file located in the target path.
[0099] S61. The experimental paradigm process generates a planned experimental event marker sequence based on the experimental stage sequence parameters and their corresponding durations. The specific marker types used are limited to a fixed planned experimental event marker code table. This code table consists of a combination of general control identifiers for each experimental stage and task loop identifiers within specific blocks, satisfying the following definition: ; In the formula, Label the experimental events with a code table; The code that marks the start of the eye-opening phase is defined as PHASE_EO_START; The code that marks the start of the closed-eye phase is defined as PHASE_EC_START; This is the code that marks the end of the experiment; its defined value is EXP_END. For the first The starting code for each block task phase is defined as PHASE_TASK_START_BLK_n; For the first The block buffer phase begins with a marker code, defined as PHASE_BUFFER_START_BLK_n; For the first The code that marks the start of the rest phase for each block is defined as PHASE_REST_START_BLK_n; This is the block number.
[0100] The experimental paradigm process is arranged chronologically to generate a complete sequence of planned experimental event markers, which can be formally expressed as follows: ; In the formula, Label the sequence of planned experimental events; Mark the code to begin the eye-opening stage; Mark the code for the closed-eye phase; to Mark the start code for the task phase of each corresponding block; to Mark the start of the buffer phase for each corresponding block with code; to Mark the start of the rest phase for each corresponding block with code; The code marks the end of the experiment.
[0101] S62. In addition to the planned experimental event markers, the system has pre-set fixed marker codes that are independent and do not change with experimental configuration messages. These fixed codes belong to the runtime marker code set. In one implementation, this runtime marker code set includes pre-set codes used to characterize the recovery period state and statistics of multiple EEG processing indicators, specifically covering a total of 18 fixed code characters, such as PHASE_RECOVERY_EO, PHASE_RECOVERY_EC, and STIM_STD. These runtime marker codes are distinct from each other and completely independent of the aforementioned planned experimental event marker code table, facilitating accurate modal filtering during subsequent parsing of recorded files. Any discrete data not covered in the aforementioned two sets is classified and identified by the system as unrecognized markers.
[0102] S63. During operation, the unified recorder relies on a unified time reference at the system's underlying level to timestamp the continuously incoming EEG signal stream, functional near-infrared spectral signal stream, and experimental event marker stream. This unified timestamp mechanism is the core physical foundation for ensuring accurate alignment and analysis of subsequent cross-modal neural data. The timestamped multi-source data is written to the same target recording file in real time. In specific engineering development, the synchronization mechanism for the time reference can typically be constructed using conventional low-level communication mapping methods such as network time protocols, which is a mature application in this field.
[0103] S64. After completing the execution of all stages in the experimental phase sequence, the experimental paradigm process writes a unique experiment end marker to the experimental event marker stream. This marker writing action defines the actual valid data range of this multimodal experiment, satisfying the following definition: ; In the formula, For planned experimental event intervals; Mark the writing time for the first planned experimental event; This is the time when the experiment end marker was written.
[0104] Writing the experiment end marker stops the experimental paradigm process from issuing new planned experimental events. The experiment end marker does not directly trigger the network disconnection action of the process at the data stream generation end. The remote EEG device, the functional near-infrared spectroscopy device, and the corresponding transmission process continue to maintain data output, and the unified recorder continues to perform the recording of end samples.
[0105] The logic behind this mechanism is to provide a prerequisite for data preservation before the system enters the time redundancy protection phase, allowing sufficient buffer time for the end samples and the experiment end marker itself to be absorbed and recorded to disk. Therefore, entering the experiment end marker does not mean that the memory buffer inside the unified recorder has been cleared or the end structure of the file has been closed; the final termination of the recording still depends on a series of subsequent state judgments and stop control logic of the system.
[0106] After completing the writing of the planned experimental event markers, the controller will transfer the control flow to the redundancy protection and timeout handling stage on the stop side, which will be implemented according to the following steps.
[0107] S7. Call the data stream generation end preservation and time redundancy protection module to keep the data stream generation end alive and perform time redundancy protection after the experiment end marker is written in the experiment paradigm process.
[0108] S71. After writing the experiment end marker, the experimental paradigm process stops generating new planned experimental events. In engineering practice, due to the time delays inherent in multi-source physiological signal acquisition devices (such as EEG devices and functional near-infrared spectroscopy devices), the transmission links of network communication nodes, and the internal memory queue of the unified recorder, the recording process could be easily terminated when writing the experiment end marker, potentially leading to the loss of the final sample or the experiment end marker itself because the disk write operation has not yet been completed. Therefore, the controller is configured to execute a time redundancy protection mechanism. The controller records the moment when the time redundancy protection ends and the unified recorder stops processing. .
[0109] S72, From the time the experiment ends after the end marker is written until the arrival time. During this period, the main body of the EEG device, the main body of the functional near-infrared spectroscopy device, and the portion continuously outputting data streams during the experimental paradigm process all remain operational. The unified recorder continuously writes the multi-source output data it receives into the target recording file. The corresponding time redundancy protection interval and its duration during this stage satisfy the following relationship: ; In the formula, The preset time redundancy protection duration is in seconds; This is the moment when time redundancy protection ends and unified recorder stop processing begins; This is the time when the experiment end marker was written.
[0110] In this embodiment, the preset time redundancy protection duration is 10 seconds. Before the preset time redundancy protection duration expires, the controller is prohibited from issuing any stop control commands to the unified recorder.
[0111] S73. The set of continuous neural signal data blocks recorded by the unified recorder during the time redundancy protection period is denoted as... For a data block within a set, its temporal characteristics satisfy the following condition: ; In the formula, This is the time when the experiment end marker was written. A collection of continuous neural signal data blocks any data block The timestamp of the last sample; This marks the moment when time redundancy protection ends and the unified recorder stops processing.
[0112] S8. Call the unified recorder stop and timeout handling module. After completing the time redundancy protection, execute the operation of sending the unified recorder stop control command to the unified recorder and perform corresponding exception handling for various response timeout situations.
[0113] S81. After the time redundancy protection is completed, the controller uses the current time as the aforementioned time. The controller then initiates a unified recorder to stop processing. It checks the standard input status of the unified recorder process to determine if it is in a writable state.
[0114] In specific software implementations, this verification action is typically confirmed by polling the status of the inter-process pipe communication handle. When it is determined that the standard input of the unified recorder process is writable, the controller sends a unified recorder stop control command in the form of a newline character to the unified recorder process through this standard input. The unified recorder stop control command is used to request the unified recorder to write the data in the system's internal buffer queue and the file end structure to the target recording file, and to perform a closing operation on the target recording file after the above writing action is completed. The file end structure is specifically a file end-related structure identifier that the unified recorder writes according to a preset target recording file format and solidifies at the stop recording stage.
[0115] For operations such as refreshing the file pointer, flushing data to disk, and closing the file handle, those skilled in the art can directly call the standard file operation interface of the operating system to implement them. The specific implementation mechanism is a well-known technology in this field and will not be described in detail here.
[0116] S82. After the unified recorder stop control command is successfully sent, the controller starts an internal timer and monitors the exit status of the unified recorder process within a preset unified recorder process exit waiting time limit. In this embodiment, the preset unified recorder process exit waiting time limit is set to 15 seconds. The moment when the controller first receives the unified recorder process exit event through the system layer, thus confirming that the process has exited, is recorded as follows: When the controller successfully receives the unified recorder process exit event within the preset unified recorder process exit waiting time limit, the controller ends the waiting state and the control flow proceeds to the subsequent steps of confirming the file size and accepting the recorded file.
[0117] S83. If the unified recorder fails to exit normally, the controller will classify it as an anomaly if any of the following occurs: the standard input state of the unified recorder process is not writable; the unified recorder stop control command fails to be sent; or the controller still has not received a unified recorder process exit event when the preset unified recorder process exit waiting timeout expires. In this case, the controller will take the current moment when the anomaly occurs as the failure moment and record the corresponding failure stage and reason. Subsequently, the controller will send a forced termination command to the target process through the operating system-level process management interface to forcibly close the abnormal process.
[0118] The moment when the controller sends the above-mentioned forced termination command is recorded as . The system then resets the start timer and enters a preset forced termination exit waiting period to continue waiting for the unified recorder process to exit. In this embodiment, the preset forced termination exit waiting period is set to 5 seconds. When the controller receives a unified recorder process exit event within this preset forced termination exit waiting period, the time of receiving the event is recorded as... The control process then proceeds to the next steps: confirming the file size and verifying the recorded file.
[0119] S84. When the preset forced termination and exit waiting time limit expires and the controller still has not received a unified recorder process exit event, the system is controlled to enter an abnormal hold state. In this abnormal hold state, the controller adopts a resource locking strategy, specifically including: The system prohibits the initiation of the start command for the next experiment; it skips and does not execute the file size confirmation process, the recording file acceptance process, and the regular experimental resource cleanup process; at the same time, it maintains the underlying data links from being destroyed, and retains the current unified recorder process handle, the current underlying data stream connection, and the corresponding communication handle, so as to preserve the system fault scene.
[0120] S85. After entering the abnormal hold state, the system continuously monitors the system status and external intervention signals. The system will exit the abnormal hold state under any of the following circumstances: Scenario 1: The controller subsequently receives a delayed unified recorder process exit event. In this case, the controller updates the time of receiving the delayed event to... Then proceed to the next steps of confirming the file size and accepting the recorded file.
[0121] Scenario 2: The controller receives a reset command and confirms that the unified recorder process has actually exited by retrieving the unified recorder process handle. In this case, the controller writes a result flag indicating that the recorded file acceptance was not performed to the experiment log, then directly jumps to execute the cleanup process for experimental resources, and drives the system back to the standby stage after resource cleanup is complete. If the controller does not confirm that the unified recorder process has exited when it receives the reset command, it rejects the reset operation, and the system continues to maintain the abnormal hold-in state.
[0122] Scenario 3: The controller restarts. In this case, subsequent system operations will follow the initialization process after the controller restarts.
[0123] S86. Based on the above-mentioned normal and abnormal processing paths, the temporal relationship of critical event moments must meet specific constraints.
[0124] For processing paths that successfully enter subsequent processes without sending a forced termination command, the following conditions must be met at each time point: ; In the formula, This is the time when the experiment end marker was written. This is the moment when time redundancy protection ends and unified recorder stop processing begins; This is the moment when the controller first confirms that the unified recorder process has exited; To confirm the point at which the size of the target recording file no longer changes; This marks the point at which the system enters the experimental resource cleanup phase.
[0125] For the processing path that receives the unified recorder process exit event and enters the subsequent process only after sending a forced termination command, the following conditions must be met at each time point: ; In the formula, This is the time when the experiment end marker was written. This is the moment when time redundancy protection ends and unified recorder stop processing begins; The time at which the forced termination command is sent; This is the moment when the controller first confirms that the unified recorder process has exited; To confirm the point at which the size of the target recording file no longer changes; This marks the point at which the system enters the experimental resource cleanup phase.
[0126] The controller calls the file size confirmation, file recording and acceptance result recording modules, as well as the experimental resource cleanup and session-level resource retention modules, and executes the subsequent steps in sequence.
[0127] S9. Only after the controller receives the unified recorder process exit event, perform file size verification on the target recording file; after confirming that the file size is stable, call the parser to read the target recording file sequentially for acceptance and record the corresponding acceptance results.
[0128] S91, the controller performs multiple rounds of polling to read the target recording file. Specifically, it reads the size of the disk space currently occupied by the target recording file in bytes at preset sampling time intervals, and records the result as the first... The size of the file obtained from the first read is .
[0129] It is understandable that those skilled in the art can directly obtain the file size by calling the operating system's file status query interface. Such metadata reading mechanisms are well-known technologies in this field and will not be elaborated upon here.
[0130] The preset sampling time interval and preset number of consecutive samples are typically set based on a comprehensive evaluation of the operating system's disk cache flush cycle and the response latency of the storage hardware under normal load conditions. In this embodiment, the preset sampling time interval is set to 1 second, the preset number of consecutive samples is 3, and the preset maximum number of reads is set to... Here we take 30 times.
[0131] When the controller obtains the same file size a preset number of times consecutively, it determines that the disk write operation of the target recording file has been completed, and the controller sets a file size confirmation flag. And record the moment when the file size no longer changes as .
[0132] S92. When the file size has not yet been confirmed and the number of reads is less than the preset maximum number of reads. During this period, the controller continues polling and reading the file size, but does not write the acceptance results to the recorded file. If the cumulative number of reads reaches the preset maximum number of reads... If the above-mentioned stable condition of continuous same size is still not met, the controller can determine that the file system has a persistent hanging anomaly.
[0133] At this point, the controller sets a file size confirmation flag. And the recorded file has passed acceptance. In this scenario, the controller summarizes and records the file size obtained from each read operation. The experiment record records the results of the recorded file failing acceptance and the reasons for failure due to the file size not meeting the stability condition. It then skips the subsequent calculation process of the acceptance vector and recovery scan judgment quantity and directly proceeds to the resource cleanup step.
[0134] S93, When the file size confirmation flag is met At this time, the controller invokes the file parser to open and sequentially read the target recording file in read-only mode. The parser identifies the file header, stream description block, and data blocks according to the predefined data organization format of the target recording file.
[0135] In one possible implementation, the target recording file adopts an encapsulation format of block header information plus data payload, and those skilled in the art can define the specific boundaries of each data block based on the identifier code and length field in the block header.
[0136] For data blocks that the parser can clearly identify the block type and block length, and can accurately define the start byte position and end byte position, they are uniformly marked as complete parsed data blocks; for complete parsed data blocks containing neural signal samples or labeled codes, the parser further extracts the last sample timestamp of the data block.
[0137] S94. During the sequential reading of the target recording file by the parser, corrupted data areas that cannot be parsed normally according to the target recording file format are skipped using a recovery scan strategy. The parser records the consecutive byte range that needs to be skipped by the recovery scan as the recovery scan byte range. This allows for the construction of a set of restored scanned byte ranges. .
[0138] In practice, if the parser offsets to the new position according to the length declared by the previous data block, and the read block identifier code fails to match any valid signature, the parser determines that a byte misalignment or data corruption has occurred. At this point, the parser starts a byte-by-byte sliding probe mode until a valid block identifier code is hit again, thereby restoring parsing synchronization.
[0139] For sets Each recovery scan byte range The parser records the starting byte position of the interval. And the starting byte position of the first complete parsed data block that is successfully identified and synchronized by the parser after this interval. When the end of a file is corrupted and no complete parsed data block is found after the recovery scan byte range, the system uses the total file length of the target recorded file as the starting byte position. The file length value corresponds to the physical offset position of the last byte after the end of the target recorded file.
[0140] S95. Based on the aforementioned analysis results, the controller performs multi-dimensional recording validity assessment and calculates the acceptance vector. The principle behind the aforementioned acceptance mechanism is to systematically screen for potential interruptions or truncation anomalies in the incremental writing process of recorded files through multi-dimensional verification of physical structure, data integrity, time benchmark, and event logic, thereby ensuring the reliability of data for subsequent neural activity analysis.
[0141] Acceptance Vector Each component is composed of a status flag with a value of 0 or 1. A component is set to 1 when the inspection conditions are met and to 0 when they are not met. Furthermore, this acceptance vector... Each component corresponds to one of the six dimensions examined in the recorded file, specifically including the existence of physical structure, completeness of full file reading, completeness of required stream inclusion, order of timestamp sequence, existence of experiment end marker, and consistency of experiment event markers. The judgment rules are as follows: Determine if the target recording file exists and the extracted file size is greater than 0; if so, set the component... ; Determine whether the parser has successfully completed the sequential reading of the entire file and has fully recorded the starting byte position of each recovered scan byte interval. and start byte position If satisfied, let the component ; Determine whether the parsed flow description block contains all the necessary flows required by the experimental configuration; if so, let the component... ; Iterate through the data blocks of each required stream, and determine whether the timestamp sequence corresponding to each required stream is non-empty and arranged in non-decreasing order. If it satisfies this condition, then let the component... ; Search all experimental event-marked data blocks and determine whether the target recording file actually records a specific marker indicating the end of the experiment. If so, let the component... ; Verify whether the continuous neural signal coverage area completely includes the planned experimental event interval from the time the first planned experimental event marker was written to the time the experimental end marker was written; simultaneously, filter out the preset set of running marker codes. After covering the run markers, determine whether the remaining experimental event markers all conform to the specific experimental event marker code table. Defined, and the planned experimental event label sequence is the same as the expected generated planned experimental event label sequence. If they are consistent, then let the components be consistent. .
[0142] The controller calculates and integrates six check flags based on each component. The following relation is satisfied: ; In the formula, This is the pass / fail indicator for the six checks, and its value can be 0 or 1. It is 1 when all six checks are passed, and 0 otherwise. Acceptance vector The first in One verification component; The value is a positive integer from 1 to 6. This calculation is equivalent to performing a logical AND operation on the six verification components.
[0143] S96. Further, the system performs a recovery positioning verification and calculates the recovery scan determination quantity. The principle behind this determination is to use the timestamps of undamaged data blocks to estimate the time period during which the data corruption occurred, thereby identifying whether an irreversible temporal break has occurred within the critical experimental interval.
[0144] For sets Each recovery scan byte range The controller logically traces backwards to find the position of the current starting byte. The nearest complete parsed data block containing the sample is the one that was previously found and is byte-distance from it. If a complete parsed data block that meets the criteria is found, the timestamp of the last sample in that block is extracted and determined as the recovery positioning time for that interval. If at this starting byte position If no complete parsed data block matching the criteria is found previously, the specific recovery scan byte range is directly marked as an unlocatable range.
[0145] The controller assigns values based on the inspection results and conditions: When the set of restored scanned byte ranges satisfies At that time, or when for all The corresponding recovery and positioning time All can be effectively determined and all satisfy If the subsequent impact is determined to be controllable, then the recovery scan determination amount is set. .
[0146] Conversely, when there exists at least one interval whose recovery positioning time satisfies If at least one recovery scan byte range is determined to be an unlocatable range, it indicates that irreversible data loss or timing breakage has occurred within the critical valid range of the experiment. In this case, let the recovery scan determination value... .
[0147] Among the above judgment conditions, The moment when the experiment end marker is written by the experimental paradigm process; This refers to the recovery positioning time for the corresponding recovery scan byte range; To restore the scanned byte range. Restore scan determination quantity. The value can be 0 or 1.
[0148] S97. When the file size confirmation flag is met. At that time, the controller passes all six comprehensive checks. With recovery scan judgment quantity Obtain the final recording file acceptance mark. The following relation is satisfied: ; In the formula, This is a flag indicating whether the recorded file has passed inspection; its value can be either 0 or 1. This indicates that all six checks have been passed. To restore the scan determination quantity.
[0149] Subsequently, the controller verifies the acceptance flag based on the recorded file. , Restore the set of scanned byte ranges Acceptance vector The state of each component and the extracted recovery positioning time Write the corresponding acceptance judgment conclusion and the corresponding reasons for failure in the experimental record.
[0150] Specifically, when and At that time, the record showed that all six checks passed, and no recovery scan byte range was reported; when and At that time, it was recorded that all six checks passed, and the time for all recovery and positioning was later than the time when the experiment end mark was written. when If the recording file fails acceptance, the specific reason for the failure is recorded, based on the failed acceptance vector component or the recovery positioning result. After recording any of the above acceptance results, the controller proceeds to step S10.
[0151] S10. After completing the aforementioned steps, the controller enters the experimental resource cleanup phase, which reclaims and releases process handles, network communication and cache resources involved in the system according to their categories, while retaining public resource facilities that can be reused across sessions according to the configuration.
[0152] The controller executes this step only if: the acceptance process for the target recording file has been completed; or if, according to the pre-set rules, it is confirmed that the acceptance process will not be performed in the event of a system malfunction or failure to start the unified recorder; or if a startup failure occurs during the data stream admission and real-time processing startup phase in the early stage of the experiment and it is confirmed that the relevant process has exited.
[0153] S101. The controller first performs associated cleanup on the unified recorder process. When a unified recorder process has been created in this experiment, and the system has received a legitimate exit event confirming its closure, the controller calls the system process management interface to release the corresponding unified recorder process handle. This handle release operation is achieved by reducing the reference count of the process kernel object, preventing system resource leaks caused by long-term operation.
[0154] If the system determines that the Unified Recorder process is in an unconfirmed exit state during cleanup, the controller must not perform subsequent experimental resource cleanup operations to avoid unknown memory access errors caused by forced reclamation. For experimental scenarios where the Unified Recorder process has not been created, the process handle release operation will not be performed.
[0155] S102. The controller then performs corresponding processing for the real-time processing process. Since real-time processing is enabled in this embodiment's experimental configuration, the real-time processing process has been started by the system. The controller determines the lifecycle state of the real-time processing process at this moment: When the controller detects that the real-time processing process has exited, it directly releases the real-time processing process handle.
[0156] When the real-time processing process has not yet exited, the controller sends a process termination command through the process management interface, causing the system to enter a real-time processing process exit waiting state. Within a preset exit waiting time limit, which is pre-set to 5 seconds, the controller continuously listens for exit events.
[0157] If the real-time processing process is confirmed to have exited within the time limit, the real-time processing process handle will be released and the remaining experimental resources will be cleaned up. If the system still has not confirmed the process's exit by the time limit, the system will remain in the real-time processing process exit waiting state, suspend the cleanup of other experimental resources, and will not return to the standby stage.
[0158] During this waiting period, if the controller subsequently captures a delayed real-time processing process exit event, the controller will restore the execution handle release and then continue to clean up the remaining experimental resources.
[0159] S103. After ensuring that the core processes requiring control have exited and their handles have been released, the controller begins to clean up the remaining experimental-level resources. Specifically, the following logic is executed: Clear all experimental configuration messages and experimental start control signals that have not yet been sent in the current control cycle; close the display windows related to the experimental paradigm; Disconnect the data stream connection opened to carry the current physiological data stream. This can be achieved by those skilled in the art using conventional socket disconnect commands or pipe release mechanisms, followed by releasing the corresponding handle. Further, clear the current experiment identifier and release the current entry buffer used for receiving data, completing the recycling operations for other components related to this single experiment.
[0160] S104. While performing the above cleanup actions, the controller adopts a categorized retention strategy for session-level resources. The controller itself continues to run and does not shut down the session-level local data forwarding service; it does not disconnect the database connection of the business system; and it does not clear the data directory configuration.
[0161] The aforementioned public resources can be reused horizontally across multiple independent experiments within the same controller session, both currently and in the future.
[0162] S105. The controller will allow the system to reset and return to the standby phase if and only if all of the following conditions are met in this experiment: the first condition is that the unified recorder process has not been created, or has been confirmed to have exited and released the corresponding handle; the second condition is that the real-time processing process has not been created, or has been confirmed to have exited and released the corresponding handle; and the third condition is that all other experimental-level resources mentioned above have been cleared.
[0163] After the system returns to the standby phase, the next experiment will re-establish the experimental context and perform flow admission, prohibiting the use of experimental-level resources from the previous experiment.
[0164] Although embodiments of the invention have been shown and described, it will be understood by those skilled in the art that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the appended claims and their equivalents.
Claims
1. A method for state-gated recording and file protection of multi-source neural signals, characterized in that, Includes the following steps: Obtain the experiment configuration, generate the experiment identifier, establish the experiment context, and divide the data stream set, which includes required streams and optional streams; Perform a data stream discovery operation, compare the measured identity description vector with the target identity description vector, and determine whether the required stream satisfies the continuous and stable condition. Based on the determination results of the real-time processing enable flag and continuous stability conditions in the experimental configuration, a real-time processing process is created and started, and a processing readiness determination is performed. Start the unified recorder process, check the running status of the unified recorder process, the status of the standard input control channel, and the status of the target recording file, and comprehensively determine that recording is ready; The experiment configuration is sent to the experimental paradigm process, and the experiment start control signal is sent. The first planned experiment event flag is written. A unified recorder is used to synchronously write the continuous neural signal stream and experimental event marker stream into the target recording file until the end-of-experiment marker is written. Keep the data stream generating end running, and ensure that the unified recorder continuously records for a preset time redundancy protection duration; Send a unified recorder stop control command, and if the system fails to exit within the timeout period, send a forced termination command or control system enters an abnormal hold state. After confirming that the unified recorder process has exited, the size of the target recording file is read and confirmed, the target recording file is parsed, and the recording file acceptance flag is calculated. Clean up the experiment-level resources used by a single experiment, and retain the session-level resources.
2. The method for state-gated recording and file protection of multi-source neural signals according to claim 1, characterized in that, The determination of whether the required flow satisfies the continuous stability condition specifically includes: Within the preset single discovery waiting time and preset adjacent discovery period, data stream discovery and detection are performed cyclically; Extract the measured identity description vector corresponding to the current network node and process port, and perform a one-by-one comparison and matching with each component of the target identity description vector; A single match is considered successful when all five component values—stream name, stream type, source identifier, number of channels, and nominal sampling rate—are identical. Within a previously defined continuous period, a logical AND operation is performed on the matching status of all necessary flows in both time and space dimensions. If all necessary flows are accurately ready at the current moment and have maintained a single successful match within a previously defined number of consecutive periods, then the continuous stability condition is satisfied.
3. The method for state-gated recording and file protection of multi-source neural signals according to claim 1, characterized in that, The creation and initiation of the real-time processing process, and the determination of processing readiness, specifically include: When the real-time processing enable flag is read to indicate that the real-time processing is enabled, and the preceding required stream meets the continuous stability condition, a subprocess for performing real-time processing is created, and the real-time processing loop is started. Within the preset processing ready time limit, listen for the ready events output by the real-time processing process; The experiment identifier and real-time processing process identifier within the ready event are parsed. When the parsing result matches the current experiment context, the determination result of the processing readiness is calculated.
4. The method for state-gated recording and file protection of multi-source neural signals according to claim 1, characterized in that, The process of checking the running status of the unified recorder process, the status of the standard input control channel, and the status of the target recording file to comprehensively determine whether recording is ready includes: Check the status of the unified recorder process handle to confirm that the unified recorder process has not exited. Perform a zero-byte write test operation to the standard input handle of the unified recorder process to confirm that the underlying pipe buffer is not broken and that the standard input control channel is writable. Confirm in the file system that the target recording file has been created and can be successfully opened in write mode; When the three conditions of the unified recorder process not exiting, the standard input control channel being writable, and the target recording file being successfully opened are met simultaneously, the result of the recording readiness determination is calculated.
5. The method for state-gated recording and file protection of multi-source neural signals according to claim 1, characterized in that, The process of issuing experimental configurations and sending experimental start control signals to the experimental paradigm process, and writing the first planned experimental event marker, specifically includes: After determining that recording is ready, the serialized experimental configuration is sent to the standard input of the experimental paradigm process; After maintaining the preset control interval and confirming that the experimental paradigm process is alive, the experimental start control signal is sent to the experimental paradigm process. The time span from the recording ready moment to the first planned experimental event marker being written is defined as the recording preparation interval. The recording preparation interval covers the process of the unified recorder performing discovery and subscription feedback processing on all necessary streams. The duration of the recording preparation interval is not less than the sum of the preset control interval, the duration of the prompt tone, the no-event interval, and the time occupied by the warm-up screen.
6. The method for state-gated recording and file protection of multi-source neural signals according to claim 1, characterized in that, The process of using a unified recorder to synchronously write the continuous neural signal stream and experimental event labeling stream into the target recording file specifically includes: Based on the experimental phase sequence parameters and corresponding durations, a planned experimental event marker sequence is generated and combined with an independently preset set of running marker codes; Relying on the unified time base of the system's underlying layer, the continuously connected neural signal stream and experimental event tagging stream are timestamped; Multi-source data, after being calibrated with a unified timestamp, are synchronously written to the same target recording file in real time until the experimental paradigm process completes all stages of execution and writes a unique experiment end marker.
7. The method for state-gated recording and file protection of multi-source neural signals according to claim 1, characterized in that, The step of sending a unified recorder stop control command and, if the system fails to exit within a timeout period, sending a forced termination command or controlling the system to enter an abnormal hold state specifically includes: After the preset time redundancy protection period expires, when it is determined that the standard input of the unified recorder process is writable, a unified recorder stop control command is sent to the unified recorder process. If no unified recorder process exit event is received after the preset unified recorder process exit waiting time limit expires, a forced termination command is sent to the unified recorder process and the preset forced termination exit waiting time limit is re-entered. If the process exit is not confirmed by the expiration of the preset forced termination exit waiting time limit, the control system enters an abnormal hold state, skips the recorded file acceptance process and the experimental resource cleanup process, and retains the current unified recorder process handle and the underlying current data stream connection.
8. The method for state-gated recording and file protection of multi-source neural signals according to claim 1, characterized in that, After confirming the exit of the unified recorder process, reading and confirming the size of the target recording file specifically includes: Upon receiving the unified recorder process exit event, the size of the disk space currently occupied by the target recording file in bytes is read multiple times at a preset sampling time interval; When the file size is obtained continuously for the same number of preset consecutive samplings, it is determined that the disk write operation of the target recording file has been completed and the file size is confirmed to no longer change. If the cumulative number of reads reaches the preset maximum number of reads and still no consecutive files of the same size are obtained, the file system is determined to be abnormal, the subsequent parsing process is skipped and the result of failing the acceptance test is recorded.
9. The method for state-gated recording and file protection of multi-source neural signals according to claim 1, characterized in that, The process of parsing the target recording file and calculating the recording file acceptance flag specifically includes: The parser is invoked to read the target recording file sequentially, and a recovery scan strategy is executed for corrupted data areas that cannot be parsed normally, and the recovery scan byte range is recorded; From six dimensions—existence of physical structure, completeness of full file reading, completeness of required stream, order of timestamp sequence, existence of experiment end marker, and consistency of experiment event markers—state flags are extracted and logically ANDed to calculate six pass flags. The recovery positioning time of each recovery scan byte interval is traced in reverse, and the recovery scan judgment quantity is calculated based on the timing relationship between the recovery positioning time and the time when the experiment end mark is written; By combining the six check pass indicators and the recovery scan judgment quantity, a logical AND operation is performed to calculate the acceptance pass indicator of the recorded file.
10. A state-gated recording and file protection system for multi-source neural signals, applied to the state-gated recording and file protection method for multi-source neural signals as described in any one of claims 1-9, characterized in that, include: The lifecycle state controller is used to control the coordinated operation of the following modules based on system state variables; The experiment context establishment module is used to obtain the experiment configuration, generate the experiment identifier, establish the experiment context, and divide the data stream set into required and optional streams; The multi-source data stream discovery module is used to perform data stream discovery operations, compare the measured data with the target identity description vector, and determine whether the necessary stream meets the continuous and stable condition. The real-time processing startup module is used to create and start a real-time processing process based on the experimental configuration and judgment results, and to determine the processing readiness. The unified recorder startup module is used to start the unified recorder process, check the running and channel status, and comprehensively determine whether recording is ready. The experiment execution trigger module is used to issue experiment configurations and send experiment start control signals, and write the first planned experiment event flag; The signal and label recording module is used to synchronously write neural signal streams and experimental event label streams into the target recording file until the end of the experiment is written; The time redundancy protection module is used to keep the data stream generating end running and continuously record the preset time redundancy protection duration; The unified recorder stop module is used to send a unified recorder stop control command and, if the recorder fails to exit within a timeout period, send a forced termination command or control the system to enter an abnormal hold state. The recording file acceptance module is used to parse the file and calculate the recording file acceptance pass flag after confirming process exit and file size; The resource cleanup module is used to clean up the experiment-level resources used by a single experiment and retain the session-level resources.
