├── CHANGELOG.md ├── lib ├── fsrs │ ├── version.rb │ └── fsrs.rb └── fsrs.rb ├── sig └── fsrs.rbs ├── .gitignore ├── bin ├── setup └── console ├── Rakefile ├── Gemfile ├── .rubocop.yml ├── test ├── test_helper.rb ├── test_fsrs.rb └── test_serialization.rb ├── .github └── workflows │ └── main.yml ├── .rubocop_todo.yml ├── LICENSE.txt ├── fsrs.gemspec ├── .idx └── dev.nix ├── README.md ├── Gemfile.lock └── CODE_OF_CONDUCT.md /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [Unreleased] 2 | 3 | ## [0.1.0] - 2024-04-30 4 | 5 | - Initial release 6 | -------------------------------------------------------------------------------- /lib/fsrs/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Fsrs 4 | VERSION = "0.9.0" 5 | end 6 | -------------------------------------------------------------------------------- /sig/fsrs.rbs: -------------------------------------------------------------------------------- 1 | module Fsrs 2 | VERSION: String 3 | # See the writing guide of rbs: https://github.com/ruby/rbs#guides 4 | end 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | *.gem 10 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | 8 | # Do any other automated setup that you need to do here 9 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "bundler/gem_tasks" 4 | require "minitest/test_task" 5 | require "minitest/pride" 6 | 7 | Minitest::TestTask.create 8 | 9 | task default: %i[test] 10 | 11 | # require "rubocop/rake_task" 12 | 13 | # RuboCop::RakeTask.new 14 | 15 | # task default: %i[test rubocop] 16 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require "bundler/setup" 5 | require "fsrs" 6 | 7 | # You can add fixtures and/or initialization code here to make experimenting 8 | # with your gem easier. You can also use a different console, if you like. 9 | 10 | require "irb" 11 | IRB.start(__FILE__) 12 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source "https://rubygems.org" 4 | 5 | # Specify your gem's dependencies in fsrs.gemspec 6 | gemspec 7 | 8 | # Silence ruby deprecation warnings about irb and rdoc gems 9 | # no longer being included in stdlib from Ruby 3.5.0 10 | gem "irb" 11 | gem "rdoc" 12 | 13 | gem "minitest", "~> 5.16" 14 | gem "rake", "~> 13.0" 15 | gem "rubocop", "~> 1.21" 16 | gem "rubocop-minitest" 17 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | inherit_from: .rubocop_todo.yml 2 | 3 | AllCops: 4 | TargetRubyVersion: 3.0 5 | NewCops: enable 6 | SuggestExtensions: false 7 | 8 | Style/StringLiterals: 9 | EnforcedStyle: double_quotes 10 | 11 | Style/StringLiteralsInInterpolation: 12 | EnforcedStyle: double_quotes 13 | 14 | Naming/MethodParameterName: 15 | AllowedNames: s, r, d 16 | 17 | Metrics/MethodLength: 18 | Exclude: 19 | - 'test/**/test_*.rb' -------------------------------------------------------------------------------- /lib/fsrs.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "active_support/deprecator" 4 | require "active_support/deprecation" 5 | require "active_support/time" 6 | require "active_support/time_with_zone" 7 | 8 | require_relative "fsrs/version" 9 | require_relative "fsrs/fsrs" 10 | 11 | module Fsrs 12 | class Error < StandardError; end 13 | 14 | # 15 | ## An error for invalidate dates 16 | class InvalidDateError < Error 17 | def initialize(msg = "Date must be UTC and timezone-aware") 18 | super 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | $LOAD_PATH.unshift File.expand_path("../lib", __dir__) 4 | require "fsrs" 5 | 6 | require "minitest/autorun" 7 | require "minitest/pride" 8 | 9 | def print_scheduling_cards(scheduling_cards) 10 | # Useful for debugging 11 | # 12 | %i[again hard good easy].each do |state| 13 | puts scheduling_cards[Fsrs::Rating.const_get(state.upcase.to_sym)] 14 | .card.inspect 15 | puts scheduling_cards[Fsrs::Rating.const_get(state.upcase.to_sym)] 16 | .review_log.inspect 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Ruby 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | pull_request: 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | name: Ruby ${{ matrix.ruby }} 14 | strategy: 15 | matrix: 16 | ruby: 17 | - '3.3.1' 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: Set up Ruby 22 | uses: ruby/setup-ruby@v1 23 | with: 24 | ruby-version: ${{ matrix.ruby }} 25 | bundler-cache: true 26 | - name: Run Rubocop 27 | run: bundle exec rubocop 28 | - name: Run the default task 29 | run: bundle exec rake 30 | -------------------------------------------------------------------------------- /.rubocop_todo.yml: -------------------------------------------------------------------------------- 1 | # This configuration was generated by 2 | # `rubocop --auto-gen-config` 3 | # on 2025-05-29 19:12:15 UTC using RuboCop version 1.75.8. 4 | # The point is for the user to remove these configuration records 5 | # one by one as the offenses are removed from the code base. 6 | # Note that changes in the inspected code, or installation of new 7 | # versions of RuboCop, may require this file to be generated again. 8 | 9 | # Offense count: 7 10 | # Configuration parameters: AllowedMethods, AllowedPatterns, CountRepeatedAttributes. 11 | Metrics/AbcSize: 12 | Max: 31 13 | 14 | # Offense count: 2 15 | # Configuration parameters: CountComments, CountAsOne. 16 | Metrics/ClassLength: 17 | Max: 111 18 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2024 clayton 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /fsrs.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "lib/fsrs/version" 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = "fsrs" 7 | spec.version = Fsrs::VERSION 8 | spec.authors = ["clayton"] 9 | spec.email = ["6334+clayton@users.noreply.github.com"] 10 | 11 | spec.summary = "Ruby implementation of FSRS algorithm." 12 | spec.description = "A ruby implementation of the Open Spaced Repetition's Free Spaced Repetition Scheduler." 13 | spec.homepage = "https://github.com/clayton/rb-fsrs" 14 | spec.license = "MIT" 15 | spec.required_ruby_version = ">= 3.0.0" 16 | 17 | spec.metadata["allowed_push_host"] = "https://rubygems.org" 18 | 19 | spec.metadata["homepage_uri"] = spec.homepage 20 | spec.metadata["source_code_uri"] = "https://github.com/clayton/rb-fsrs" 21 | spec.metadata["changelog_uri"] = "https://github.com/clayton/rb-fsrs/blob/master/CHANGELOG.md" 22 | 23 | # Specify which files should be added to the gem when it is released. 24 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 25 | gemspec = File.basename(__FILE__) 26 | spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| 27 | ls.readlines("\x0", chomp: true).reject do |f| 28 | (f == gemspec) || 29 | f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile]) 30 | end 31 | end 32 | spec.bindir = "exe" 33 | spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } 34 | spec.require_paths = ["lib"] 35 | 36 | # Uncomment to register a new dependency of your gem 37 | # spec.add_dependency "example-gem", "~> 1.0" 38 | spec.add_dependency "activesupport", ">= 7.0", "< 9.0" 39 | 40 | # For more information and examples about making a new gem, check out our 41 | # guide at: https://bundler.io/guides/creating_gem.html 42 | spec.metadata["rubygems_mfa_required"] = "true" 43 | end 44 | -------------------------------------------------------------------------------- /.idx/dev.nix: -------------------------------------------------------------------------------- 1 | # To learn more about how to use Nix to configure your environment 2 | # see: https://developers.google.com/idx/guides/customize-idx-env 3 | { pkgs, ... }: { 4 | # Which nixpkgs channel to use. 5 | channel = "stable-24.11"; # or "unstable" 6 | 7 | # Use https://search.nixos.org/packages to find packages 8 | packages = [ 9 | # pkgs.go 10 | # pkgs.python311 11 | # pkgs.python311Packages.pip 12 | # pkgs.nodejs_20 13 | # pkgs.nodePackages.nodemon 14 | pkgs.ruby 15 | pkgs.ruby-lsp 16 | pkgs.gem 17 | pkgs.fish 18 | pkgs.stdenv.cc 19 | pkgs.gnumake 20 | ]; 21 | 22 | # Sets environment variables in the workspace 23 | env = {}; 24 | idx = { 25 | # Search for the extensions you want on https://open-vsx.org/ and use "publisher.id" 26 | extensions = [ 27 | # "vscodevim.vim" 28 | "rebornix.ruby" 29 | "Shopify.ruby-lsp" 30 | "wingrunr21.vscode-ruby" 31 | ]; 32 | 33 | # Enable previews 34 | previews = { 35 | enable = true; 36 | previews = { 37 | # web = { 38 | # # Example: run "npm run dev" with PORT set to IDX's defined port for previews, 39 | # # and show it in IDX's web preview panel 40 | # command = ["npm" "run" "dev"]; 41 | # manager = "web"; 42 | # env = { 43 | # # Environment variables to set for your server 44 | # PORT = "$PORT"; 45 | # }; 46 | # }; 47 | }; 48 | }; 49 | 50 | # Workspace lifecycle hooks 51 | workspace = { 52 | # Runs when a workspace is first created 53 | onCreate = { 54 | # Example: install JS dependencies from NPM 55 | # npm-install = "npm install"; 56 | "setup" = "bin/setup"; 57 | }; 58 | # Runs when the workspace is (re)started 59 | onStart = { 60 | # Example: start a background task to watch and re-build backend code 61 | # watch-backend = "npm run watch-backend"; 62 | "test" = "rake test"; 63 | }; 64 | }; 65 | }; 66 | } 67 | -------------------------------------------------------------------------------- /test/test_fsrs.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "test_helper" 4 | 5 | class FSRSTest < Minitest::Test 6 | def test_repeat 7 | f = Fsrs::Scheduler.new 8 | f.p.w = [ 9 | 1.14, 10 | 1.01, 11 | 5.44, 12 | 14.67, 13 | 5.3024, 14 | 1.5662, 15 | 1.2503, 16 | 0.0028, 17 | 1.5489, 18 | 0.1763, 19 | 0.9953, 20 | 2.7473, 21 | 0.0179, 22 | 0.3105, 23 | 0.3976, 24 | 0.0, 25 | 2.0902 26 | ] 27 | 28 | card = Fsrs::Card.new 29 | now = DateTime.parse("2022-11-29 12:30 +00:00") 30 | scheduling_cards = f.repeat(card, now) 31 | # print_scheduling_cards(scheduling_cards) 32 | 33 | ratings = [ 34 | Fsrs::Rating::GOOD, 35 | Fsrs::Rating::GOOD, 36 | Fsrs::Rating::GOOD, 37 | Fsrs::Rating::GOOD, 38 | Fsrs::Rating::GOOD, 39 | Fsrs::Rating::GOOD, 40 | Fsrs::Rating::AGAIN, 41 | Fsrs::Rating::AGAIN, 42 | Fsrs::Rating::GOOD, 43 | Fsrs::Rating::GOOD, 44 | Fsrs::Rating::GOOD, 45 | Fsrs::Rating::GOOD, 46 | Fsrs::Rating::GOOD 47 | ] 48 | ivl_history = [] 49 | 50 | ratings.each do |rating| 51 | card = scheduling_cards[rating].card 52 | ivl = card.scheduled_days 53 | ivl_history.push(ivl) 54 | now = card.due 55 | scheduling_cards = f.repeat(card, now) 56 | # print_scheduling_cards(scheduling_cards) 57 | end 58 | 59 | assert_equal [0, 5, 16, 43, 106, 236, 0, 0, 12, 25, 47, 85, 147], ivl_history 60 | end 61 | 62 | def test_datetime 63 | f = Fsrs::Scheduler.new 64 | card = Fsrs::Card.new 65 | 66 | # new cards should be due immediately after creation 67 | assert card.due >= DateTime.new 68 | 69 | # repeating a card with a non-UTC, non-timezone-aware datetime object should raise a Value Error 70 | assert_raises Fsrs::InvalidDateError do 71 | f.repeat(card, DateTime.parse("2022-11-29 12:30 +05:00")) 72 | end 73 | 74 | # repeat a card with rating good before next tests 75 | scheduling_cards = f.repeat(card, DateTime.now.utc) 76 | card = scheduling_cards[Fsrs::Rating::GOOD].card 77 | 78 | # card object's due and last_review attributes must be timezone aware and UTC 79 | assert_equal "UTC", card.due.zone 80 | assert_equal "UTC", card.last_review.zone 81 | 82 | # card object's due datetime should be later than its last review 83 | assert card.due >= card.last_review 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Ruby](https://github.com/clayton/rb-fsrs/actions/workflows/main.yml/badge.svg)](https://github.com/clayton/rb-fsrs/actions/workflows/main.yml) 2 | [![Gem Version](https://badge.fury.io/rb/fsrs.svg)](https://badge.fury.io/rb/fsrs) 3 | ## About The Project 4 | 5 | rb-fsrs is a Ruby Gem implements [Free Spaced Repetition Scheduler algorithm](https://github.com/open-spaced-repetition/free-spaced-repetition-scheduler). It helps developers apply FSRS in their flashcard apps. 6 | 7 | ## Getting Started 8 | 9 | ``` 10 | gem install fsrs 11 | ``` 12 | 13 | or 14 | 15 | ``` 16 | bundle add fsrs 17 | ``` 18 | 19 | ## Usage 20 | 21 | Create a card and review it at a given time: 22 | ```ruby 23 | require 'fsrs' 24 | 25 | scheduler = Fsrs::Scheduler.new 26 | card = Fsrs::Card.new 27 | now = DateTime.now.utc 28 | scheduling_cards = scheduler.repeat(card, now) 29 | ``` 30 | 31 | There are four ratings: 32 | ```ruby 33 | Rating::AGAIN # forget; incorrect response 34 | Rating::HARD # recall; correct response recalled with serious difficulty 35 | Rating::GOOD # recall; correct response after a hesitation 36 | Rating::EASY # recall; perfect response 37 | ``` 38 | 39 | 40 | Get the new state of card for each rating: 41 | ```ruby 42 | scheduling_cards[Rating::AGAIN].card 43 | scheduling_cards[Rating::HARD].card 44 | scheduling_cards[Rating::GOOD].card 45 | scheduling_cards[Rating::EASY].card 46 | ``` 47 | 48 | Get the scheduled days for each rating: 49 | ```ruby 50 | card_again.scheduled_days 51 | card_hard.scheduled_days 52 | card_good.scheduled_days 53 | card_easy.scheduled_days 54 | ``` 55 | 56 | Update the card after rating `GOOD`: 57 | ```ruby 58 | card = scheduling_cards[Rating::GOOD].card 59 | ``` 60 | 61 | Get the review log after rating `GOOD`: 62 | ```ruby 63 | review_log = scheduling_cards[Rating::GOOD].review_log 64 | ``` 65 | 66 | Get the due date for card: 67 | ```ruby 68 | due = card.due 69 | ``` 70 | 71 | There are four states: 72 | ```ruby 73 | State::NEW # Never been studied 74 | State::LEARNING # Been studied for the first time recently 75 | State::REVIEW # Graduate from learning state 76 | State::RELEARNING # Forgotten in review state 77 | ``` 78 | 79 | ## Acknowledgements 80 | 81 | * [Open Spaced Repetition](https://github.com/open-spaced-repetition) 82 | * [py-fsrs](https://github.com/open-spaced-repetition/py-fsrs) 83 | 84 | This library was ported from [py-fsrs](https://github.com/open-spaced-repetition/py-fsrs) to Ruby. Much refactoring to be done, but the core logic is the same. 85 | 86 | ## License 87 | 88 | Distributed under the MIT License. See `LICENSE` for more information. -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | fsrs (0.9.0) 5 | activesupport (>= 7.0, < 9.0) 6 | 7 | GEM 8 | remote: https://rubygems.org/ 9 | specs: 10 | activesupport (8.0.0) 11 | base64 12 | benchmark (>= 0.3) 13 | bigdecimal 14 | concurrent-ruby (~> 1.0, >= 1.3.1) 15 | connection_pool (>= 2.2.5) 16 | drb 17 | i18n (>= 1.6, < 2) 18 | logger (>= 1.4.2) 19 | minitest (>= 5.1) 20 | securerandom (>= 0.3) 21 | tzinfo (~> 2.0, >= 2.0.5) 22 | uri (>= 0.13.1) 23 | ast (2.4.3) 24 | base64 (0.2.0) 25 | benchmark (0.4.0) 26 | bigdecimal (3.1.8) 27 | concurrent-ruby (1.3.4) 28 | connection_pool (2.4.1) 29 | date (3.4.1) 30 | drb (2.2.1) 31 | erb (5.0.1) 32 | i18n (1.14.6) 33 | concurrent-ruby (~> 1.0) 34 | io-console (0.8.0) 35 | irb (1.15.2) 36 | pp (>= 0.6.0) 37 | rdoc (>= 4.0.0) 38 | reline (>= 0.4.2) 39 | json (2.12.2) 40 | language_server-protocol (3.17.0.5) 41 | lint_roller (1.1.0) 42 | logger (1.6.2) 43 | minitest (5.25.4) 44 | parallel (1.27.0) 45 | parser (3.3.8.0) 46 | ast (~> 2.4.1) 47 | racc 48 | pp (0.6.2) 49 | prettyprint 50 | prettyprint (0.2.0) 51 | prism (1.4.0) 52 | psych (5.2.6) 53 | date 54 | stringio 55 | racc (1.8.1) 56 | rainbow (3.1.1) 57 | rake (13.2.1) 58 | rdoc (6.14.0) 59 | erb 60 | psych (>= 4.0.0) 61 | regexp_parser (2.10.0) 62 | reline (0.6.1) 63 | io-console (~> 0.5) 64 | rubocop (1.75.8) 65 | json (~> 2.3) 66 | language_server-protocol (~> 3.17.0.2) 67 | lint_roller (~> 1.1.0) 68 | parallel (~> 1.10) 69 | parser (>= 3.3.0.2) 70 | rainbow (>= 2.2.2, < 4.0) 71 | regexp_parser (>= 2.9.3, < 3.0) 72 | rubocop-ast (>= 1.44.0, < 2.0) 73 | ruby-progressbar (~> 1.7) 74 | unicode-display_width (>= 2.4.0, < 4.0) 75 | rubocop-ast (1.44.1) 76 | parser (>= 3.3.7.2) 77 | prism (~> 1.4) 78 | rubocop-minitest (0.35.0) 79 | rubocop (>= 1.61, < 2.0) 80 | rubocop-ast (>= 1.31.1, < 2.0) 81 | ruby-progressbar (1.13.0) 82 | securerandom (0.4.0) 83 | stringio (3.1.7) 84 | tzinfo (2.0.6) 85 | concurrent-ruby (~> 1.0) 86 | unicode-display_width (3.1.4) 87 | unicode-emoji (~> 4.0, >= 4.0.4) 88 | unicode-emoji (4.0.4) 89 | uri (1.0.2) 90 | 91 | PLATFORMS 92 | arm64-darwin-23 93 | ruby 94 | 95 | DEPENDENCIES 96 | fsrs! 97 | irb 98 | minitest (~> 5.16) 99 | rake (~> 13.0) 100 | rdoc 101 | rubocop (~> 1.21) 102 | rubocop-minitest 103 | 104 | BUNDLED WITH 105 | 2.5.9 106 | -------------------------------------------------------------------------------- /test/test_serialization.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "test_helper" 4 | require "json" 5 | 6 | class SerializationTest < Minitest::Test 7 | def setup 8 | @now = DateTime.now 9 | end 10 | 11 | def test_card_serialization_roundtrip 12 | # 1. Create object using helper 13 | original = create_test_card 14 | 15 | # 2. Serialize with to_h and to_json 16 | serialized_hash = original.to_h 17 | serialized_json = original.to_h.to_json 18 | 19 | # 3. Deserialize and verify 20 | restored_from_hash = Fsrs::Card.from_h(serialized_hash) 21 | restored_from_json = Fsrs::Card.from_h(JSON.parse(serialized_json)) 22 | 23 | # Verify properties using helper 24 | assert_card_properties_equal(original, restored_from_hash) 25 | assert_card_properties_equal(original, restored_from_json) 26 | end 27 | 28 | def test_scheduler_serialization_roundtrip 29 | # 1. Create and modify 30 | original = Fsrs::Scheduler.new 31 | original.p.w = [1.1, 2.2, 3.3, 4.4] 32 | original.decay = -0.7 33 | original.factor = 1.2 34 | 35 | # 2. Test JSON roundtrip 36 | json_string = original.to_h.to_json 37 | parsed_hash = JSON.parse(json_string, symbolize_names: true) 38 | restored = Fsrs::Scheduler.from_h(parsed_hash) 39 | 40 | assert_equal original.p.w, restored.p.w 41 | assert_equal original.decay, restored.decay 42 | assert_equal original.factor, restored.factor 43 | end 44 | 45 | def test_parameters_serialization_roundtrip 46 | # 1. Create and modify 47 | original = Fsrs::Parameters.new 48 | original.w = [1.0, 2.0, 3.0] 49 | original.request_retention = 0.8 50 | original.maximum_interval = 1000 51 | 52 | # 2. Serialize 53 | serialized = original.to_h 54 | 55 | # 3. Deserialize 56 | restored = Fsrs::Parameters.from_h(serialized) 57 | 58 | # 4. Verify all properties 59 | assert_equal original.w, restored.w 60 | assert_equal original.request_retention, restored.request_retention 61 | assert_equal original.maximum_interval, restored.maximum_interval 62 | end 63 | 64 | def test_review_log_serialization_roundtrip 65 | original = Fsrs::ReviewLog.new( 66 | Fsrs::Rating::GOOD, 67 | 10, 68 | 5, 69 | @now, 70 | Fsrs::State::REVIEW 71 | ) 72 | 73 | serialized = original.to_h 74 | restored = Fsrs::ReviewLog.from_h(serialized) 75 | 76 | assert_equal original.rating, restored.rating 77 | assert_equal original.scheduled_days, restored.scheduled_days 78 | assert_equal original.elapsed_days, restored.elapsed_days 79 | assert_equal original.review, restored.review 80 | assert_equal original.state, restored.state 81 | end 82 | 83 | def test_scheduling_info_serialization_roundtrip 84 | # 1. Create test objects 85 | card = create_test_card 86 | log = Fsrs::ReviewLog.new(Fsrs::Rating::EASY, 15, 3, @now, Fsrs::State::REVIEW) 87 | original = Fsrs::SchedulingInfo.new(card, log) 88 | 89 | # 2. Test hash roundtrip 90 | restored = Fsrs::SchedulingInfo.from_h(original.to_h) 91 | assert_equal original.card.to_h, restored.card.to_h 92 | assert_equal original.review_log.to_h, restored.review_log.to_h 93 | 94 | # 3. Test JSON roundtrip (compare string representations) 95 | json_restored = Fsrs::SchedulingInfo.from_h(JSON.parse(original.to_h.to_json, symbolize_names: true)) 96 | assert_equal original.to_h.to_json, json_restored.to_h.to_json 97 | end 98 | 99 | private 100 | 101 | def create_test_card 102 | card = Fsrs::Card.new 103 | card.state = Fsrs::State::REVIEW 104 | card.due = @now 105 | card.stability = 1.5 106 | card.difficulty = 3.2 107 | card.elapsed_days = 5 108 | card.scheduled_days = 10 109 | card.reps = 3 110 | card.lapses = 1 111 | card.last_review = @now - 5 112 | card 113 | end 114 | 115 | def assert_card_properties_equal(original, restored) 116 | assert_equal original.state, restored.state 117 | assert_equal original.due.inspect, restored.due.inspect 118 | assert_equal original.stability, restored.stability 119 | assert_equal original.difficulty, restored.difficulty 120 | assert_equal original.elapsed_days, restored.elapsed_days 121 | assert_equal original.scheduled_days, restored.scheduled_days 122 | assert_equal original.reps, restored.reps 123 | assert_equal original.lapses, restored.lapses 124 | assert_equal original.last_review.inspect, restored.last_review.inspect 125 | end 126 | end 127 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or 22 | advances of any kind 23 | * Trolling, insulting or derogatory comments, and personal or political attacks 24 | * Public or private harassment 25 | * Publishing others' private information, such as a physical or email 26 | address, without their explicit permission 27 | * Other conduct which could reasonably be considered inappropriate in a 28 | professional setting 29 | 30 | ## Enforcement Responsibilities 31 | 32 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 33 | 34 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 35 | 36 | ## Scope 37 | 38 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 39 | 40 | ## Enforcement 41 | 42 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at 6334+clayton@users.noreply.github.com. All complaints will be reviewed and investigated promptly and fairly. 43 | 44 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 45 | 46 | ## Enforcement Guidelines 47 | 48 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 49 | 50 | ### 1. Correction 51 | 52 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 53 | 54 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 55 | 56 | ### 2. Warning 57 | 58 | **Community Impact**: A violation through a single incident or series of actions. 59 | 60 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 61 | 62 | ### 3. Temporary Ban 63 | 64 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 65 | 66 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 67 | 68 | ### 4. Permanent Ban 69 | 70 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 71 | 72 | **Consequence**: A permanent ban from any sort of public interaction within the community. 73 | 74 | ## Attribution 75 | 76 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 77 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 78 | 79 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 80 | 81 | [homepage]: https://www.contributor-covenant.org 82 | 83 | For answers to common questions about this code of conduct, see the FAQ at 84 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 85 | -------------------------------------------------------------------------------- /lib/fsrs/fsrs.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Fsrs 4 | # 5 | ## Scheduling Info 6 | class SchedulingInfo 7 | attr_accessor :card, :review_log 8 | 9 | def initialize(card, review_log) 10 | @card = card 11 | @review_log = review_log 12 | end 13 | 14 | def to_h 15 | { 16 | card: @card.to_h, 17 | review_log: @review_log.to_h 18 | } 19 | end 20 | 21 | def self.from_h(hash) 22 | new( 23 | Fsrs::Card.from_h(hash[:card]), 24 | Fsrs::ReviewLog.from_h(hash[:review_log]) 25 | ) 26 | end 27 | end 28 | 29 | # 30 | ## Review Log 31 | class ReviewLog 32 | attr_accessor :rating, :scheduled_days, :elapsed_days, :review, :state 33 | 34 | def initialize(rating, scheduled_days, elapsed_days, review, state) 35 | @rating = rating 36 | @scheduled_days = scheduled_days 37 | @elapsed_days = elapsed_days 38 | @review = review 39 | @state = state 40 | end 41 | 42 | def to_h 43 | { 44 | rating: @rating, 45 | scheduled_days: @scheduled_days, 46 | elapsed_days: @elapsed_days, 47 | review: @review, 48 | state: @state 49 | } 50 | end 51 | 52 | def self.from_h(hash) 53 | new( 54 | hash[:rating], 55 | hash[:scheduled_days], 56 | hash[:elapsed_days], 57 | hash[:review], 58 | hash[:state] 59 | ) 60 | end 61 | end 62 | 63 | # 64 | ## Determines next review date 65 | class CardScheduler 66 | attr_accessor :again, :hard, :good, :easy 67 | 68 | def initialize(card) 69 | @again = card.clone 70 | @hard = card.clone 71 | @good = card.clone 72 | @easy = card.clone 73 | end 74 | 75 | def update_state(state) 76 | case state 77 | when State::NEW 78 | update_new_state 79 | when State::LEARNING, State::RELEARNING 80 | update_learning_relearning_state(state) 81 | when State::REVIEW 82 | update_review_state 83 | end 84 | end 85 | 86 | def schedule(now, hard_interval, good_interval, easy_interval) 87 | update_schedule_days(hard_interval, good_interval, easy_interval) 88 | update_due_dates(now, hard_interval, good_interval, easy_interval) 89 | end 90 | 91 | def record_log(card, now) 92 | { 93 | Rating::AGAIN => record_again_log(card, now), 94 | Rating::HARD => record_hard_log(card, now), 95 | Rating::GOOD => record_good_log(card, now), 96 | Rating::EASY => record_easy_log(card, now) 97 | } 98 | end 99 | 100 | private 101 | 102 | def update_due_dates(now, hard_interval, good_interval, easy_interval) 103 | @again.due = now + 5.minutes 104 | @hard.due = hard_interval.positive? ? now + hard_interval.days : now + 10.minutes 105 | @good.due = now + good_interval.days 106 | @easy.due = now + easy_interval.days 107 | end 108 | 109 | def update_schedule_days(hard_interval, good_interval, easy_interval) 110 | @again.scheduled_days = 0 111 | @hard.scheduled_days = hard_interval 112 | @good.scheduled_days = good_interval 113 | @easy.scheduled_days = easy_interval 114 | end 115 | 116 | def update_new_state 117 | @again.state = State::LEARNING 118 | @hard.state = State::LEARNING 119 | @good.state = State::LEARNING 120 | @easy.state = State::REVIEW 121 | end 122 | 123 | def update_learning_relearning_state(state) 124 | @again.state = state 125 | @hard.state = state 126 | @good.state = State::REVIEW 127 | @easy.state = State::REVIEW 128 | end 129 | 130 | def update_review_state 131 | @again.state = State::RELEARNING 132 | @hard.state = State::REVIEW 133 | @good.state = State::REVIEW 134 | @easy.state = State::REVIEW 135 | @again.lapses += 1 136 | end 137 | 138 | def record_again_log(card, now) 139 | SchedulingInfo.new( 140 | @again, 141 | ReviewLog.new( 142 | Rating::AGAIN, 143 | @again.scheduled_days, 144 | card.elapsed_days, 145 | now, 146 | card.state 147 | ) 148 | ) 149 | end 150 | 151 | def record_hard_log(card, now) 152 | SchedulingInfo.new( 153 | @hard, 154 | ReviewLog.new( 155 | Rating::HARD, 156 | @hard.scheduled_days, 157 | card.elapsed_days, 158 | now, 159 | card.state 160 | ) 161 | ) 162 | end 163 | 164 | def record_good_log(card, now) 165 | SchedulingInfo.new( 166 | @good, 167 | ReviewLog.new( 168 | Rating::GOOD, 169 | @good.scheduled_days, 170 | card.elapsed_days, 171 | now, 172 | card.state 173 | ) 174 | ) 175 | end 176 | 177 | def record_easy_log(card, now) 178 | SchedulingInfo.new( 179 | @easy, 180 | ReviewLog.new( 181 | Rating::EASY, 182 | @easy.scheduled_days, 183 | card.elapsed_days, 184 | now, 185 | card.state 186 | ) 187 | ) 188 | end 189 | end 190 | 191 | # 192 | ## Rating 193 | class Rating 194 | AGAIN = 1 195 | HARD = 2 196 | GOOD = 3 197 | EASY = 4 198 | end 199 | 200 | # 201 | ## Card 202 | class Card 203 | attr_accessor :due, :stability, :difficulty, :elapsed_days, :scheduled_days, :reps, :lapses, :state, :last_review 204 | 205 | def initialize 206 | @due = DateTime.new 207 | @stability = 0.0 208 | @difficulty = 0.0 209 | @elapsed_days = 0 210 | @scheduled_days = 0 211 | @reps = 0 212 | @lapses = 0 213 | @state = State::NEW 214 | end 215 | 216 | def get_retrievability(now) 217 | decay = -0.5 218 | factor = (0.9**(1 / decay)) - 1 219 | 220 | return nil unless @state == State::REVIEW 221 | 222 | elapsed_days = [0, (now - @last_review).to_i].max 223 | (1 + (factor * elapsed_days / @stability))**decay 224 | end 225 | 226 | def deep_clone 227 | Marshal.load(Marshal.dump(self)) 228 | end 229 | 230 | def to_h 231 | { 232 | state: @state, due: @due, 233 | stability: @stability, difficulty: @difficulty, 234 | elapsed_days: @elapsed_days, scheduled_days: @scheduled_days, 235 | reps: @reps, lapses: @lapses, 236 | last_review: @last_review 237 | } 238 | end 239 | 240 | def self.from_h(hash) 241 | card = new 242 | hash.each do |key, value| 243 | if %w[due last_review].include?(key) && value.is_a?(String) 244 | # Handle DateTime fields from JSON input 245 | card.instance_variable_set("@#{key}", DateTime.parse(value)) 246 | else 247 | # Handle regular fields and DateTime objects from hash input 248 | card.instance_variable_set("@#{key}", value) 249 | end 250 | end 251 | card 252 | end 253 | end 254 | 255 | # 256 | ## State 257 | class State 258 | NEW = 0 259 | LEARNING = 1 260 | REVIEW = 2 261 | RELEARNING = 3 262 | end 263 | 264 | # 265 | ## Scheduler 266 | class Scheduler 267 | attr_accessor :p, :decay, :factor 268 | 269 | def initialize 270 | @p = Parameters.new 271 | @decay = -0.5 272 | @factor = (0.9**(1 / @decay)) - 1 273 | end 274 | 275 | def repeat(card, now) 276 | raise Fsrs::InvalidDateError unless now.utc? 277 | 278 | card = card.clone 279 | card.elapsed_days = card_elapsed_days(card, now) 280 | card.last_review = now 281 | card.reps += 1 282 | card_scheduler = CardScheduler.new(card) 283 | card_scheduler.update_state(card.state) 284 | 285 | schedule_card(card_scheduler, card, now) 286 | card_scheduler.record_log(card, now) 287 | end 288 | 289 | def card_elapsed_days(card, now) 290 | card.state == State::NEW ? 0 : (now - card.last_review).to_i 291 | end 292 | 293 | def schedule_card(card_scheduler, card, now) 294 | case card.state 295 | when State::NEW 296 | schedule_new_state(card_scheduler, now) 297 | when State::LEARNING, State::RELEARNING 298 | schedule_learning_relearning_state(card_scheduler, now) 299 | when State::REVIEW 300 | schedule_review_state(card_scheduler, card, now) 301 | end 302 | end 303 | 304 | module NewState # rubocop:disable Style/Documentation 305 | def schedule_new_state(s, now) 306 | init_ds(s) 307 | s.again.due = now + 60 308 | s.hard.due = now + (5 * 60) 309 | s.good.due = now + (10 * 60) 310 | easy_interval = next_interval(s.easy.stability) 311 | s.easy.scheduled_days = easy_interval 312 | s.easy.due = now + easy_interval.days 313 | end 314 | 315 | def init_ds(s) 316 | s.again.difficulty = init_difficulty(Rating::AGAIN) 317 | s.again.stability = init_stability(Rating::AGAIN) 318 | s.hard.difficulty = init_difficulty(Rating::HARD) 319 | s.hard.stability = init_stability(Rating::HARD) 320 | s.good.difficulty = init_difficulty(Rating::GOOD) 321 | s.good.stability = init_stability(Rating::GOOD) 322 | s.easy.difficulty = init_difficulty(Rating::EASY) 323 | s.easy.stability = init_stability(Rating::EASY) 324 | end 325 | 326 | def init_stability(r) 327 | [self.p.w[r - 1], 0.1].max 328 | end 329 | 330 | def init_difficulty(r) 331 | (self.p.w[4] - (self.p.w[5] * (r - 3))).clamp(1, 10) 332 | end 333 | end 334 | 335 | module LearningState # rubocop:disable Style/Documentation 336 | def schedule_learning_relearning_state(s, now) 337 | hard_interval = 0 338 | good_interval = next_interval(s.good.stability) 339 | easy_interval = [next_interval(s.easy.stability), good_interval + 1].max 340 | s.schedule(now, hard_interval, good_interval, easy_interval) 341 | end 342 | end 343 | 344 | module ReviewState # rubocop:disable Style/Documentation 345 | def schedule_review_state(s, card, now) 346 | interval = card.elapsed_days 347 | last_d = card.difficulty 348 | last_s = card.stability 349 | retrievability = forgetting_curve(interval, last_s) 350 | next_ds(s, last_d, last_s, retrievability) 351 | compute_review_state_intervals_and_schedule(s, now) 352 | end 353 | 354 | def forgetting_curve(elapsed_days, stability) 355 | (1 + (factor * elapsed_days / stability))**decay 356 | end 357 | 358 | def compute_review_state_intervals_and_schedule(s, now) 359 | hard_interval = next_interval(s.hard.stability) 360 | good_interval = next_interval(s.good.stability) 361 | hard_interval = [hard_interval, good_interval].min 362 | good_interval = [good_interval, hard_interval + 1].max 363 | easy_interval = [next_interval(s.easy.stability), good_interval + 1].max 364 | 365 | s.schedule(now, hard_interval, good_interval, easy_interval) 366 | end 367 | 368 | def mean_reversion(init, current) 369 | (self.p.w[7] * init) + ((1 - self.p.w[7]) * current) 370 | end 371 | end 372 | 373 | module Common # rubocop:disable Style/Documentation 374 | def next_ds(s, last_d, last_s, retrievability) 375 | s.again.difficulty = next_difficulty(last_d, Rating::AGAIN) 376 | s.again.stability = next_forget_stability(last_d, last_s, retrievability) 377 | s.hard.difficulty = next_difficulty(last_d, Rating::HARD) 378 | s.hard.stability = next_recall_stability(last_d, last_s, retrievability, Rating::HARD) 379 | s.good.difficulty = next_difficulty(last_d, Rating::GOOD) 380 | s.good.stability = next_recall_stability(last_d, last_s, retrievability, Rating::GOOD) 381 | s.easy.difficulty = next_difficulty(last_d, Rating::EASY) 382 | s.easy.stability = next_recall_stability(last_d, last_s, retrievability, Rating::EASY) 383 | end 384 | 385 | def next_difficulty(d, r) 386 | next_d = d - (self.p.w[6] * (r - 3)) 387 | mean_reversion(self.p.w[4], next_d).clamp(1, 10) 388 | end 389 | 390 | def next_recall_stability(d, s, r, rating) 391 | hard_penalty = rating == Rating::HARD ? self.p.w[15] : 1 392 | easy_bonus = rating == Rating::EASY ? self.p.w[16] : 1 393 | s * (1 + (Math.exp(self.p.w[8]) * (11 - d) * (s**-self.p.w[9]) * 394 | (Math.exp((1 - r) * self.p.w[10]) - 1) * hard_penalty * easy_bonus)) 395 | end 396 | 397 | def next_forget_stability(d, s, r) 398 | self.p.w[11] * (d**-self.p.w[12]) * (((s + 1)**self.p.w[13]) - 1) * 399 | Math.exp((1 - r) * self.p.w[14]) 400 | end 401 | 402 | def next_interval(s) 403 | new_interval = s / factor * ((self.p.request_retention**(1 / decay)) - 1) 404 | new_interval.round.clamp(1, self.p.maximum_interval) 405 | end 406 | end 407 | 408 | module Serialization # rubocop:disable Style/Documentation 409 | def to_h 410 | { 411 | p: @p.to_h, 412 | decay: @decay, 413 | factor: @factor 414 | } 415 | end 416 | 417 | module ClassMethods # rubocop:disable Style/Documentation 418 | def from_h(hash) 419 | scheduler = new 420 | scheduler.p = Parameters.from_h(hash[:p]) 421 | scheduler.decay = hash[:decay] 422 | scheduler.factor = hash[:factor] 423 | scheduler 424 | end 425 | end 426 | 427 | def self.included(base) 428 | base.extend(ClassMethods) 429 | end 430 | end 431 | 432 | include NewState 433 | include LearningState 434 | include ReviewState 435 | include Common 436 | include Serialization 437 | end 438 | 439 | # 440 | ## Parameters 441 | class Parameters 442 | attr_accessor :request_retention, :maximum_interval, :w 443 | 444 | def initialize 445 | @request_retention = 0.9 446 | @maximum_interval = 36_500 447 | @w = [0.4, 0.6, 2.4, 5.8, 4.93, 0.94, 0.86, 0.01, 1.49, 0.14, 0.94, 448 | 2.18, 0.05, 0.34, 1.26, 0.29, 2.61] 449 | end 450 | 451 | def to_h 452 | { 453 | request_retention: @request_retention, 454 | maximum_interval: @maximum_interval, 455 | w: @w 456 | } 457 | end 458 | 459 | def self.from_h(hash) 460 | params = new 461 | params.w = hash[:w] 462 | params.request_retention = hash[:request_retention] 463 | params.maximum_interval = hash[:maximum_interval] 464 | params 465 | end 466 | end 467 | end 468 | --------------------------------------------------------------------------------