diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 732a7332..530a6063 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -25,6 +25,8 @@ jobs: run: | python3 scripts/validate_sentences.py python3 scripts/test_sentence_validator.py + python3 scripts/test_phi_readings.py + python3 scripts/test_phi_roles.py - name: Test vocabulary schema run: python3 scripts/test_vocabulary_schema.py @@ -56,6 +58,9 @@ jobs: - name: Check sentence-order ledger is in sync run: python3 scripts/audit_sentence_order.py --check + - name: Check phrase-reading ledger is in sync + run: python3 scripts/audit_phrase_readings.py --check + - name: Check generated reference is in sync with vocabulary run: | python3 scripts/generate_reference.py diff --git a/CLAUDE.md b/CLAUDE.md index 88b2b12d..fc5ed17f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,6 +17,7 @@ Authority order when documents disagree: `canon.md`. Settled decisions there are - After vocabulary changes, regenerate derived artifacts: `python3 scripts/generate_reference.py` and `python3 scripts/build_site.py`. - After any change that touches Phi examples or citations anywhere in the corpus, regenerate the neighbor baseline with `python3 scripts/audit_phonetic_neighbors.py --output documents/validation/phonetic_neighbors_baseline.txt` and commit the file when it changes. Continuous integration diffs this baseline, and its attestation counts move whenever cited examples change, even when no word form does. - The same changes can move the sentence-order ledger. Regenerate it with `python3 scripts/audit_sentence_order.py --output documents/validation/sentence_order_baseline.txt` and read every added line before committing: each is a sentence that parses but may have a manner word outside the Slot 1 block or an object before a prepositional phrase. Repair the ones that do; commit the ledger with the ones whose order is right. +- The same changes move the phrase-reading ledger, which records for each file how many sentences divide into phrases in more than one way, how many clauses leave a role open, and how often `shia` is contested. Regenerate it with `python3 scripts/audit_phrase_readings.py --output documents/validation/phrase_readings_baseline.txt` and commit it. The figures are measurements, not faults: a higher number in a row is something to notice, not something that blocks a commit. - No AI attribution anywhere: no "Generated with" footers in PRs, no Co-Authored-By trailers in commits. Contributors are not singled out. - Self-generated filenames are lowercase snake_case; `README.md`, `CLAUDE.md`, and license files are the only exceptions. - Markdown paragraphs are single lines — never hard-wrap prose; renderers break on it. diff --git a/documents/README.md b/documents/README.md index bc62b4ae..52a104ad 100644 --- a/documents/README.md +++ b/documents/README.md @@ -62,6 +62,7 @@ The [grammar index](grammar/) leads to the authoritative machinery references an | [Four-syllable migration ledger](validation/four_syllable_migration.tsv) | Verified record of the completed lexical replacements. | | [Retired forms](validation/retired_forms.txt) | Shorter forms barred from lexical reassignment without restricting productive names. | | [Sentence validator](validation/sentence_validator.md) | Executable full-utterance grammar, diagnostic contract, commands, and known limits. | +| [Phrase-reading ledger](validation/phrase_readings_baseline.txt) | For each file: sentences that divide into phrases in more than one way, clauses with an open role, and contested uses of `shia`. | | [Sentence-order ledger](validation/sentence_order_baseline.txt) | Every sentence that parses but may hold a manner word outside the Slot 1 block or an object before a prepositional phrase; CI compares it. | The [project index](../project/) holds the records that govern work around these materials. diff --git a/documents/validation/phrase_readings_baseline.txt b/documents/validation/phrase_readings_baseline.txt new file mode 100644 index 00000000..837b407d --- /dev/null +++ b/documents/validation/phrase_readings_baseline.txt @@ -0,0 +1,277 @@ +# Phrase-reading ledger +# +# Generated by scripts/audit_phrase_readings.py. Do not edit by hand. +# One row per file; every dictionary example is gathered under vocabulary/. +# The counts are upper bounds on what the grammar leaves open. They use no +# meanings and are not rates of misunderstanding. +# +# sentences sentences parsed (each quoted sentence counts as one) +# divided sentences with more than one division into phrases, counting +# only nouns, pronouns, and names as free phrase ends +# full the same, also letting an event or quality noun head a phrase +# roles clauses whose one bare phrase may be subject or object +# relroles relative clauses whose head may be subject or object +# shia uses of shia +# contested uses of shia while two or more third persons are live +# doubled clauses with two separate shia +# +# Columns: file, sentences, divided, full, roles, relroles, shia, contested, doubled. + +book/00_the_boatman.md 7 5 5 0 1 1 0 0 +book/02_what_a_refusal_is.md 4 2 2 1 0 1 1 0 +book/03_announce_then_deliver.md 2 2 2 0 0 0 0 0 +book/05_what_it_will_not_say.md 2 1 2 0 0 0 0 0 +book/07_a_literature_before_a_community.md 2 2 2 0 0 1 0 0 +book/09_a_serious_practice.md 8 3 3 0 0 0 0 0 +book/10_the_distance_of_a_learned_tongue.md 2 0 0 0 0 0 0 0 +book/11_the_lens_not_the_cage.md 2 1 1 0 0 1 0 0 +book/12_a_language_for_the_commons.md 2 1 1 0 1 0 0 0 +book/13_escaping_words.md 1 0 0 0 0 0 0 0 +book/14_the_mind_question.md 1 0 0 1 0 0 0 0 +book/15_the_door.md 1 0 0 0 0 0 0 0 +documents/evaluation/content_vocabulary_scenario_tests.md 60 29 47 1 0 10 7 0 +documents/evaluation/narrative_test_corpus.md 75 18 27 7 0 1 1 0 +documents/evaluation/peace_linguistics_vocabulary_audit.md 2 1 1 0 0 0 0 0 +documents/evaluation/philosophical_capability_matrix.md 19 8 16 1 0 0 0 0 +documents/evaluation/philosophical_test_corpus.md 279 125 207 20 0 6 0 0 +documents/grammar/complementizer_reference.md 21 1 4 1 0 7 0 0 +documents/grammar/numeral_reference.md 14 0 0 1 0 0 0 0 +documents/grammar/particle_reference.md 57 8 17 22 0 5 0 0 +documents/grammar/philosophical_conversation.md 14 2 2 6 0 0 0 0 +documents/modules/household_and_daily_life.md 5 2 3 0 0 0 0 0 +documents/modules/work_craft_and_repair.md 2 2 2 0 0 0 0 0 +documents/reference/language_guide.md 3 1 1 0 0 0 0 0 +documents/reference/taught_patterns.md 49 11 19 0 0 0 0 0 +kia.md 5 0 0 0 0 0 0 0 +manual/part1_first_light/ch02_first_words/02_your_first_sentence.md 6 1 1 0 0 0 0 0 +manual/part1_first_light/ch02_first_words/03_the_music_of_vowel_hiatus.md 3 3 3 0 0 0 0 0 +manual/part1_first_light/ch02_first_words/04_ten_essential_words.md 6 1 1 0 0 0 0 0 +manual/part1_first_light/ch02_first_words/05_a_simple_conversation.md 8 1 1 0 0 0 0 0 +manual/part2_soul/ch05_social_philosophy/02_conversation_as_collaboration.md 2 0 0 2 0 0 0 0 +manual/part4_grammar/ch09_particle_system/01_introduction.md 2 0 0 2 0 0 0 0 +manual/part4_grammar/ch09_particle_system/02_three_slots_explained.md 2 1 1 0 0 0 0 0 +manual/part4_grammar/ch09_particle_system/03_slot_0_framing.md 14 0 2 1 0 1 1 0 +manual/part4_grammar/ch09_particle_system/04_slot_1_verb_phrase.md 27 4 5 9 0 4 0 0 +manual/part4_grammar/ch09_particle_system/05_slot_2_word_level.md 17 3 10 1 0 3 2 0 +manual/part4_grammar/ch09_particle_system/06_combining_particles.md 17 6 6 8 0 0 0 0 +manual/part4_grammar/ch10_mindful_sentence/01_introduction.md 1 1 1 0 0 0 0 0 +manual/part4_grammar/ch10_mindful_sentence/02_sov_worldview.md 1 1 1 0 0 0 0 0 +manual/part4_grammar/ch10_mindful_sentence/04_building_sentences.md 4 3 3 0 0 0 0 0 +manual/part4_grammar/ch10_mindful_sentence/05_questions_requests_conditions.md 18 6 7 3 0 0 0 0 +manual/part4_grammar/ch10_mindful_sentence/06_exercises.md 34 24 25 5 0 0 0 0 +manual/part4_grammar/ch11_nouns/02_zero_article_system.md 2 2 2 0 0 0 0 0 +manual/part4_grammar/ch11_nouns/03_plural_marking.md 1 1 1 0 0 0 0 0 +manual/part4_grammar/ch11_nouns/06_expressing_possession.md 5 2 4 0 0 0 0 0 +manual/part4_grammar/ch11_nouns/07_the_words_of_color.md 5 3 5 0 0 0 0 0 +manual/part4_grammar/ch11_nouns/08_the_words_of_place.md 21 5 9 0 0 3 3 0 +manual/part4_grammar/ch11_nouns/09_the_words_of_the_body.md 12 6 6 0 0 1 0 0 +manual/part4_grammar/ch11_nouns/10_the_words_of_the_heart.md 6 2 2 0 0 1 0 0 +manual/part4_grammar/ch11_nouns/11_the_words_of_the_arts.md 8 6 6 0 0 1 0 0 +manual/part4_grammar/ch11_nouns/12_the_words_of_the_exchange.md 4 1 1 0 0 0 0 0 +manual/part4_grammar/ch13_pronouns/01_core_pronouns.md 15 4 6 0 0 3 0 0 +manual/part4_grammar/ch13_pronouns/02_forming_plurals.md 7 1 1 0 0 2 0 0 +manual/part4_grammar/ch13_pronouns/03_reflexive_miso.md 14 0 0 1 0 6 0 0 +manual/part4_grammar/ch13_pronouns/04_reciprocal_wiso.md 11 0 0 0 0 1 0 0 +manual/part4_grammar/ch13_pronouns/05_deixis.md 8 3 5 0 0 1 0 0 +manual/part4_grammar/ch14_verbs_time/01_introduction.md 2 0 0 2 0 0 0 0 +manual/part4_grammar/ch14_verbs_time/02_past_to.md 10 1 1 6 0 3 0 0 +manual/part4_grammar/ch14_verbs_time/03_future_so.md 6 2 2 3 0 0 0 0 +manual/part4_grammar/ch14_verbs_time/04_aspect.md 9 0 0 5 0 4 0 0 +manual/part4_grammar/ch14_verbs_time/05_combining_tense_aspect.md 5 1 1 3 0 0 0 0 +manual/part4_grammar/ch14_verbs_time/06_event_nouns.md 7 1 4 1 0 1 0 0 +manual/part4_grammar/ch14_verbs_time/07_the_words_of_time.md 21 8 8 1 0 1 1 0 +manual/part4_grammar/ch14_verbs_time/08_the_turning_of_a_life.md 11 3 4 0 0 2 1 0 +manual/part4_grammar/ch15_voice_possibility/01_the_passive_se.md 9 1 1 0 0 0 0 0 +manual/part4_grammar/ch15_voice_possibility/02_the_causative_ka.md 13 6 7 0 0 0 0 0 +manual/part4_grammar/ch15_voice_possibility/03_possibility_po.md 10 0 0 2 0 1 0 0 +manual/part4_grammar/ch15_voice_possibility/04_necessity_na.md 8 0 0 1 0 0 0 0 +manual/part4_grammar/ch15_voice_possibility/05_negation_ma.md 11 0 1 5 0 0 0 0 +manual/part4_grammar/ch16_evidentiality/01_introduction.md 3 0 0 0 0 0 0 0 +manual/part4_grammar/ch16_evidentiality/02_direct_hi.md 5 0 1 1 0 2 0 0 +manual/part4_grammar/ch16_evidentiality/03_inferential_ke.md 5 0 0 0 0 2 0 0 +manual/part4_grammar/ch16_evidentiality/04_reportative_ti.md 6 0 2 1 0 1 0 0 +manual/part4_grammar/ch16_evidentiality/05_assumptive_ho.md 8 0 0 0 0 3 0 0 +manual/part4_grammar/ch16_evidentiality/06_why_evidentiality_matters.md 4 1 1 0 0 3 0 0 +manual/part5_complex/ch17_coordination/01_simple_conjunction.md 6 1 3 2 0 0 0 0 +manual/part5_complex/ch17_coordination/02_contrast.md 7 1 3 4 0 2 1 0 +manual/part5_complex/ch17_coordination/03_alternative.md 6 1 2 3 0 0 0 0 +manual/part5_complex/ch17_coordination/04_addition_we.md 8 2 3 0 0 0 0 0 +manual/part5_complex/ch18_discourse/01_introduction.md 4 0 0 3 0 0 0 0 +manual/part5_complex/ch18_discourse/02_consequence_and_contrast.md 11 0 2 6 0 2 0 0 +manual/part5_complex/ch18_discourse/03_addition_and_example.md 11 7 11 0 0 3 0 0 +manual/part5_complex/ch18_discourse/04_precision.md 10 2 3 4 0 3 0 0 +manual/part5_complex/ch19_subordinate_clauses/01_introduction.md 2 1 1 0 0 2 0 0 +manual/part5_complex/ch19_subordinate_clauses/02_complement_clauses.md 10 0 1 1 0 7 0 0 +manual/part5_complex/ch19_subordinate_clauses/03_speech.md 10 1 1 0 0 2 1 0 +manual/part5_complex/ch19_subordinate_clauses/04_adverbial_clauses.md 20 5 7 7 0 3 1 0 +manual/part5_complex/ch20_relative_clauses/01_introduction.md 2 0 0 0 0 0 0 0 +manual/part5_complex/ch20_relative_clauses/02_relativizer_whu.md 4 2 2 0 1 0 0 0 +manual/part5_complex/ch20_relative_clauses/03_headed_relative_clauses.md 11 7 7 0 3 2 0 0 +manual/part5_complex/ch20_relative_clauses/04_headless_relative_clauses.md 6 1 1 0 1 0 0 0 +manual/part6_mastery/ch21_social_context/01_the_vocative_kona.md 6 0 0 0 0 0 0 0 +manual/part6_mastery/ch21_social_context/02_politeness_pi.md 2 0 0 1 0 0 0 0 +manual/part6_mastery/ch21_social_context/03_the_honorific_system.md 5 0 0 0 0 0 0 0 +manual/part6_mastery/ch21_social_context/04_register_and_formality.md 5 1 1 2 0 0 0 0 +manual/part6_mastery/ch21_social_context/05_when_to_use_what.md 8 0 0 2 0 0 0 0 +manual/part6_mastery/ch22_living_in_phi/01_daily_practice.md 4 2 2 0 0 0 0 0 +manual/part6_mastery/ch22_living_in_phi/02_journaling.md 3 2 2 0 0 0 0 0 +manual/part6_mastery/ch22_living_in_phi/03_meditation.md 5 1 2 0 0 0 0 0 +manual/part6_mastery/ch22_living_in_phi/05_the_ongoing_journey.md 5 2 2 0 0 0 0 0 +manual/part6_mastery/ch23_source_material/01_where_source_material_lives.md 1 0 1 0 0 0 0 0 +manual/part6_mastery/ch23_source_material/02_names_across_languages.md 1 1 1 0 0 0 0 0 +manual/part6_mastery/ch23_source_material/03_exact_records_and_technical_material.md 2 0 2 0 0 0 0 0 +manual/part6_mastery/ch23_source_material/04_translation_and_responsibility.md 2 0 1 0 0 1 0 0 +manual/part7_reference/modules/accessibility_and_participation.md 29 8 22 0 0 4 1 0 +manual/part7_reference/modules/commons_and_collective_governance.md 34 25 32 0 0 1 0 0 +manual/part7_reference/modules/ecological_systems_and_material_life.md 33 23 31 0 0 0 0 0 +manual/part7_reference/modules/household_and_daily_life.md 32 27 30 0 0 0 0 0 +manual/part7_reference/modules/medical_and_bodily_care.md 31 15 23 0 0 13 1 0 +manual/part7_reference/modules/philosophical_reasoning.md 29 11 22 1 0 6 2 0 +manual/part7_reference/modules/systems_and_shared_infrastructure.md 32 23 31 0 0 0 0 0 +manual/part7_reference/modules/work_craft_and_repair.md 35 24 28 0 0 8 0 0 +manual/part7_reference/sample_texts.md 23 4 6 1 0 0 0 0 +pamphlets/adverbial_clauses/01_the_frame_before_the_deed.md 1 0 0 0 0 0 0 0 +pamphlets/adverbial_clauses/02_sequence_pheo_phoe.md 5 0 0 3 0 1 0 0 +pamphlets/adverbial_clauses/03_simultaneity_whau.md 4 1 1 0 0 0 0 0 +pamphlets/adverbial_clauses/04_reason_lao.md 3 1 2 1 0 0 0 0 +pamphlets/adverbial_clauses/05_purpose_lila.md 3 0 1 3 0 1 0 0 +pamphlets/adverbial_clauses/06_concession_shai.md 2 1 1 0 0 0 0 0 +pamphlets/adverbial_clauses/07_the_frame_and_the_main_clause.md 2 1 1 1 0 0 0 0 +pamphlets/coordination/01_equal_partners_nela.md 6 2 3 2 0 0 0 0 +pamphlets/coordination/02_the_contrast_thona.md 4 0 1 2 0 2 1 0 +pamphlets/coordination/03_the_fork_sola.md 5 1 1 3 0 0 0 0 +pamphlets/coordination/04_adding_alongside_we.md 8 0 1 0 0 2 2 0 +pamphlets/evidentiality/01_four_sources_one_stack.md 7 1 1 0 0 2 0 0 +pamphlets/evidentiality/02_witness_hi.md 7 6 6 0 0 0 0 0 +pamphlets/evidentiality/03_signs_ke.md 9 3 3 0 0 1 0 0 +pamphlets/evidentiality/04_word_ti.md 13 3 4 0 0 4 2 0 +pamphlets/evidentiality/05_expectation_ho.md 10 1 1 0 0 5 0 0 +pamphlets/evidentiality/06_choosing_and_combining.md 10 4 5 1 0 2 2 0 +pamphlets/evidentiality/07_a_journal_of_sources.md 7 2 2 0 0 0 0 0 +pamphlets/evidentiality/08_common_errors.md 10 2 2 0 0 2 0 0 +pamphlets/evidentiality/10_appendix.md 11 2 2 0 0 1 0 0 +pamphlets/naming/01_a_name_is_a_word.md 4 4 4 0 0 0 0 0 +pamphlets/naming/02_the_announcing_ne.md 10 6 8 0 0 2 0 0 +pamphlets/naming/03_calling_kona.md 8 0 0 0 0 0 0 0 +pamphlets/naming/04_the_three_honorifics.md 5 0 0 0 0 0 0 0 +pamphlets/naming/05_the_family_register.md 8 0 2 2 0 0 0 0 +pamphlets/naming/07_the_open_door.md 20 7 8 1 0 0 0 0 +pamphlets/naming/08_common_errors.md 6 0 0 0 0 0 0 0 +pamphlets/nouns_classifiers/01_the_bare_noun.md 1 1 1 0 0 0 0 0 +pamphlets/nouns_classifiers/02_marking_many_lo.md 1 1 1 0 0 0 0 0 +pamphlets/nouns_classifiers/05_describing_before_the_noun.md 1 1 1 0 0 0 0 0 +pamphlets/nouns_classifiers/07_having_and_holding.md 2 2 2 0 0 0 0 0 +pamphlets/pronouns_topic_drop/01_three_words_one_shape.md 4 0 0 0 0 2 0 0 +pamphlets/pronouns_topic_drop/02_case_from_position.md 5 1 2 0 0 0 0 0 +pamphlets/pronouns_topic_drop/03_building_we.md 5 1 1 0 0 2 0 0 +pamphlets/pronouns_topic_drop/04_back_to_yourself_miso.md 8 0 0 1 0 3 0 0 +pamphlets/pronouns_topic_drop/05_between_each_other_wiso.md 8 0 0 0 0 1 0 0 +pamphlets/pronouns_topic_drop/06_pointing_ha_ra.md 5 0 2 0 0 1 0 0 +pamphlets/pronouns_topic_drop/07_the_dropped_subject.md 8 2 2 0 0 0 0 0 +pamphlets/relative_clauses/03_headed_relatives_examples.md 10 5 5 0 3 2 0 0 +pamphlets/relative_clauses/04_headless_relatives.md 16 6 6 1 4 0 0 0 +pamphlets/relative_clauses/05_advanced_patterns.md 21 10 10 0 1 2 0 0 +pamphlets/relative_clauses/07_exercises.md 2 1 1 0 1 0 0 0 +pamphlets/source_material/02_names_and_adaptation.md 1 1 1 0 0 0 0 0 +pamphlets/source_material/03_preserving_records.md 2 0 2 0 0 0 0 0 +pamphlets/source_material/04_reference_without_an_atom.md 2 2 2 0 0 0 0 0 +pamphlets/source_material/05_translation_and_commitment.md 1 0 1 0 0 0 0 0 +pamphlets/source_material/06_voice_page_and_modes.md 1 0 1 0 0 0 0 0 +pamphlets/source_material/08_answers.md 2 1 2 0 0 0 0 0 +pamphlets/spoken_punctuation/01_one_silent_mark.md 2 0 0 0 0 0 0 0 +pamphlets/spoken_punctuation/02_the_question_mark_wa.md 8 2 3 1 0 0 0 0 +pamphlets/spoken_punctuation/03_the_quotation_marks.md 10 3 3 0 0 1 0 0 +pamphlets/spoken_punctuation/04_comma_of_address_capital.md 6 1 1 1 0 0 0 0 +pamphlets/spoken_punctuation/05_the_clause_commas.md 6 2 3 3 0 1 0 0 +pamphlets/spoken_punctuation/06_the_exclamation_worded.md 4 0 1 0 0 0 0 0 +pamphlets/spoken_punctuation/07_twenty_complete_utterances.md 15 1 1 1 0 0 0 0 +pamphlets/spoken_punctuation/08_the_marks_with_no_counterpart.md 8 3 4 2 0 2 0 0 +pamphlets/spoken_punctuation/09_the_dictation_test.md 9 0 0 1 0 0 0 0 +pamphlets/tengwar_mode/01_two_hands_for_one_language.md 1 1 1 0 0 0 0 0 +pamphlets/tengwar_mode/03_the_vowel_marks_above_and_below.md 1 1 1 0 0 0 0 0 +pamphlets/tengwar_mode/04_one_tengwa_two_vowels.md 2 1 1 0 0 0 0 0 +pamphlets/tengwar_mode/05_romen_and_ore_the_two_rs.md 2 2 2 0 0 0 0 0 +pamphlets/tengwar_mode/06_the_silent_marks.md 1 0 1 0 0 0 0 0 +pamphlets/tengwar_mode/07_a_line_written_by_hand.md 3 1 1 0 0 0 0 0 +pamphlets/tengwar_mode/08_common_errors.md 5 3 4 0 0 0 0 0 +pamphlets/tengwar_mode/11_examples.md 23 5 7 0 0 4 2 0 +pamphlets/tense_aspect/01_the_verb_at_rest.md 3 0 0 3 0 0 0 0 +pamphlets/tense_aspect/02_looking_back_to.md 4 0 0 2 0 1 0 0 +pamphlets/tense_aspect/03_looking_forward_so.md 4 1 1 2 0 0 0 0 +pamphlets/tense_aspect/04_within_and_whole_si_ki.md 6 2 2 2 0 1 0 0 +pamphlets/tense_aspect/05_the_edges_pa_te.md 4 0 0 0 0 1 1 0 +pamphlets/tense_aspect/06_the_pattern_ro.md 5 0 0 0 0 0 0 0 +pamphlets/tense_aspect/07_the_ten_combinations.md 6 2 2 0 0 2 1 0 +pamphlets/tense_aspect/08_the_day_around_the_verb.md 7 3 3 1 0 0 0 0 +pamphlets/ternary_numerals/01_counting_in_threes.md 5 1 1 0 0 0 0 0 +pamphlets/ternary_numerals/03_the_four_natures.md 6 0 0 0 0 0 0 0 +pamphlets/ternary_numerals/04_position_nu.md 2 0 0 0 0 0 0 0 +pamphlets/ternary_numerals/05_the_honest_about.md 4 0 0 0 0 0 0 0 +pamphlets/ternary_numerals/06_calculating_aloud.md 16 0 0 1 0 0 0 0 +pamphlets/ternary_numerals/07_market_day.md 24 9 9 0 0 0 0 0 +pamphlets/ternary_numerals/08_common_errors.md 6 0 0 0 0 0 0 0 +pamphlets/three_slots/01_one_machine_three_scopes.md 1 1 1 0 0 0 0 0 +pamphlets/three_slots/02_slot_0_framing.md 7 0 0 1 0 1 0 0 +pamphlets/three_slots/03_slot_1_tense_aspect.md 7 0 0 4 0 1 0 0 +pamphlets/three_slots/04_slot_1_voice.md 7 4 4 0 0 0 0 0 +pamphlets/three_slots/05_slot_1_evidence_modality.md 6 0 1 2 0 0 0 0 +pamphlets/three_slots/07_slot_2_nesting_phrase.md 4 1 2 1 0 1 0 0 +pamphlets/three_slots/09_one_sentence_grown.md 8 5 5 0 0 0 0 0 +primer/01_the_household.md 24 9 17 0 0 0 0 0 +primer/02_the_day_begins.md 18 9 9 0 0 0 0 0 +primer/03_big_and_small.md 17 5 13 0 0 0 0 0 +primer/04_at_the_door.md 20 1 5 0 0 0 0 0 +primer/05_whose_and_where.md 21 2 7 0 0 0 0 0 +primer/06_around_the_village.md 24 6 6 0 0 0 0 0 +primer/07_yesterday.md 23 4 6 0 0 0 0 0 +primer/08_tomorrow.md 25 9 10 0 0 0 0 0 +primer/09_meanwhile.md 18 2 2 3 0 0 0 0 +primer/10_finished_work.md 20 8 8 0 0 0 0 0 +primer/11_every_morning.md 18 3 5 0 0 0 0 0 +primer/12_the_year_turns.md 28 1 4 0 0 0 0 0 +primer/13_what_is_not.md 17 2 4 1 0 0 0 0 +primer/14_the_rules_of_the_house.md 23 3 3 0 0 0 0 0 +primer/15_at_the_market.md 25 5 5 1 0 1 1 0 +primer/16_visitors.md 25 2 3 0 0 1 0 0 +primer/17_the_gift.md 27 6 11 4 0 0 0 0 +primer/18_together.md 16 5 6 0 0 0 0 0 +primer/19_the_message.md 17 4 6 1 0 0 0 0 +primer/20_the_question.md 14 4 4 0 0 0 0 0 +primer/21_the_elders_story.md 21 7 8 0 0 0 0 0 +primer/22_the_one_who.md 16 1 1 0 0 0 0 0 +primer/23_weather_plans.md 17 2 2 0 0 0 0 0 +primer/24_the_news.md 24 10 10 3 0 0 0 0 +primer/25_the_work_gets_done.md 13 2 3 0 0 0 0 0 +primer/26_making_it_happen.md 13 7 8 0 0 0 0 0 +primer/27_the_wish.md 13 5 5 0 0 0 0 0 +primer/28_how_warm_is_the_soup.md 13 0 13 0 0 0 0 0 +primer/29_more_and_most.md 11 2 11 0 0 1 1 0 +primer/30_this_one_only_this_one.md 11 2 2 0 0 0 0 0 +short_road.md 16 6 6 0 0 0 0 0 +texts/a_second_way_for_water.md 198 93 143 8 0 44 35 0 +texts/babel_text.md 28 17 19 1 0 17 8 0 +texts/care_and_coercion.md 82 28 51 5 0 0 0 0 +texts/gibran/on_children.md 31 15 19 1 0 14 2 0 +texts/gibran/on_giving.md 50 24 36 8 0 1 0 0 +texts/gibran/on_love.md 50 21 33 8 0 17 7 1 +texts/gibran/on_work.md 24 8 18 8 0 1 0 0 +texts/heart_sutra.md 37 11 26 1 0 8 1 0 +texts/human_rights_article_one.md 4 3 3 0 0 5 3 1 +texts/little_prince_excerpts.md 7 4 5 1 0 0 0 0 +texts/metta_sutta.md 28 8 17 1 0 17 3 0 +texts/news_from_nowhere/chapter_01.md 109 54 77 2 2 82 20 1 +texts/news_from_nowhere/chapter_02.md 403 157 266 31 7 87 11 0 +texts/news_from_nowhere/chapter_03.md 462 186 298 40 5 119 21 2 +texts/news_from_nowhere/chapter_04.md 159 76 115 9 4 39 12 0 +texts/news_from_nowhere/chapter_05.md 308 134 210 32 4 119 30 4 +texts/news_from_nowhere/chapter_06.md 361 139 227 22 5 127 57 4 +texts/north_wind_and_sun.md 25 11 14 3 0 13 7 0 +texts/ring_verse_refusal.md 4 2 2 0 0 2 2 0 +texts/schleicher_fable.md 17 9 10 1 0 0 0 0 +texts/solarpunk_manifesto.md 110 71 88 2 7 41 13 0 +texts/tao_te_ching.md 52 13 39 1 0 17 9 0 +texts/the_mended_wall.md 57 25 45 2 0 1 1 0 +texts/the_report_at_dusk.md 56 30 47 2 0 2 2 0 +texts/the_worth_of_a_fallen_branch.md 56 26 42 0 0 1 1 0 +texts/velveteen_rabbit.md 530 223 323 25 4 376 158 25 +vocabulary/ 1464 613 944 44 2 0 0 0 diff --git a/documents/validation/sentence_validator.md b/documents/validation/sentence_validator.md index 8af3f5c7..952ad814 100644 --- a/documents/validation/sentence_validator.md +++ b/documents/validation/sentence_validator.md @@ -91,6 +91,54 @@ A literal `--sentence` always prints its advisories. Corpus runs print them with The ledger mixes two kinds of line: sentences whose order is right under the reading their author meant, and sentences that still need repair. Presence in the ledger means a sentence has been seen, not that it has been cleared. Lines from `texts/` wait for the two-phase translation process before any change. +## Counting readings + +The parser answers whether a sentence has a canonical parse. `scripts/phi_readings.py` asks how many it has. Phi marks the edges of embedded statements, questions, and quotations with words and leaves the commoner edges unmarked: where the subject ends and the object begins, where a prepositional phrase ends, whether a quality word before the verb is manner or object, and where an adverbial or relative clause hands over to the clause around it. + +A reading is one way of dividing a clause into phrases. For each core clause the counter takes the words before the Slot 1 stack, or before the verb when there is no stack, and enumerates every division that canon's order allows: subject, adjuncts, object or complement, then manner. It adds every place a dependent clause could end, using the parser to decide which ends are grammatical and its own phrase rules to discard the ones that leave an undividable clause. Readings multiply across the clauses of a sentence. Each sentence inside a quotation is counted as a sentence of its own. + +`phao lopia shelu theo.` has three: the parent reads the child's book, the parent's child reads the book, and the single phrase in which nobody is named as reader. `mia shia wiru ma nila.` has one, because a pronoun begins its phrase. + +Two counts are reported. The conservative count lets a noun, pronoun, or name end a phrase anywhere and lets an adjective or verb stand as a phrase only by itself and only where nothing else can end the phrase. The full count also lets an adjective (quality noun) or a verb (event noun) head a phrase with modifiers of its own, so `mia nohero to helui.` gains "my belief changed" beside "I changed the belief". + +What the figure is not: + +- It is an upper bound on structural choice. The counter has no verb valency and no meanings, so `mia nosa thole.` counts "my now practices" beside "I practice now". It does not estimate how often a reader goes wrong. +- It does not count bracketing inside a phrase, the role of a clause's only bare phrase (subject or object), or which referent a pronoun picks out. The last two are where the certified texts' recorded misreadings fall, and the next section counts them. +- It follows the parser's choice for clause coordination, and a small share of sentences in the texts fall outside its clause model; the report lists them as not modelled. + +```bash +python3 scripts/audit_phrase_readings.py --sentence "phao lopia shelu theo." +python3 scripts/audit_phrase_readings.py +python3 scripts/audit_phrase_readings.py --paths texts/velveteen_rabbit.md +python3 scripts/audit_phrase_readings.py --openers ha ra lo +``` + +The last form is a what-if. Canon lets a possessor stand before a phrase that opens with `ha` or `lo` (`lo mia lo manuwe`). `--openers` counts the readings that would remain if the listed Slot 2 words always began a new phrase. + +## Open roles and third persons + +`scripts/phi_roles.py` counts the two things the reading count leaves out. + +An open role is a clause with one bare phrase and a verb that takes an object elsewhere. Phi marks no case and lets an established subject go unsaid, so the phrase is the subject, with nothing said about an object, or the object, with the subject unsaid. `lopia nuola.` is "the child eats" and "(it) eats the child". A relative clause has the same opening when one phrase is left inside it: in `whu mia nila miona`, the person is the one I see or the one who sees me. A passive, a command, or a second bare phrase settles the role. + +The lexicon records no valency, so the corpus supplies it. A verb counts as taking an object when it appears at least once in the passive, with two bare phrases that cannot be read as one (`mia thia nila.`), or in a command over a noun phrase (`no shelu theo.`), in a clause that has a single structural reading. A verb never witnessed that way is treated as taking no object, so the count leans low for rare verbs. + +A contested third person is a `shia`, or an unsaid subject, at a point where two or more third persons are live. A third person here is the head of a clause-initial bare phrase that is a noun or a name, and it stays live for three further sentences. The tracker knows nothing of animacy or plausibility. It also counts clauses with two separate `shia`, where the listener has to tell them apart inside one clause. + +Both counts are indicators of exposure. A first-person `mia nila.` is an open role by this definition and no reader stumbles on it, so the report also gives the open roles whose phrase is not `mia` or `thia`. + +## The phrase-reading ledger + +`documents/validation/phrase_readings_baseline.txt` holds one row per file: sentences, sentences with more than one division on each count, open roles, relative clauses with an open head, uses of `shia`, contested uses, and clauses with two `shia`. Every dictionary example is gathered into one `vocabulary/` row. CI regenerates the ledger and fails on any difference. + +```bash +python3 scripts/audit_phrase_readings.py --output documents/validation/phrase_readings_baseline.txt +python3 scripts/audit_phrase_readings.py --check +``` + +The figures are for watching a trend, text by text. A row usually changes only when its file does. The open-role columns can also move when another file adds the first witness that a verb takes an object. + ## Limits The parser knows grammar, not the English translation beside it. It cannot decide whether an evidential claim is warranted, whether an honorific tells the truth about a relationship, or whether a source sentence has been translated faithfully. diff --git a/project/development_log.md b/project/development_log.md index 5d094f9f..9846bea5 100644 --- a/project/development_log.md +++ b/project/development_log.md @@ -147,6 +147,8 @@ Implementation status, dependencies, optional evaluation work, and the next deve | D129 | Accepted | Certify chapter 1 of *News from Nowhere* under the isolated translation process. | Seventy-seven aligned Phi units reconstruct all 5,214 normalized Morris characters. The source-to-Phi pass read every unit against the source and repaired 30 under D126 and D128: adjuncts moved behind explicit subjects, dependent clauses given their own tense, past narration that had lost `to` restored, manner words brought inside the Slot 1 block, `miso` used as possessor and after a preposition, the old `sui` with an event noun replaced by `whau`, and a concessive `lu` recast with `shai`. Three fresh source-blind contexts derived the complete frozen stream, and a fourth checked the 26 units of the risk queue and deterministic sample. Its findings led to five further repairs: a passive for the rope-supported bridge whose relative clause read both ways, a `tha` frame that held two sentences, `li` on a quantity, a degree particle on a preposition, and a relative clause whose tense said "had stood" for "was standing". A fifth and a sixth context derived and checked those. The Phi freezes at `b8e2ae226d10405915618993bb9584d4e5974f537d88863ef5d9f12e8a9258ff`. The chapter no longer has a line in the sentence-order ledger. Left for the vocabulary work: `we` where Morris says "again", and `phirae` where he says "the rest". | | D130 | Accepted | Settle the small words and the clause relations, and license `tei` over a clause. | Seven maintainer rulings on 2026-11-24 answer section 4.7 and recommendation 16 of the November assessment. Each rests on a survey of every aligned text unit by its source line and on a source-blind reading test of thirty-eight invented sentences, two fresh readers per form; the sheet he ruled from is `archive/small_words_study.md`. Again receives a word (D131). Still is `tei nosa`, not yet is `tei nosa` with a negated verb, already is `phoe nosa` with `ki`, and no longer is `to te`, since readers took present `te` as a stopping in progress; `ra shemu` replaces `nosa` in a past account. Even is `we ko`, which the Slot 2 order already allowed and no text had used; bare `we` read as too every time. Instead is negation with `thona` or `whekai`, and except is `li` with the predicate turned. No relator is coined for when: `pheo` takes sequence, `whau` takes overlap and may now hold the briefer event, whenever is `lu` with `ro`, and `lu` never renders one past occasion, which both readers read as if. `tei` may stand over a clause, the one grammar extension: the clause comes first and carries its own tense, `tei` stays a preposition, and the relators stay six; the reason is the one that brought `whau`, and two of five source lines had dropped their until. At once, as soon as, soon, since, unless, even if, whether or not, only if, as if, so that, and the more the more are registered as the existing grammar says them. Canon gains four bullets, `documents/reference/small_words.md` is the registry, five fixed phrases enter the compound registry, thirteen entries, the grammar references, six manual pages, and five pages of the Adverbial Clauses pamphlet carry the rulings, and the pamphlet no longer teaches that `tei` takes no clause. The parser accepts a clause under sentence-initial `tei` and gains advisory `PHL005` for a `lu` condition whose two sentences are past with no `ro`. No text changes; `project/deferred_questions.md` lists the affected lines for one sweep after the language has settled. | | D131 | Accepted | Coin base `ture` for again. | The reading test in D130 tried four existing devices for again (`we` before the verb, `newu` as manner, an ordinal with `shemu`, and `phirae shemu`) and none was read as again above about seventy percent; in the one source-blind chapter all three `we` lines came back as also. `ture` is an adjective: directly before the verb, inside the Slot 1 block, it is again, and before a noun it is one more of the same kind, which leaves `phirae` to mean different. The maintainer chose the form from three cleared candidates. It has no neighbour at edit distance 1 and none in the phonetic audit, is no English word, and shares its opening with `turema` (return) as audible kinship without a productive affix. Two syllables rest on the protocol's daily-round test. The gloss is `again` although the class is adjective, because a gloss line reading `repeated` would suggest many repetitions; this is a judgement call open to correction. `CV-SMALL-01` records the decision, and `CV-SMALL-07` defers other and else to the ordinary-vocabulary step. | +| D132 | Accepted | Count the structural readings of Phi sentences. | Step 1 of the November assessment's answer to its central finding (section 4.3, recommendations 3 and 6): measure the unmarked phrase boundaries before deciding whether to mark them. `scripts/phi_readings.py` extends the sentence parser to count, for every clause, the ways the words before the verb divide into subject, adjuncts, object or complement, and manner, and the places each adverbial or relative clause could end; readings multiply across a sentence's clauses, and quoted sentences count separately. It reports a conservative count, in which only nouns, pronouns, and names end a phrase freely, and a full count that also lets an event or quality noun head a phrase with its own modifiers. `scripts/audit_phrase_readings.py` runs it over the lexicon's examples and the active Markdown and can show one sentence's divisions; `--openers` is a what-if that treats the listed Slot 2 words as always opening a phrase. The counter has no verb valency or meanings, so the figure is an upper bound on structural choice and not a comprehension rate, and it does not see the role of a single bare phrase or pronoun reference, which is where the two verified misreadings in certified text fall. First measurement on 2026-11-24: 42 percent of sentences in the translations have more than one division on the conservative count and 66 percent on the full count; the primer has 22 and 34 percent. Treating `ha`, `ra`, and `lo` as phrase openers lowers the translations' conservative figure to 35 percent. About one adverbial clause in five and one relative clause in five has more than one grammatical end. No language rule changes. | +| D133 | Accepted | Count open roles and contested third persons, and track all three figures. | Two maintainer rulings on 2026-11-24 after the first reading count: measure roles and reference next, and track the figure. The reading count does not see the two kinds of misreading verified in certified text, a single bare phrase taken as object where subject was meant and a `shia` assigned to the wrong referent. `scripts/phi_roles.py` counts both exposures. An open role is a clause, or a relative clause, with one bare phrase and a verb that takes an object elsewhere; the lexicon has no valency field, so a verb counts as taking an object when the corpus shows it in the passive, with two bare phrases that cannot be read as one, or in a command over a noun phrase, in a clause with a single structural reading (154 verbs on first measurement). A contested third person is a `shia` or an unsaid subject while two or more third persons are live, a third person being the noun or name heading a clause-initial bare phrase within the last three sentences; clauses with two separate `shia` are counted too. First measurement: in the translations 5 percent of clauses have an open role (197, of which 124 are not `mia` or `thia`), a third of the 1,102 uses of `shia` are contested, and 38 clauses hold two `shia`, 25 of them in *The Velveteen Rabbit*; both verified misreadings fall in clauses the counts flag. `documents/validation/phrase_readings_baseline.txt` records one row per file for all three measures, CI checks it, and the working rules name the regeneration command. The figures use no meanings and are upper bounds on exposure; a corpus-derived valency is a stopgap for the valency field the assessment recommends. No language rule changes. | ## Completed discretionary lexical migrations diff --git a/project/handoff/repository_workflow.md b/project/handoff/repository_workflow.md index f71c918e..b8137a86 100644 --- a/project/handoff/repository_workflow.md +++ b/project/handoff/repository_workflow.md @@ -103,6 +103,7 @@ python3 scripts/validate_sentences.py --paths texts/example.md python3 scripts/validate_sentences.py --docs python3 scripts/validate_sentences.py --paths texts/example.md --lint python3 scripts/audit_sentence_order.py --output documents/validation/sentence_order_baseline.txt +python3 scripts/audit_phrase_readings.py --output documents/validation/phrase_readings_baseline.txt ``` The full active Markdown scan remains a migration command because the evaluation corpus predates the parser. As of D113, `--docs` parses 5,532 complete examples and reports two diagnostics in `documents/evaluation/narrative_test_corpus.md`: PHS103 at line 46 and PHS115 at line 212. Triage each as parser or corpus before editing it. The parser's boundary and diagnostic contract are in `documents/validation/sentence_validator.md`. diff --git a/scripts/README.md b/scripts/README.md index 759d6170..8f7dae4f 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -119,6 +119,20 @@ python3 scripts/audit_phonetic_neighbors.py --candidate proposed_word python3 scripts/audit_phonetic_neighbors.py --kind function --prompts 40 --seed 202601 ``` +## audit_phrase_readings.py + +Measures where sentences leave structure to the listener, over the lexicon's examples and the active Markdown. `phi_readings.py` counts the ways each clause divides into subject, adjuncts, object, and manner, and the places each dependent clause could end. `phi_roles.py` counts clauses whose one bare phrase may be subject or object, and uses of `shia` while two or more third persons are live. The report gives tables by corpus and by text; the committed ledger, which CI checks, gives one row per file. None of the counts uses meanings, so each is an upper bound. `documents/validation/sentence_validator.md` describes the models and their limits. + +```bash +python3 scripts/audit_phrase_readings.py +python3 scripts/audit_phrase_readings.py --sentence "phao lopia shelu theo." +python3 scripts/audit_phrase_readings.py --openers ha ra lo +python3 scripts/audit_phrase_readings.py --output documents/validation/phrase_readings_baseline.txt +python3 scripts/audit_phrase_readings.py --check +python3 scripts/test_phi_readings.py +python3 scripts/test_phi_roles.py +``` + ## audit_sentence_order.py Lists every sentence in the lexicon and the active Markdown that parses and still has a reading under which canon's order is broken: a manner word outside the Slot 1 block (`PHL001`), a direct object before a prepositional phrase (`PHL002`), a period before `sho` (`PHL003`), an adjunct before the subject (`PHL004`), or a past `lu` condition with no habit marked (`PHL005`). The parser has no verb valency and cannot choose between the readings, so the list is for a person. CI regenerates the committed ledger and fails on any difference. diff --git a/scripts/audit_phrase_readings.py b/scripts/audit_phrase_readings.py new file mode 100644 index 00000000..8b0ca679 --- /dev/null +++ b/scripts/audit_phrase_readings.py @@ -0,0 +1,426 @@ +#!/usr/bin/env python3 +"""Report where Phi's sentences leave structure to the listener. + +Every sentence in the lexicon's examples and the active Markdown is parsed +and measured three ways. + +* **Readings** (``phi_readings``): the ways each clause divides into subject, + adjuncts, object, and manner, and the places each dependent clause could + end. The conservative count lets only nouns, pronouns, and names end a + phrase freely; the full count also lets an event or quality noun head a + phrase with modifiers of its own. +* **Open roles** (``phi_roles``): clauses whose one bare phrase may be + subject or object, because the verb takes an object elsewhere. +* **Third persons** (``phi_roles``): uses of ``shia``, and unsaid subjects, + while two or more third persons are live in the text. + +None of the counts uses meanings, so each is an upper bound on what the +grammar leaves open. None is a rate of misunderstanding. + +The committed ledger records one row per file. Continuous integration +regenerates it and fails on any difference, so a change in a text shows up +as a changed row. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from dataclasses import dataclass, field +import json +from pathlib import Path +import sys + +from phi_readings import ReadingCounter, SentenceReadings +from phi_roles import ( + ReferenceCounts, + ReferenceTracker, + object_taking_verbs, + open_role, + settled, +) +from phi_sentence_validator import Lexicon, PROJECT_ROOT +import validate_sentences + +LEDGER = PROJECT_ROOT / "documents" / "validation" / "phrase_readings_baseline.txt" + +GROUP_ORDER = ( + "Translations", + "Original compositions", + "Manual", + "Pamphlets", + "Primer", + "Book", + "Dictionary examples", + "Other documents", +) +PREFIX_GROUPS = ( + ("manual/", "Manual"), + ("pamphlets/", "Pamphlets"), + ("primer/", "Primer"), + ("book/", "Book"), + ("vocabulary/", "Dictionary examples"), +) + +LEDGER_HEADER = """\ +# Phrase-reading ledger +# +# Generated by scripts/audit_phrase_readings.py. Do not edit by hand. +# One row per file; every dictionary example is gathered under vocabulary/. +# The counts are upper bounds on what the grammar leaves open. They use no +# meanings and are not rates of misunderstanding. +# +# sentences sentences parsed (each quoted sentence counts as one) +# divided sentences with more than one division into phrases, counting +# only nouns, pronouns, and names as free phrase ends +# full the same, also letting an event or quality noun head a phrase +# roles clauses whose one bare phrase may be subject or object +# relroles relative clauses whose head may be subject or object +# shia uses of shia +# contested uses of shia while two or more third persons are live +# doubled clauses with two separate shia +# +# Columns: file, sentences, divided, full, roles, relroles, shia, contested, doubled. +""" + + +@dataclass +class Row: + path: str + sentence: SentenceReadings + roles: list[str] = field(default_factory=list) + role_verbs: list[str] = field(default_factory=list) + # Open roles whose phrase is not headed by mia or thia. + third_person_roles: int = 0 + reference: ReferenceCounts = field(default_factory=ReferenceCounts) + + +def original_works() -> frozenset[str]: + catalogue = json.loads((PROJECT_ROOT / "texts" / "catalogue.json").read_text(encoding="utf-8")) + return frozenset( + "texts/" + work["path"] + for work in catalogue.get("works", []) + if work.get("method", "").lower().startswith("original") + ) + + +def group_of(path: str, originals: frozenset[str]) -> str: + if path.startswith("texts/"): + return "Original compositions" if path in originals else "Translations" + for prefix, name in PREFIX_GROUPS: + if path.startswith(prefix): + return name + return "Other documents" + + +def collect(openers: frozenset[str] = frozenset()) -> tuple[list[Row], Counter[str]]: + """Measure the whole corpus, in document order.""" + lexicon = Lexicon.load() + counter = ReadingCounter(lexicon, openers=openers) + sources = list(validate_sentences.iter_lexicon_examples(PROJECT_ROOT)) + sources.extend( + validate_sentences.iter_markdown_examples( + PROJECT_ROOT, lexicon, validate_sentences.ACTIVE_DOC_ROOTS + ) + ) + seen = set() + rows: list[Row] = [] + for source in sources: + path = source.label.split(":", 1)[0] + parts = counter.analyse_sentences(source.text, allow_fragments=source.allow_fragments) + if parts is None: + continue + for part in parts: + key = (path, part.text) + if key in seen: + continue + seen.add(key) + rows.append(Row(path, part)) + + verbs = object_taking_verbs(row.sentence for row in rows) + tracker = ReferenceTracker() + current = None + for row in rows: + # Where a dependent clause has several possible ends, the clauses of + # every alternative are on record, so roles are counted only where + # the clause structure is settled. + if settled(row.sentence): + for clause in row.sentence.clauses: + kind = open_role(clause, verbs) + if kind: + row.roles.append(kind) + row.role_verbs.append(clause.verb) + if kind == "main" and clause.bare_heads[0][1] not in {"mia", "thia"}: + row.third_person_roles += 1 + if row.path.startswith("vocabulary/"): + continue + if row.path != current: + tracker.reset() + current = row.path + row.reference = tracker.observe(row.sentence) + return rows, verbs + + +def percent(part: int, whole: int) -> str: + return f"{100 * part / whole:.0f}%" if whole else "-" + + +def ledger_key(path: str) -> str: + return "vocabulary/" if path.startswith("vocabulary/") else path + + +def render_ledger(rows: list[Row]) -> str: + by_file: dict[str, list[Row]] = defaultdict(list) + for row in rows: + by_file[ledger_key(row.path)].append(row) + lines = [LEDGER_HEADER] + for path in sorted(by_file): + group = by_file[path] + lines.append( + "\t".join( + str(value) + for value in ( + path, + len(group), + sum(1 for r in group if r.sentence.conservative > 1), + sum(1 for r in group if r.sentence.full > 1), + sum(r.roles.count("main") for r in group), + sum(r.roles.count("relative") for r in group), + sum(r.reference.third_person_pronouns for r in group), + sum(r.reference.contested_pronouns for r in group), + sum(r.reference.doubled_clauses for r in group), + ) + ) + ) + return "\n".join(lines) + "\n" + + +def render_report(rows: list[Row], verbs: Counter[str], top: int) -> str: + originals = original_works() + by_group: dict[str, list[Row]] = defaultdict(list) + by_file: dict[str, list[Row]] = defaultdict(list) + for row in rows: + by_group[group_of(row.path, originals)].append(row) + by_file[row.path].append(row) + + lines = ["# Phrase-reading audit", "", "## Readings", ""] + lines += [ + "| Corpus | Sentences | More than one reading | Four or more | " + "More than one, full count | Outside canonical order | Not modelled |", + "|---|---:|---:|---:|---:|---:|---:|", + ] + for name in GROUP_ORDER: + group = by_group.get(name) + if not group: + continue + total = len(group) + many = sum(1 for r in group if r.sentence.conservative > 1) + four = sum(1 for r in group if r.sentence.conservative >= 4) + wide = sum(1 for r in group if r.sentence.full > 1) + relaxed = sum(1 for r in group if any(c.relaxed for c in r.sentence.clauses)) + missed = sum(1 for r in group if r.sentence.unmodelled) + lines.append( + f"| {name} | {total} | {many} ({percent(many, total)}) | " + f"{four} ({percent(four, total)}) | {wide} ({percent(wide, total)}) | " + f"{relaxed} ({percent(relaxed, total)}) | {missed} ({percent(missed, total)}) |" + ) + + seam_counts: Counter[str] = Counter() + divided_clauses = 0 + join_open: Counter[str] = Counter() + join_total: Counter[str] = Counter() + for row in rows: + for clause in row.sentence.clauses: + if clause.conservative > 1 and clause.seams: + divided_clauses += 1 + seam_counts.update(clause.seams) + for join in row.sentence.joins: + join_total[join.kind] += 1 + if join.alternatives > 1: + join_open[join.kind] += 1 + lines += [ + "", + f"Clauses with more than one division, conservative count: {divided_clauses}. " + "A clause may show several kinds of seam.", + "", + "| Kind of seam | Clauses |", + "|---|---:|", + ] + for kind, count in seam_counts.most_common(): + lines.append(f"| {kind} | {count} |") + lines += ["", "| Dependent clause | With more than one possible end | Of |", "|---|---:|---:|"] + for kind in ("adverbial", "relative"): + lines.append(f"| {kind} | {join_open[kind]} | {join_total[kind]} |") + + lines += [ + "", + "## Open roles", + "", + f"Verbs the corpus shows with an object: {len(verbs)}.", + "", + "| Corpus | Clauses | One bare phrase, subject or object | " + "Of which not `mia` or `thia` | Relative clauses, head subject or object | " + "Sentences with either |", + "|---|---:|---:|---:|---:|---:|", + ] + role_verbs: Counter[str] = Counter() + for name in GROUP_ORDER: + group = by_group.get(name) + if not group: + continue + clauses = sum(len(r.sentence.clauses) for r in group) + main = sum(r.roles.count("main") for r in group) + relative = sum(r.roles.count("relative") for r in group) + either = sum(1 for r in group if r.roles) + third = sum(r.third_person_roles for r in group) + for r in group: + role_verbs.update(r.role_verbs) + lines.append( + f"| {name} | {clauses} | {main} ({percent(main, clauses)}) | {third} | {relative} | " + f"{either} ({percent(either, len(group))} of sentences) |" + ) + lines += [ + "", + "Verbs most often found with an open role: " + + ", ".join(f"`{verb}` ({count})" for verb, count in role_verbs.most_common(15)) + + ".", + ] + + lines += [ + "", + "## Third persons", + "", + "| Corpus | Uses of `shia` | While two or more third persons are live | " + "Clauses with two `shia` | Unsaid subjects | Unsaid while two or more are live |", + "|---|---:|---:|---:|---:|---:|", + ] + for name in GROUP_ORDER: + group = by_group.get(name) + if not group or name == "Dictionary examples": + continue + uses = sum(r.reference.third_person_pronouns for r in group) + contested = sum(r.reference.contested_pronouns for r in group) + doubled = sum(r.reference.doubled_clauses for r in group) + unsaid = sum(r.reference.unsaid_subjects for r in group) + unsaid_contested = sum(r.reference.contested_unsaid for r in group) + lines.append( + f"| {name} | {uses} | {contested} ({percent(contested, uses)}) | {doubled} | " + f"{unsaid} | {unsaid_contested} ({percent(unsaid_contested, unsaid)}) |" + ) + + lines += [ + "", + "## By text", + "", + "| File | Sentences | More than one reading | Full count | Open roles | " + "`shia` | Contested | Two `shia` in a clause |", + "|---|---:|---:|---:|---:|---:|---:|---:|", + ] + for path in sorted(by_file): + if not path.startswith("texts/"): + continue + group = by_file[path] + total = len(group) + many = sum(1 for r in group if r.sentence.conservative > 1) + wide = sum(1 for r in group if r.sentence.full > 1) + roles = sum(len(r.roles) for r in group) + uses = sum(r.reference.third_person_pronouns for r in group) + contested = sum(r.reference.contested_pronouns for r in group) + doubled = sum(r.reference.doubled_clauses for r in group) + lines.append( + f"| `{path}` | {total} | {many} ({percent(many, total)}) | " + f"{wide} ({percent(wide, total)}) | {roles} | {uses} | " + f"{contested} ({percent(contested, uses)}) | {doubled} |" + ) + + lines += ["", f"## The {top} sentences with the most readings", ""] + ranked = sorted(rows, key=lambda r: (-r.sentence.conservative, r.path, r.sentence.text)) + for row in ranked[:top]: + lines.append( + f"- {row.sentence.conservative} readings, `{row.path}`: `{row.sentence.text}`" + ) + return "\n".join(lines) + "\n" + + +def show_sentence(text: str, openers: frozenset[str]) -> int: + counter = ReadingCounter(openers=openers) + parts = counter.analyse_sentences(text) + if parts is None: + print("The sentence does not parse.") + return 1 + for part in parts: + print(f"{part.text}") + print(f" readings: {part.conservative} conservative, {part.full} full") + for join in part.joins: + print( + f" {join.kind} clause opened by '{join.opener}': " + f"{join.alternatives} possible end(s)" + ) + for clause in part.clauses: + if clause.conservative < 2: + continue + print(f" clause: {clause.text}") + for division in clause.divisions: + print(f" {division}") + if clause.seams: + print(f" open seams: {', '.join(clause.seams)}") + return 0 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--sentence", help="count one literal Phi sentence and show its divisions") + parser.add_argument("--paths", nargs="+", help="limit the report to files under these paths") + parser.add_argument("--report", type=Path, help="write the Markdown report here") + parser.add_argument("--output", type=Path, help="write the per-file ledger here") + parser.add_argument( + "--check", action="store_true", help="fail when the committed ledger is stale" + ) + parser.add_argument("--top", type=int, default=20, help="how many sentences to list") + parser.add_argument( + "--openers", + nargs="+", + default=[], + help="what-if: count as though these Slot 2 words always began a new phrase", + ) + args = parser.parse_args() + openers = frozenset(args.openers) + + if args.sentence is not None: + return show_sentence(args.sentence, openers) + + rows, verbs = collect(openers) + if args.check or args.output: + if openers: + print("the ledger records the language as it is; drop --openers") + return 2 + ledger = render_ledger(rows) + if args.check: + current = LEDGER.read_text(encoding="utf-8") if LEDGER.is_file() else "" + if current != ledger: + print( + "phrase-reading ledger is stale; run " + "python3 scripts/audit_phrase_readings.py --output " + "documents/validation/phrase_readings_baseline.txt" + ) + return 1 + print("phrase-reading ledger is current.") + return 0 + args.output.write_text(ledger, encoding="utf-8") + files = len(ledger.splitlines()) - len(LEDGER_HEADER.splitlines()) + print(f"wrote {args.output}: {files} file(s)") + return 0 + + if args.paths: + rows = [row for row in rows if any(row.path.startswith(path) for path in args.paths)] + report = render_report(rows, verbs, args.top) + if args.report: + args.report.write_text(report, encoding="utf-8") + print(f"wrote {args.report}") + else: + sys.stdout.write(report) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/phi_readings.py b/scripts/phi_readings.py new file mode 100644 index 00000000..cb38e956 --- /dev/null +++ b/scripts/phi_readings.py @@ -0,0 +1,920 @@ +#!/usr/bin/env python3 +"""Count the structural readings of a Phi sentence. + +``phi_sentence_validator`` accepts a sentence when one canonical parse +exists. This module asks the next question: how many are there? Phi marks +the edges of embedded statements, questions, and quotations with words, and +leaves the commoner edges unmarked: where the subject ends and the object +begins, where a prepositional phrase ends, whether a quality word before the +verb is its manner or its object, and where an adverbial or relative clause +hands over to the clause around it. + +A reading here is one way of dividing a clause's words into phrases. For +each core clause the counter takes the words before the Slot 1 stack (or +before the verb when the clause has no stack) and enumerates every division +into phrases that canon's clause order allows: + + [subject] [adjuncts] [object or complement] | Slot 1 | manner | verb + +It adds the places where a dependent clause could end, using the parser +itself to decide which splits are grammatical. Readings multiply across the +clauses of one sentence. + +What the count does not do: + +* It has no verb valency and no meanings, so it cannot discard a reading + that is grammatical and absurd. ``mia nosa thole`` counts two divisions, + "I practice now" and "my now practices". The figure is an upper bound on + structural choice, never an estimate of how often a reader is confused. +* It does not count bracketing inside a phrase. ``phao lopia shelu`` as one + phrase is one reading, whichever noun owns which. +* It follows the parser's own choice for clause coordination. + +Two strictness levels are reported. The conservative count lets a noun, +pronoun, or name end a phrase anywhere, and lets an adjective or verb stand +as a phrase by itself only where nothing else can end the phrase. The full +count also lets an adjective (quality noun) or a verb (event noun) head a +phrase with its own modifiers, as in ``thia shua`` (your coming). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Iterator, Sequence + +from phi_sentence_validator import ( + ADVERBIAL_RELATORS, + CLAUSAL_PREPOSITIONS, + COORDINATORS, + DISCOURSE_MARKERS, + Lexicon, + NOMINAL_RELATORS, + NUMERAL_DIGITS, + NUMERAL_SCALES, + PREDICATIVE_VERBS, + PhiParser, + SLOT2_DEGREE, + SLOT2_OUTER, + SLOT2_WORDS, + SyntaxNode, + TEMPORAL_NP_RELATORS, +) + +ADJUNCT_INTERROGATIVES = frozenset({"misa", "weno", "kua", "thela"}) +# Nouns that stand as bare time adjuncts between subject and object. The +# parser's own temporal set is every noun with a temporal domain, which +# includes child, elder, seed, and festival; a bare adjunct needs a narrower +# test, so these are chosen by gloss. +TIME_ADJUNCT_GLOSSES = frozenset( + { + "now", "moment", "time", "instant", "period", "past", "present", "future", + "day", "week", "month", "season", "year", "generation", + "dawn", "morning", "midday", "afternoon", "evening", "dusk", "night", "midnight", + "spring", "summer", "autumn", "winter", + } +) +NAME_MARKERS = frozenset({"ne", "sa", "ni", "le"}) + +# A clause this long is not enumerated. Nothing in the corpus comes close. +MAX_UNITS = 22 +MAX_SHOWN = 12 + + +@dataclass(frozen=True) +class Unit: + """One top-level item before the verb: a word, a frame, or a relative clause.""" + + cls: str + start: int + end: int + word: str + temporal: bool = False + inner: tuple[int, int] = (1, 1) + + +@dataclass +class ClauseReadings: + """The divisions of one core clause.""" + + start: int + end: int + text: str + conservative: int + full: int + relaxed: bool + divisions: list[str] = field(default_factory=list) + seams: list[str] = field(default_factory=list) + # Facts the role and reference counts need. + verb: str = "" + slot0: tuple[str, ...] = () + slot1: tuple[str, ...] = () + gapped: bool = False + # How many bare phrases (subject, object, complement) each division has. + bare_counts: tuple[int, ...] = () + # The head of the first phrase when it is bare: (class, word). + first_bare: tuple[str, str] | None = None + # The head of every bare phrase in the first division. + bare_heads: tuple[tuple[str, str], ...] = () + # Third-person pronouns standing as separate words in the clause. + third_persons: int = 0 + + +@dataclass +class JoinReadings: + """The places where one dependent clause could end.""" + + kind: str + opener: str + start: int + alternatives: int + + +@dataclass +class SentenceReadings: + """Counts for one sentence, or for a condition with its consequence.""" + + text: str + conservative: int + full: int + clauses: list[ClauseReadings] + joins: list[JoinReadings] + unmodelled: bool = False + + @property + def ambiguous(self) -> bool: + return self.conservative > 1 + + +class ReadingCounter(PhiParser): + """A parser that also counts the readings of what it accepts. + + Internally every count is a pair, conservative and full. A full count of + zero means the span has no division under this model, which is how an + alternative the looser parser would accept gets discarded. + """ + + def __init__( + self, lexicon: Lexicon | None = None, *, openers: frozenset[str] = frozenset() + ): + """``openers`` is a what-if: Slot 2 words assumed always to begin a phrase. + + Canon lets a possessor stand before a phrase that opens with ``ha`` or + ``lo`` (``lo mia lo manuwe``, our hands). Passing those words here + counts the readings that would remain if such a word always began a + new phrase. + """ + super().__init__(lexicon) + self.openers = openers + self.time_heads = frozenset( + word + for word, entry in self.lexicon.entries.items() + if entry.pos == "noun" and entry.gloss.split(" (")[0] in TIME_ADJUNCT_GLOSSES + ) + self._clauses: list[ClauseReadings] = [] + self._joins: list[JoinReadings] = [] + self._quoted: dict[tuple[int, int], SentenceReadings] = {} + self._unmodelled = False + + # ------------------------------------------------------------------ + # Entry points + # ------------------------------------------------------------------ + + def analyse(self, text: str, *, allow_fragments: bool = False) -> SentenceReadings | None: + """Counts for a whole passage, or None if it does not parse.""" + parts = self.analyse_sentences(text, allow_fragments=allow_fragments) + if parts is None: + return None + conservative, full = 1, 1 + clauses: list[ClauseReadings] = [] + joins: list[JoinReadings] = [] + for part in parts: + conservative *= part.conservative + full *= part.full + clauses.extend(part.clauses) + joins.extend(part.joins) + return SentenceReadings( + text, conservative, full, clauses, joins, any(part.unmodelled for part in parts) + ) + + def analyse_sentences( + self, text: str, *, allow_fragments: bool = False + ) -> list[SentenceReadings] | None: + """Counts for each sentence of a passage, or None if it does not parse. + + A ``lu`` condition and its consequence count as one sentence. Each + sentence inside a quotation counts as a sentence of its own. + """ + result = self.parse(text, allow_fragments=allow_fragments) + if not result.ok or result.tree is None: + return None + parts = [] + for node in result.tree.children: + self._clauses = [] + self._joins = [] + self._quoted = {} + self._unmodelled = False + cons, wide = self._floor(self._count_node(node)) + words = self._sentence_text(node.start, node.end) + parts.append( + SentenceReadings(words, cons, wide, self._clauses, self._joins, self._unmodelled) + ) + parts.extend(self._quoted[key] for key in sorted(self._quoted)) + del self.diagnostics[:] + return parts + + def _floor(self, counts: tuple[int, int]) -> tuple[int, int]: + """A sentence the parser accepted has at least one reading.""" + if counts[1] == 0: + self._unmodelled = True + return 1, 1 + return counts + + def _sentence_text(self, start: int, end: int) -> str: + """The words of a sentence, with the content of each quotation elided.""" + words = [] + index = start + while index < end: + word = self._word(index) + words.append(word) + closer = self.frame_close.get(index) + if word == "sha" and closer is not None and closer < end: + words.append("...") + index = closer + continue + index += 1 + return " ".join(words).replace(" .", ".") + "." + + def _count_node(self, node: SyntaxNode) -> tuple[int, int]: + if node.kind in {"realis-conditional", "irrealis-conditional"}: + cons, wide = 1, 1 + for child in node.children: + c, w = self._count_node(child) + cons *= c + wide *= w + return cons, wide + if node.kind == "clause": + return self._count_clause(node.start, node.end, allow_gap=False) + return 1, 1 + + # ------------------------------------------------------------------ + # Records that can be withdrawn when an alternative proves illegal + # ------------------------------------------------------------------ + + def _mark(self) -> tuple[int, int]: + return len(self._clauses), len(self._joins) + + def _rollback(self, mark: tuple[int, int]) -> None: + del self._clauses[mark[0] :] + del self._joins[mark[1] :] + + def _record_join(self, kind: str, opener: str, start: int, alternatives: int) -> None: + if not any(join.kind == kind and join.start == start for join in self._joins): + self._joins.append(JoinReadings(kind, opener, start, alternatives)) + + # ------------------------------------------------------------------ + # Clauses and their joins + # ------------------------------------------------------------------ + + def _parses(self, start: int, end: int, *, allow_gap: bool) -> bool: + checkpoint = len(self.diagnostics) + self._parse_clause(start, end, allow_gap=allow_gap) + ok = len(self.diagnostics) == checkpoint + del self.diagnostics[checkpoint:] + return ok + + def _core_parses(self, start: int, end: int, allow_gap: bool) -> bool: + checkpoint = len(self.diagnostics) + self._parse_core_clause(start, end, allow_gap=allow_gap) + ok = len(self.diagnostics) == checkpoint + del self.diagnostics[checkpoint:] + return ok + + def _count_clause(self, start: int, end: int, *, allow_gap: bool) -> tuple[int, int]: + checkpoint = len(self.diagnostics) + index, frame_nodes = self._parse_sentence_frame(start, end) + del self.diagnostics[checkpoint:] + slot0 = tuple(node.value for node in frame_nodes if node.value) + if index < end and self._word(index) in DISCOURSE_MARKERS: + index += 1 + if index >= end: + return 1, 1 + if index + 1 == end and self._word(index) in self.lexicon.interjections: + return 1, 1 + + checkpoint = len(self.diagnostics) + coordinate = self._try_clause_coordination(index, end, allow_gap) + del self.diagnostics[checkpoint:] + if coordinate is not None and len(coordinate.children) == 2: + left, right = coordinate.children + lc, lw = self._count_clause(left.start, left.end, allow_gap=allow_gap) + rc, rw = self._count_clause(right.start, right.end, allow_gap=allow_gap) + return lc * rc, lw * rw + + opener = self._word(index) + if opener in ADVERBIAL_RELATORS or opener in CLAUSAL_PREPOSITIONS: + counted = self._count_adverbial(index, end, allow_gap) + if counted is not None: + return counted + return self._count_core(index, end, allow_gap=allow_gap, slot0=slot0) + + def _count_adverbial( + self, start: int, end: int, allow_gap: bool + ) -> tuple[int, int] | None: + """Sum over every place the dependent material could end.""" + relator = self._word(start) + cons_total, wide_total = 0, 0 + alternatives = 0 + parser_alternatives = 0 + for split in self._candidate_clause_ends(start + 1, end): + if split >= end: + continue + if not self._parses(start + 1, split, allow_gap=False): + continue + if not self._parses(split, end, allow_gap=allow_gap): + continue + parser_alternatives += 1 + mark = self._mark() + dc, dw = self._count_clause(start + 1, split, allow_gap=False) + mc, mw = self._count_clause(split, end, allow_gap=allow_gap) + if dw == 0 or mw == 0: + self._rollback(mark) + continue + cons_total += dc * mc + wide_total += dw * mw + alternatives += 1 + if relator in TEMPORAL_NP_RELATORS | NOMINAL_RELATORS: + needs_time = relator in TEMPORAL_NP_RELATORS + for split in range(start + 2, end): + if not self._valid_nominal_span(start + 1, split): + continue + if needs_time and not self._is_time_phrase(self._words(start + 1, split)): + continue + if not self._parses(split, end, allow_gap=allow_gap): + continue + parser_alternatives += 1 + if not self._is_noun_phrase(start + 1, split): + continue + mark = self._mark() + mc, mw = self._count_clause(split, end, allow_gap=allow_gap) + if mw == 0: + self._rollback(mark) + continue + cons_total += mc + wide_total += mw + alternatives += 1 + if parser_alternatives == 0: + return None + if relator in CLAUSAL_PREPOSITIONS and self._core_parses(start, end, allow_gap): + # tei is still a preposition, so the whole span may also be one + # clause that opens with a prepositional phrase. + core_c, core_w = self._count_core(start, end, allow_gap=allow_gap, record=False) + if core_w: + cons_total += core_c + wide_total += core_w + alternatives += 1 + if alternatives: + self._record_join("adverbial", relator, start, alternatives) + return cons_total, wide_total + + def _is_noun_phrase(self, start: int, end: int) -> bool: + """Whether the span is one noun phrase under the full count.""" + for units, _, inner_w in self._unit_sequences(start, end): + if inner_w and units and self._noun_phrase(units, 0, len(units), None, True): + return True + return False + + # ------------------------------------------------------------------ + # The core clause + # ------------------------------------------------------------------ + + def _count_core( + self, + start: int, + end: int, + *, + allow_gap: bool, + record: bool = True, + slot0: tuple[str, ...] = (), + ) -> tuple[int, int]: + predicate_index = end - 1 + if predicate_index < start: + return 1, 1 + cons_total, wide_total = 0, 0 + relaxed_used = False + shown: list[str] = [] + seams: set[str] = set() + bare_counts: set[int] = set() + first_bare: tuple[str, str] | None = None + bare_heads: tuple[tuple[str, str], ...] | None = None + slot1: tuple[str, ...] = () + third_persons = 0 + mark = self._mark() + for units, inner_c, inner_w in self._unit_sequences(start, predicate_index): + if inner_w == 0: + continue + pre, manner_ok = self._preverbal(units, predicate_index) + if len(pre) > MAX_UNITS: + cons_total += inner_c + wide_total += inner_w + continue + has_ka = any(u.cls == "S1" and u.word == "ka" for u in units) + predicative = self._word(predicate_index) in PREDICATIVE_VERBS + counts = {} + for full in (False, True): + found = self._divisions( + pre, manner_ok, has_ka, predicative, allow_gap, full, relaxed=False + ) + if not found: + found = self._divisions( + pre, manner_ok, has_ka, predicative, allow_gap, full, relaxed=True + ) + if found and full: + relaxed_used = True + counts[full] = found + cons, wide = counts[False], counts[True] + if not wide and not cons: + continue + # A clause that divides only when an event or quality noun heads + # a phrase still has that one reading on the conservative count. + cons_total += max(len(cons), 1) * inner_c + wide_total += max(len(wide), len(cons)) * inner_w + if len(cons) > 1: + seams.update(self._seam_types(pre, cons)) + for division in cons: + if len(shown) < MAX_SHOWN: + shown.append(self._render(pre, division)) + slot1 = tuple(u.word for u in units if u.cls == "S1") + third_persons = max( + third_persons, + sum(1 for u in pre if u.cls == "PRON" and u.word == "shia"), + ) + for boundaries, _, types in cons or wide: + bare_counts.add(sum(1 for kind in types if kind == "BARE")) + if first_bare is None and types and types[0] == "BARE": + head = pre[boundaries[0] - 1] + first_bare = (head.cls, head.word) + if bare_heads is None: + bare_heads = tuple( + (pre[stop - 1].cls, pre[stop - 1].word) + for stop, kind in zip(boundaries, types) + if kind == "BARE" + ) + if wide_total == 0: + self._rollback(mark) + return 0, 0 + if record and not any( + clause.start == start and clause.end == end for clause in self._clauses + ): + self._clauses.append( + ClauseReadings( + start, + end, + " ".join(self._words(start, end)), + cons_total, + wide_total, + relaxed_used, + shown if cons_total > 1 else [], + sorted(seams), + verb=self._word(predicate_index), + slot0=slot0, + slot1=slot1, + gapped=allow_gap, + bare_counts=tuple(sorted(bare_counts)), + first_bare=first_bare, + bare_heads=bare_heads or (), + third_persons=third_persons, + ) + ) + return cons_total, wide_total + + def _unit_sequences( + self, start: int, stop: int + ) -> Iterator[tuple[list[Unit], int, int]]: + """Every way to cut the words in [start, stop) into top-level units. + + Complement frames are single units. A relative clause may end at more + than one verb, so each ``whu`` yields one sequence per legal end. + """ + + def walk(index: int) -> Iterator[tuple[list[Unit], int, int]]: + if index >= stop: + yield [], 1, 1 + return + word = self._word(index) + closer = self.frame_close.get(index) + if closer is not None and closer < stop + 1: + if word == "sha": + inner = self._count_quotation(index + 1, closer) + else: + inner = self._floor(self._count_sequence(index + 1, closer)) + unit = Unit("FRAME", index, closer + 1, word) + for rest, c, w in walk(closer + 1): + yield [unit, *rest], c * inner[0], w * inner[1] + return + if word == "whu": + ends = [] + parser_ends = [] + for clause_end in self._candidate_clause_ends(index + 1, stop + 1): + if clause_end > stop: + continue + if not self._parses(index + 1, clause_end, allow_gap=True): + continue + parser_ends.append(clause_end) + mark = self._mark() + inner = self._count_clause(index + 1, clause_end, allow_gap=True) + if inner[1] == 0: + self._rollback(mark) + continue + ends.append((clause_end, inner)) + if not ends and parser_ends: + self._unmodelled = True + ends = [(parser_ends[-1], (1, 1))] + if ends: + self._record_join("relative", "whu", index, len(ends)) + for clause_end, inner in ends: + unit = Unit("REL", index, clause_end, "whu") + for rest, c, w in walk(clause_end): + yield [unit, *rest], c * inner[0], w * inner[1] + return + unit = self._classify(index) + for rest, c, w in walk(index + 1): + yield [unit, *rest], c, w + + yield from walk(start) + + def _count_quotation(self, start: int, end: int) -> tuple[int, int]: + """Count each quoted sentence as a sentence of its own. + + A speech of ten sentences inside one ``sha ... sho`` frame is ten + sentences for a listener, so its readings are reported one by one and + do not multiply into the sentence that frames it. + """ + checkpoint = len(self.diagnostics) + ranges = self._root_sentence_ranges(start, end) + del self.diagnostics[checkpoint:] + position = 0 + while position < len(ranges): + first_start, last_end = ranges[position] + step = 1 + if self._word(first_start) == "lu" and position + 1 < len(ranges): + last_end = ranges[position + 1][1] + step = 2 + key = (first_start, last_end) + if key not in self._quoted: + saved = (self._clauses, self._joins, self._unmodelled) + self._clauses, self._joins, self._unmodelled = [], [], False + cons, wide = self._floor(self._count_sequence(first_start, last_end)) + self._quoted[key] = SentenceReadings( + self._sentence_text(first_start, last_end), + cons, + wide, + self._clauses, + self._joins, + self._unmodelled, + ) + self._clauses, self._joins, self._unmodelled = saved + position += step + return 1, 1 + + def _count_sequence(self, start: int, end: int) -> tuple[int, int]: + """Readings of the sentences inside a complement frame.""" + cons, wide = 1, 1 + checkpoint = len(self.diagnostics) + ranges = self._root_sentence_ranges(start, end) + del self.diagnostics[checkpoint:] + for sentence_start, sentence_end in ranges: + index = sentence_start + if self._word(index) == "lu": + index += 1 + if index < sentence_end and self._word(index) == "he": + index += 1 + if self._parses(index, sentence_end, allow_gap=False): + c, w = self._count_clause(index, sentence_end, allow_gap=False) + cons, wide = cons * c, wide * w + return cons, wide + + def _classify(self, index: int) -> Unit: + word = self._word(index) + lexicon = self.lexicon + pos = lexicon.pos(word) + + def unit(cls: str, temporal: bool = False) -> Unit: + return Unit(cls, index, index + 1, word, temporal) + + if index in self.name_atoms: + return unit("NAME") + if word in lexicon.slot1_words: + return unit("S1") + if word in NAME_MARKERS or word in SLOT2_WORDS: + return unit("S2") + if word in TEMPORAL_NP_RELATORS: + return unit("RELT") + if word in lexicon.prepositions or word == "lila": + return unit("PREP") + if word in COORDINATORS: + return unit("COORD") + if word in lexicon.pronouns: + return unit("PRON") + if word in ADJUNCT_INTERROGATIVES: + return unit("ADVQ") + if word == "sua": + return unit("PRON") + if ( + word in lexicon.quantifiers + or word in lexicon.classifiers + or word in NUMERAL_DIGITS + or word in NUMERAL_SCALES + or word == "wia" + or pos == "numeral" + ): + return unit("DET") + if pos == "noun" or word == "hina": + return unit("N", word in self.time_heads) + if pos == "adjective": + return unit("ADJ") + if pos == "verb": + return unit("V") + return unit("OTHER") + + def _preverbal( + self, units: Sequence[Unit], predicate_index: int + ) -> tuple[list[Unit], bool]: + """The units to divide, and whether a manner tail is possible. + + With a Slot 1 stack, only what stands before the stack is divided: + whatever follows it is manner by position. With no stack, an + adjective directly before the verb may be manner or object. + """ + stack = [position for position, u in enumerate(units) if u.cls == "S1"] + if stack: + pre = list(units[: stack[0]]) + manner_ok = False + else: + pre = list(units) + manner_ok = self._word(predicate_index) not in PREDICATIVE_VERBS + # we and li on the verb stand at the outer edge of the verb phrase, and + # a degree particle or ko directly before the verb belongs to the verb. + while pre and pre[-1].cls == "S2" and pre[-1].word in SLOT2_OUTER | SLOT2_DEGREE | {"ko"}: + pre.pop() + return pre, manner_ok + + # ------------------------------------------------------------------ + # Dividing the words before the verb + # ------------------------------------------------------------------ + + def _divisions( + self, + pre: Sequence[Unit], + manner_ok: bool, + has_ka: bool, + predicative: bool, + allow_gap: bool, + full: bool, + relaxed: bool, + ) -> list[tuple]: + """Every legal division, as (boundaries, manner_start, phrase_types).""" + results: list[tuple] = [] + # A manner tail is a run of adjectives, each with any degree + # particles, standing directly before the verb. A degree particle + # left behind at the end of the body fails the phrase check below. + tails = [len(pre)] + if manner_ok and pre and pre[-1].cls == "ADJ": + position = len(pre) + while position > 0 and ( + pre[position - 1].cls == "ADJ" + or (pre[position - 1].cls == "S2" and pre[position - 1].word in SLOT2_DEGREE) + ): + position -= 1 + tails.append(position) + for tail in sorted(set(tails)): + body = pre[:tail] + for boundaries, types in self._segmentations(body, allow_gap, full): + if self._template_ok(body, types, has_ka, predicative, relaxed): + results.append((boundaries, tail, types)) + return results + + def _segmentations( + self, body: Sequence[Unit], allow_gap: bool, full: bool + ) -> Iterator[tuple[tuple[int, ...], tuple[str, ...]]]: + count = len(body) + if count == 0: + yield (), () + return + + def walk(position: int) -> Iterator[tuple[tuple[int, ...], tuple[str, ...]]]: + if position == count: + yield (), () + return + for stop in range(position + 1, count + 1): + kind = self._phrase_type(body, position, stop, allow_gap, full) + if kind is None: + continue + for boundaries, types in walk(stop): + yield (stop, *boundaries), (kind, *types) + + yield from walk(0) + + def _phrase_type( + self, body: Sequence[Unit], start: int, stop: int, allow_gap: bool, full: bool + ) -> str | None: + following = body[stop] if stop < len(body) else None + # we, li, and ko may stand at the outer edge of a prepositional phrase. + while ( + start + 1 < stop + and body[start].cls == "S2" + and body[start].word in SLOT2_OUTER | {"ko"} + and body[start + 1].cls in {"PREP", "RELT", "S2"} + and any(unit.cls in {"PREP", "RELT"} for unit in body[start + 1 : stop]) + and all(unit.cls == "S2" for unit in body[start : self._first_opener(body, start, stop)]) + ): + start += 1 + first = body[start] + if first.cls == "ADVQ": + return "ADJUNCT" if stop == start + 1 else None + if first.cls == "OTHER": + return "ADJUNCT" if stop == start + 1 else None + if first.cls in {"PREP", "RELT"}: + # Two prepositional phrases joined by a coordinator are one adjunct. + for position in range(start + 1, stop - 1): + if body[position].cls == "COORD" and body[position + 1].cls in {"PREP", "RELT"}: + left = self._phrase_type(body[:position], start, position, allow_gap, full) + right = self._phrase_type(body, position + 1, stop, allow_gap, full) + return "ADJUNCT" if left == right == "ADJUNCT" else None + rest_start = start + 1 + if rest_start == stop: + return "ADJUNCT" if allow_gap else None + if stop == rest_start + 1 and body[rest_start].cls == "ADVQ": + return "ADJUNCT" + if body[rest_start].cls in {"PREP", "RELT"}: + inner = self._phrase_type(body, rest_start, stop, allow_gap, full) + return "ADJUNCT" if inner == "ADJUNCT" else None + head = self._noun_phrase(body, rest_start, stop, following, full) + if head is None: + return None + if first.cls == "RELT" and head != "TIME": + return None + return "ADJUNCT" + head = self._noun_phrase(body, start, stop, following, full) + if head is None: + return None + return "TIME" if head == "TIME" else "BARE" + + def _first_opener(self, body: Sequence[Unit], start: int, stop: int) -> int: + for position in range(start, stop): + if body[position].cls in {"PREP", "RELT"}: + return position + return stop + + def _noun_phrase( + self, + body: Sequence[Unit], + start: int, + stop: int, + following: Unit | None, + full: bool, + ) -> str | None: + """Whether body[start:stop] is one noun phrase; returns its head kind.""" + conjuncts: list[list[Unit]] = [[]] + for unit in body[start:stop]: + if unit.cls == "COORD": + conjuncts.append([]) + else: + conjuncts[-1].append(unit) + if any(not conjunct for conjunct in conjuncts): + return None + # Nothing can continue a noun phrase across these, so a quality word, + # an event noun, or a quantity word standing before one must be a head. + forced = following is None or following.cls in { + "PREP", "RELT", "ADVQ", "PRON", "FRAME", "OTHER", "S1" + } + head_kind = "NOUN" + for position, conjunct in enumerate(conjuncts): + last = conjunct[-1] + is_last_conjunct = position == len(conjuncts) - 1 + content = [u for u in conjunct if u.cls not in {"S2", "DET"}] + for offset, unit in enumerate(conjunct): + if unit.cls in {"PREP", "RELT", "ADVQ", "OTHER", "S1"}: + return None + if unit.cls == "FRAME" and any( + earlier.cls != "S2" for earlier in conjunct[:offset] + ): + return None + if unit.cls == "PRON" and any( + earlier.cls != "S2" for earlier in conjunct[:offset] + ): + return None + if ( + unit.cls == "S2" + and unit.word in self.openers + and any(earlier.cls != "S2" for earlier in conjunct[:offset]) + ): + return None + alone = len(content) <= 1 + edge_forced = forced if is_last_conjunct else True + if last.cls in {"N", "PRON", "NAME", "REL", "FRAME"}: + pass + elif last.cls in {"ADJ", "V"}: + if not full and not (alone and edge_forced): + return None + elif last.cls == "DET": + if not edge_forced: + return None + elif last.cls == "S2": + if last.word not in {"ha", "ra"} or any(u.cls != "S2" for u in conjunct): + return None + else: + return None + if is_last_conjunct: + head_kind = "TIME" if last.temporal else "NOUN" + return head_kind + + def _template_ok( + self, + body: Sequence[Unit], + types: Sequence[str], + has_ka: bool, + predicative: bool, + relaxed: bool, + ) -> bool: + count = len(types) + bare = [position for position, kind in enumerate(types) if kind == "BARE"] + limit = 3 if has_ka else 2 + if len(bare) > limit: + return False + if predicative: + # nai and kelu need a complement, and canon makes a clause-initial + # pronoun before one the subject: mia lohau nai is "I am a dog". + if count == 0: + return False + content = [unit for unit in body if unit.cls != "S2"] + if count == 1 and len(content) > 1 and content[0].cls == "PRON": + return False + if relaxed: + return True + allowed = {0, count - 1} + if has_ka: + allowed.add(count - 2) + return all(position in allowed for position in bare) + + # ------------------------------------------------------------------ + # Reporting + # ------------------------------------------------------------------ + + def _render(self, pre: Sequence[Unit], division: tuple) -> str: + if not division: + return "" + boundaries, tail, _ = division + parts = [] + position = 0 + for stop in boundaries: + words = " ".join( + " ".join(self._words(u.start, u.end)) for u in pre[position:stop] + ) + parts.append(f"[{words}]") + position = stop + if tail < len(pre): + words = " ".join(u.word for u in pre[tail:]) + parts.append(f"<{words}>") + return " ".join(parts) + + def _seam_types(self, pre: Sequence[Unit], divisions: Sequence[tuple]) -> set[str]: + """Name each place that is a phrase edge in one reading and not in another.""" + types: set[str] = set() + edge_sets = [] + manner_starts = set() + for boundaries, tail, _ in divisions: + edges = set(boundaries) + if tail < len(pre): + manner_starts.add(tail) + edge_sets.append(edges - {len(pre)}) + if len(manner_starts) > 0 and any(tail == len(pre) for _, tail, _ in divisions): + types.add("manner or object") + every = set().union(*edge_sets) if edge_sets else set() + for edge in sorted(every): + if all(edge in edges for edges in edge_sets): + continue + left, right = pre[edge - 1], pre[edge] + if left.temporal or right.temporal or self._phrase_is_time(pre, edge): + types.add("time word") + elif right.cls == "S2": + types.add("before a Slot 2 word") + elif left.cls == "PRON": + types.add("pronoun then noun") + elif left.cls == "NAME": + types.add("name then noun") + elif left.cls in {"ADJ", "V"} or right.cls in {"ADJ", "V"}: + types.add("quality or event word") + else: + types.add("noun then noun") + return types + + def _phrase_is_time(self, pre: Sequence[Unit], edge: int) -> bool: + position = edge + while position < len(pre) and pre[position].cls in {"S2", "DET", "ADJ"}: + position += 1 + return position < len(pre) and pre[position].temporal + + +def count_readings(text: str, counter: ReadingCounter | None = None) -> SentenceReadings | None: + """Convenience wrapper for one sentence.""" + return (counter or ReadingCounter()).analyse(text) diff --git a/scripts/phi_roles.py b/scripts/phi_roles.py new file mode 100644 index 00000000..9b764ef5 --- /dev/null +++ b/scripts/phi_roles.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Count open roles and contested third persons in Phi text. + +``phi_readings`` counts how a clause divides into phrases. Two things it +cannot see are where readers of the certified texts actually went wrong: + +* **An open role.** A clause has one bare phrase and a verb that elsewhere + takes both a subject and an object. Phi lets an established subject go + unsaid and marks no case, so the phrase is the subject (with nothing said + about an object) or the object (with the subject unsaid). ``lopia nuola`` + is "the child eats" and "(it) eats the child". +* **A contested third person.** Phi has one third-person pronoun. When two + or more third persons are live in the story, ``shia`` and an unsaid + subject both leave the listener to choose. + +Neither count uses meanings. Whether a verb takes an object is read from +the corpus itself, so the figures are indicators of exposure, not rates of +misunderstanding. + +A verb counts as taking an object when the corpus shows it at least once + +* in the passive (``shelu se theo``), +* with two bare phrases that cannot be read as one, each headed by a noun, + pronoun, name, or complement frame (``mia thia nila``, + ``mia tha ... tho sano``), or +* in a command over a noun phrase that is not the person addressed + (``no shelu theo``). + +Only clauses with a single structural reading are taken as witnesses, so an +adjective standing as manner or complement is not mistaken for an object. +""" + +from __future__ import annotations + +from collections import Counter, deque +from dataclasses import dataclass, field +from typing import Iterable + +from phi_readings import ClauseReadings, SentenceReadings +from phi_sentence_validator import PREDICATIVE_VERBS + +ADDRESSEE = frozenset({"thia"}) +ARGUMENT_HEADS = frozenset({"N", "PRON", "NAME", "FRAME", "REL"}) +# How many earlier sentences a third person stays live for. +WINDOW = 3 + + +def settled(sentence: SentenceReadings) -> bool: + """Whether every dependent clause in the sentence has one possible end.""" + return all(join.alternatives == 1 for join in sentence.joins) + + +def object_taking_verbs(sentences: Iterable[SentenceReadings]) -> Counter[str]: + """Verbs the corpus shows with an object, with the number of witnesses.""" + seen: Counter[str] = Counter() + for sentence in sentences: + if not settled(sentence): + continue + for clause in sentence.clauses: + verb = clause.verb + if not verb or verb in PREDICATIVE_VERBS or "ka" in clause.slot1: + continue + if "se" in clause.slot1: + seen[verb] += 1 + continue + if clause.gapped or clause.full != 1: + continue + heads_ok = all(cls in ARGUMENT_HEADS for cls, _ in clause.bare_heads) + if clause.bare_counts == (2,) and heads_ok: + seen[verb] += 1 + elif ( + "no" in clause.slot0 + and clause.bare_counts == (1,) + and clause.bare_heads + and clause.bare_heads[0][0] in {"N", "NAME"} + ): + seen[verb] += 1 + return seen + + +def open_role(clause: ClauseReadings, object_verbs: Counter[str] | set[str]) -> str | None: + """Name the open role in a clause, if it has one. + + ``main`` is a clause whose one bare phrase may be subject or object. + ``relative`` is a relative clause whose head may be either, because the + one phrase left inside it may be the other. + """ + if clause.verb not in object_verbs or clause.verb in PREDICATIVE_VERBS: + return None + if "se" in clause.slot1 or "ka" in clause.slot1: + return None + if clause.bare_counts != (1,): + return None + if not clause.bare_heads or clause.bare_heads[0][0] not in ARGUMENT_HEADS: + return None + if clause.gapped: + return "relative" + if "no" in clause.slot0: + return None + return "main" + + +@dataclass +class ReferenceCounts: + """Third-person exposure in one sentence.""" + + third_person_pronouns: int = 0 + contested_pronouns: int = 0 + doubled_clauses: int = 0 + unsaid_subjects: int = 0 + contested_unsaid: int = 0 + live: tuple[str, ...] = () + + +@dataclass +class ReferenceTracker: + """Follow which third persons are live as a text goes by. + + A third person is the head of a clause-initial bare phrase that is a + noun or a name: the likeliest subjects. It stays live for ``window`` + further sentences. This is a heuristic. It knows nothing of animacy or + plausibility, and it treats a thing and a person alike, as ``shia`` does. + """ + + window: int = WINDOW + recent: deque = field(default_factory=deque) + + def reset(self) -> None: + self.recent.clear() + + def observe(self, sentence: SentenceReadings) -> ReferenceCounts: + own = [] + for clause in sentence.clauses: + if clause.gapped or clause.first_bare is None: + continue + cls, word = clause.first_bare + if cls in {"N", "NAME"}: + own.append(word) + live = set(own) + for earlier in self.recent: + live.update(earlier) + counts = ReferenceCounts(live=tuple(sorted(live))) + words = sentence.text.replace(".", " ").split() + counts.third_person_pronouns = words.count("shia") + if len(live) >= 2: + counts.contested_pronouns = counts.third_person_pronouns + for clause in sentence.clauses: + if clause.third_persons >= 2: + counts.doubled_clauses += 1 + if ( + not clause.gapped + and clause.bare_counts == (0,) + and "no" not in clause.slot0 + and clause.verb not in PREDICATIVE_VERBS + ): + counts.unsaid_subjects += 1 + if len(live) >= 2: + counts.contested_unsaid += 1 + self.recent.append(own) + while len(self.recent) > self.window: + self.recent.popleft() + return counts diff --git a/scripts/test_phi_readings.py b/scripts/test_phi_readings.py new file mode 100644 index 00000000..01f2966b --- /dev/null +++ b/scripts/test_phi_readings.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Regression tests for the structural-reading counter.""" + +from pathlib import Path +import subprocess +import sys +import unittest + +from phi_readings import ReadingCounter + + +PROJECT_ROOT = Path(__file__).resolve().parent.parent + + +class ReadingCounterTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.counter = ReadingCounter() + + def counts(self, text): + result = self.counter.analyse(text) + self.assertIsNotNone(result, text) + return result.conservative, result.full + + def test_settled_clauses_have_one_reading(self): + for text in ( + "mia thia nila.", + "melu to kamo.", + "lopia tei norawhi wile.", + "shia to pakiro whano.", + "mia thia ru woraka.", + ): + with self.subTest(text=text): + self.assertEqual((1, 1), self.counts(text)) + + def test_a_bare_noun_chain_divides_at_every_seam(self): + result = self.counter.analyse("phao lopia shelu theo.") + self.assertEqual(3, result.conservative) + self.assertEqual( + ["[phao] [lopia shelu]", "[phao lopia] [shelu]", "[phao lopia shelu]"], + result.clauses[0].divisions, + ) + self.assertEqual(["noun then noun"], result.clauses[0].seams) + + def test_the_causative_admits_a_third_bare_phrase(self): + self.assertEqual((4, 4), self.counts("phao lopia shelu ka theo.")) + + def test_a_pronoun_begins_its_phrase(self): + self.assertEqual((1, 1), self.counts("mia shia wiru ma nila.")) + + def test_canon_settles_the_pronoun_before_nai(self): + self.assertEqual((1, 1), self.counts("mia lohau nai.")) + self.assertEqual(1, self.counts("mia lohau welao nai.")[0]) + + def test_manner_or_object_without_a_slot_one_stack(self): + result = self.counter.analyse("shia welao thumela.") + self.assertEqual((2, 3), (result.conservative, result.full)) + self.assertEqual(["[shia] ", "[shia] [welao]"], result.clauses[0].divisions) + self.assertEqual(["manner or object"], result.clauses[0].seams) + + def test_an_event_noun_with_a_possessor_is_a_full_count_reading(self): + self.assertEqual((1, 2), self.counts("mia nohero to helui.")) + + def test_a_bare_time_word_is_an_open_seam(self): + result = self.counter.analyse("mia nosa thole.") + self.assertEqual(2, result.conservative) + self.assertEqual(["time word"], result.clauses[0].seams) + + def test_a_prepositional_phrase_has_no_marked_end(self): + result = self.counter.analyse("mia mua womu shelu theo.") + self.assertEqual( + ["[mia] [mua womu] [shelu]", "[mia] [mua womu shelu]"], + result.clauses[0].divisions, + ) + + def test_dependent_material_may_end_in_more_than_one_place(self): + result = self.counter.analyse("lao pheralu ruela wirua nai.") + self.assertEqual(2, result.conservative) + self.assertEqual([("adverbial", 2)], [(j.kind, j.alternatives) for j in result.joins]) + result = self.counter.analyse("tei thia shua mia so hasi.") + self.assertEqual([("adverbial", 2)], [(j.kind, j.alternatives) for j in result.joins]) + + def test_quoted_sentences_count_as_sentences_of_their_own(self): + parts = self.counter.analyse_sentences( + "ne kulo sha lia. mia melu shelu so theo sho to haolu." + ) + self.assertEqual( + [("ne kulo sha... sho to haolu.", 1), ("lia.", 1), ("mia melu shelu so theo.", 3)], + [(part.text, part.conservative) for part in parts], + ) + + def test_opener_what_if_closes_the_seam_before_a_slot_two_word(self): + self.assertEqual((2, 2), self.counts("phao ha shelu theo.")) + strict = ReadingCounter(openers=frozenset({"ha", "ra", "lo"})) + self.assertEqual(1, strict.analyse("phao ha shelu theo.").conservative) + + def test_a_sentence_that_does_not_parse_has_no_count(self): + self.assertIsNone(self.counter.analyse("mia shua mia.")) + + def test_cli_shows_the_divisions(self): + completed = subprocess.run( + [ + sys.executable, + str(PROJECT_ROOT / "scripts" / "audit_phrase_readings.py"), + "--sentence", + "phao lopia shelu theo.", + ], + cwd=PROJECT_ROOT, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(0, completed.returncode, completed.stdout + completed.stderr) + self.assertIn("readings: 3 conservative, 3 full", completed.stdout) + self.assertIn("[phao lopia] [shelu]", completed.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_phi_roles.py b/scripts/test_phi_roles.py new file mode 100644 index 00000000..70263ac0 --- /dev/null +++ b/scripts/test_phi_roles.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Regression tests for the open-role and third-person counts.""" + +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from phi_readings import ReadingCounter +from phi_roles import ReferenceTracker, object_taking_verbs, open_role + + +PROJECT_ROOT = Path(__file__).resolve().parent.parent + + +class RoleTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.counter = ReadingCounter() + + def sentences(self, *texts): + parts = [] + for text in texts: + found = self.counter.analyse_sentences(text) + self.assertIsNotNone(found, text) + parts.extend(found) + return parts + + def test_three_kinds_of_witness_show_a_verb_takes_an_object(self): + verbs = object_taking_verbs( + self.sentences("mia thia nila.", "shelu se theo.", "no noru kolua.") + ) + self.assertEqual({"nila", "theo", "kolua"}, set(verbs)) + + def test_manner_and_single_phrases_are_not_witnesses(self): + verbs = object_taking_verbs( + self.sentences("melu to kamo.", "shia welao thumela.", "no thia shua.") + ) + self.assertEqual(set(), set(verbs)) + + def test_one_bare_phrase_before_an_object_taking_verb_is_an_open_role(self): + verbs = {"nila", "nuola"} + (clause,) = self.sentences("lopia nuola.")[0].clauses + self.assertEqual("main", open_role(clause, verbs)) + (clause,) = self.sentences("lo phirae tupiwa so ma nila.")[0].clauses + self.assertEqual("main", open_role(clause, verbs)) + + def test_roles_are_settled_by_two_phrases_passive_command_or_verb(self): + verbs = {"nila", "nuola", "theo"} + for text in ("mia thia nila.", "shelu se theo.", "no shelu theo.", "melu to kamo."): + with self.subTest(text=text): + (clause,) = self.sentences(text)[0].clauses + self.assertIsNone(open_role(clause, verbs)) + + def test_a_relative_clause_with_one_phrase_leaves_its_head_open(self): + verbs = {"nila"} + clauses = self.sentences("whu mia nila miona shua.")[0].clauses + kinds = [open_role(clause, verbs) for clause in clauses] + self.assertIn("relative", kinds) + + def test_third_persons_become_contested_when_two_are_live(self): + tracker = ReferenceTracker() + first, second, third = self.sentences( + "ne samira to shua.", "lopia to wile.", "shia to hola." + ) + self.assertEqual(0, tracker.observe(first).contested_pronouns) + self.assertEqual(0, tracker.observe(second).contested_pronouns) + counts = tracker.observe(third) + self.assertEqual(1, counts.third_person_pronouns) + self.assertEqual(1, counts.contested_pronouns) + self.assertEqual(("lopia", "samira"), counts.live) + + def test_one_live_third_person_is_not_contested(self): + tracker = ReferenceTracker() + first, second = self.sentences("lopia to wile.", "shia to hola.") + tracker.observe(first) + self.assertEqual(0, tracker.observe(second).contested_pronouns) + + def test_two_separate_shia_in_one_clause_are_counted(self): + tracker = ReferenceTracker() + (sentence,) = self.sentences("shia roa shia to pa rato.") + self.assertEqual(1, tracker.observe(sentence).doubled_clauses) + + def test_an_unsaid_subject_is_counted(self): + tracker = ReferenceTracker() + first, second, third = self.sentences( + "ne samira to shua.", "lopia to wile.", "mua womu to therilu." + ) + tracker.observe(first) + tracker.observe(second) + counts = tracker.observe(third) + self.assertEqual((1, 1), (counts.unsaid_subjects, counts.contested_unsaid)) + + def test_committed_ledger_is_current(self): + completed = subprocess.run( + [sys.executable, str(PROJECT_ROOT / "scripts" / "audit_phrase_readings.py"), "--check"], + cwd=PROJECT_ROOT, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(0, completed.returncode, completed.stdout + completed.stderr) + + def test_ledger_refuses_the_what_if(self): + with tempfile.TemporaryDirectory() as directory: + completed = subprocess.run( + [ + sys.executable, + str(PROJECT_ROOT / "scripts" / "audit_phrase_readings.py"), + "--openers", + "ha", + "--output", + str(Path(directory) / "ledger.txt"), + ], + cwd=PROJECT_ROOT, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(2, completed.returncode) + + +if __name__ == "__main__": + unittest.main()