tensorlogic-cli 0.1.0-alpha.2

TensorLogic command-line interface and library for compiling logical expressions to tensor graphs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
# TensorLogic CLI

**Command-line interface for TensorLogic compilation**

[![Crates.io](https://img.shields.io/crates/v/tensorlogic-cli.svg)](https://crates.io/crates/tensorlogic-cli)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](../../LICENSE)

A comprehensive command-line tool for compiling logical expressions to tensor graphs using TensorLogic.

## Features

- πŸš€ **Multiple Modes**: Interactive REPL, batch processing, watch mode
- πŸ“ **Rich Input Formats**: Expression strings, JSON, YAML, stdin
- πŸ“Š **Multiple Output Formats**: Graph, DOT, JSON, statistics
- βš™οΈ **6 Compilation Strategies**: Differentiable, Boolean, fuzzy logic variants
- 🎨 **Colored Output**: Beautiful terminal output with status indicators
- πŸ” **Graph Analysis**: Complexity metrics, FLOP estimation, memory analysis
- πŸ“ **Configuration Files**: Persistent settings via `.tensorlogicrc`
- πŸ”„ **File Watching**: Auto-recompilation on file changes
- πŸ“¦ **Batch Processing**: Process multiple expressions with progress bars
- 🐚 **Shell Completion**: Bash, Zsh, Fish, PowerShell support
- 🎯 **Enhanced Parser**: Arithmetic, comparisons, conditionals, Unicode operators

## Installation

### From crates.io

```bash
cargo install tensorlogic-cli
```

### From source

```bash
git clone https://github.com/cool-japan/tensorlogic.git
cd tensorlogic
cargo install --path crates/tensorlogic-cli
```

### Development build

```bash
cargo build -p tensorlogic-cli --release
# Binary at target/release/tensorlogic
```

## Quick Start

### Basic Compilation

```bash
tensorlogic "knows(x, y)"
```

### Interactive REPL

```bash
tensorlogic repl
```

```
TensorLogic Interactive REPL
Type '.help' for available commands, '.exit' to quit

tensorlogic> knows(x, y) AND likes(y, z)
βœ“ Compilation successful
  3 tensors, 3 nodes, depth 2
```

### Batch Processing

```bash
# expressions.txt contains one expression per line
tensorlogic batch expressions.txt
```

### Watch Mode

```bash
tensorlogic watch my_expression.tl
```

## Usage

### Command Structure

```bash
tensorlogic [OPTIONS] <INPUT>
tensorlogic <SUBCOMMAND>
```

### Main Options

| Option | Description |
|--------|-------------|
| `-f, --input-format <FORMAT>` | Input format: `expr`, `json`, `yaml` (default: `expr`) |
| `-o, --output <FILE>` | Output file (default: stdout) |
| `-F, --output-format <FORMAT>` | Output format: `graph`, `dot`, `json`, `stats` (default: `graph`) |
| `-s, --strategy <STRATEGY>` | Compilation strategy |
| `-d, --domain <NAME:SIZE>` | Define domain (can be repeated) |
| `--validate` | Enable graph validation |
| `--debug` | Enable debug output |
| `-a, --analyze` | Show graph analysis metrics |
| `-q, --quiet` | Quiet mode (minimal output) |
| `--no-color` | Disable colored output |
| `--no-config` | Don't load configuration file |

### Subcommands

#### `repl` - Interactive REPL

Start an interactive Read-Eval-Print Loop for exploring TensorLogic.

```bash
tensorlogic repl
```

**REPL Commands:**
- `.help` - Show help
- `.exit` - Exit REPL
- `.clear` - Clear screen
- `.context` - Show compiler context
- `.domain <name> <size>` - Add domain
- `.strategy [name]` - Show/set strategy
- `.validate` - Toggle validation
- `.debug` - Toggle debug mode
- `.history` - Show command history

#### `batch` - Batch Processing

Process multiple expressions from files (one expression per line).

```bash
tensorlogic batch file1.txt file2.txt
```

Features:
- Progress bar with elapsed time
- Summary statistics (successes/failures)
- Line-by-line error reporting
- Comments support (`#` prefix)

#### `watch` - File Watching

Watch a file and recompile on changes.

```bash
tensorlogic watch expression.tl
```

Features:
- Auto-recompilation on file save
- Debounced updates (configurable)
- Clear screen on reload (configurable)
- Timestamp display

#### `completion` - Shell Completion

Generate shell completion scripts.

```bash
# Bash
tensorlogic completion bash > /etc/bash_completion.d/tensorlogic

# Zsh
tensorlogic completion zsh > ~/.zsh/completion/_tensorlogic

# Fish
tensorlogic completion fish > ~/.config/fish/completions/tensorlogic.fish

# PowerShell
tensorlogic completion powershell > tensorlogic.ps1
```

#### `config` - Configuration Management

Manage configuration files.

```bash
# Show current configuration
tensorlogic config show

# Show config file path
tensorlogic config path

# Initialize default config
tensorlogic config init

# Edit configuration
tensorlogic config edit
```

## Configuration File

TensorLogic CLI supports persistent configuration via `.tensorlogicrc` (TOML format).

**Search order:**
1. `TENSORLOGIC_CONFIG` environment variable
2. `.tensorlogicrc` in current directory
3. `.tensorlogicrc` in home directory

**Example configuration:**

```toml
# Default compilation strategy
strategy = "soft_differentiable"

# Enable colored output
colored = true

# Enable validation by default
validate = false

# Default domains
[domains]
Person = 100
City = 50

# REPL settings
[repl]
prompt = "tensorlogic> "
history_file = ".tensorlogic_history"
max_history = 1000
auto_save = true

# Watch mode settings
[watch]
debounce_ms = 500
clear_screen = true
show_timestamps = true
```

### Initialize Configuration

```bash
tensorlogic config init
```

## Input Formats

### 1. Expression String (Default)

Direct expression input with enhanced syntax:

```bash
tensorlogic "knows(x, y) AND likes(y, z)"
```

**Supported syntax:**
- **Predicates**: `pred(x, y, ...)`
- **Logical**: `AND` (`&`, `&&`, `∧`), `OR` (`|`, `||`, `∨`), `NOT` (`~`, `!`, `Β¬`), `IMPLIES` (`->`, `=>`, `β†’`)
- **Quantifiers**: `EXISTS x IN Domain. expr` (`βˆƒ`), `FORALL x IN Domain. expr` (`βˆ€`)
- **Arithmetic**: `+`, `-`, `*` (`Γ—`), `/` (`Γ·`)
- **Comparisons**: `=` (`==`), `<`, `>`, `<=` (`≀`), `>=` (`β‰₯`), `!=` (`β‰ `)
- **Conditional**: `IF cond THEN x ELSE y`
- **Parentheses**: `(...)` for grouping

**Examples:**
```bash
# Basic predicate
tensorlogic "person(x)"

# Logical operations
tensorlogic "p(x) AND q(y) OR r(z)"

# Quantifiers
tensorlogic "EXISTS x IN Person. knows(x, alice)"
tensorlogic "FORALL x IN Person. likes(x, pizza)"

# Arithmetic
tensorlogic "age(x) + 10"

# Comparisons
tensorlogic "age(x) > 18"

# Conditional
tensorlogic "IF age(x) >= 18 THEN adult(x) ELSE child(x)"

# Complex expression
tensorlogic "(p(x) OR q(y)) AND (r(z) -> s(w))"
```

### 2. JSON Input

```bash
tensorlogic --input-format json expression.json
```

```json
{
  "And": {
    "left": {
      "Pred": {
        "name": "knows",
        "args": [{"Var": "x"}, {"Var": "y"}]
      }
    },
    "right": {
      "Pred": {
        "name": "likes",
        "args": [{"Var": "y"}, {"Var": "z"}]
      }
    }
  }
}
```

### 3. YAML Input

```bash
tensorlogic --input-format yaml expression.yaml
```

```yaml
And:
  left:
    Pred:
      name: knows
      args:
        - Var: x
        - Var: y
  right:
    Pred:
      name: likes
      args:
        - Var: y
        - Var: z
```

### 4. Stdin Input

```bash
echo '{"Pred": {"name": "test", "args": []}}' | tensorlogic --input-format json -
```

## Output Formats

### 1. Graph (Default)

Human-readable graph structure:

```bash
tensorlogic "knows(x, y)" --output-format graph
```

### 2. DOT Format

Generate Graphviz DOT for visualization:

```bash
tensorlogic "knows(x, y)" --output-format dot > graph.dot
dot -Tpng graph.dot -o graph.png
```

### 3. JSON

Machine-readable JSON output:

```bash
tensorlogic "knows(x, y)" --output-format json
```

### 4. Statistics

Graph statistics and metrics:

```bash
tensorlogic "knows(x, y) AND likes(y, z)" --output-format stats
```

Output:
```
Graph Statistics:
  Tensors: 3
  Nodes: 3
  Inputs: 2
  Outputs: 1
  Depth: 2
  Avg Fanout: 1.00

Operation Breakdown:
  Einsum: 2
  ElemBinary: 1

Estimated Complexity:
  FLOPs: 6000
  Memory: 24000 bytes
```

## Compilation Strategies

Choose from 6 preset strategies:

### 1. Soft Differentiable (Default)

For neural network training with smooth gradients:

```bash
tensorlogic --strategy soft_differentiable "p AND q"
```

- AND: Element-wise product
- OR: Probabilistic sum
- NOT: Complement (1 - x)

### 2. Hard Boolean

For discrete Boolean logic:

```bash
tensorlogic --strategy hard_boolean "p AND q"
```

- AND: Minimum
- OR: Maximum
- NOT: Complement

### 3. Fuzzy GΓΆdel

GΓΆdel fuzzy logic (min/max operations):

```bash
tensorlogic --strategy fuzzy_godel "p AND q"
```

### 4. Fuzzy Product

Product fuzzy logic (probabilistic):

```bash
tensorlogic --strategy fuzzy_product "p AND q"
```

### 5. Fuzzy Łukasiewicz

Łukasiewicz fuzzy logic (bounded):

```bash
tensorlogic --strategy fuzzy_lukasiewicz "p AND q"
```

### 6. Probabilistic

Probabilistic interpretation:

```bash
tensorlogic --strategy probabilistic "p AND q"
```

## Domain Definitions

Define domains for variables:

```bash
tensorlogic --domain Person:100 --domain City:50 "lives_in(x, c)"
```

Multiple domains:

```bash
tensorlogic \
  --domain Person:100 \
  --domain Location:50 \
  --domain Event:20 \
  "attends(p, e) AND located_at(e, l)"
```

## Graph Analysis

Enable detailed analysis with `--analyze`:

```bash
tensorlogic "complex(expression)" --analyze
```

Output includes:
- Tensor and node counts
- Graph depth (longest path)
- Average fanout (outputs per node)
- Operation breakdown (Einsum, element-wise, reduction)
- Estimated FLOPs (computational cost)
- Estimated memory usage

## Validation

Enable graph validation:

```bash
tensorlogic "knows(x, y)" --validate
```

Checks:
- Free variable consistency
- Arity validation
- Type checking
- Graph structure validity

## Debug Mode

Enable detailed debug output:

```bash
tensorlogic "knows(x, y)" --debug
```

Shows:
- Parsed expression (AST)
- Compiler context (domains, strategies)
- Intermediate compilation steps
- Final graph structure
- Validation results

## Examples

### Example 1: Simple Predicate

```bash
tensorlogic "knows(alice, bob)"
```

### Example 2: Logical Conjunction

```bash
tensorlogic "knows(x, y) AND likes(y, z)"
```

### Example 3: Quantifier

```bash
tensorlogic --domain Person:100 "EXISTS x IN Person. knows(x, bob)"
```

### Example 4: Implication

```bash
tensorlogic "knows(x, y) -> likes(x, y)"
```

### Example 5: Arithmetic and Comparison

```bash
tensorlogic "age(x) + 10 > 30"
```

### Example 6: Conditional Expression

```bash
tensorlogic "IF age(x) >= 18 THEN adult(x) ELSE child(x)"
```

### Example 7: Visualization

```bash
tensorlogic "knows(x, y) AND likes(y, z)" \
  --output-format dot \
  --validate > graph.dot
dot -Tpng graph.dot -o graph.png
```

### Example 8: Complex Expression with Analysis

```bash
tensorlogic \
  "FORALL x IN Person. (knows(x, y) -> likes(x, y))" \
  --domain Person:100 \
  --strategy fuzzy_godel \
  --output-format stats \
  --analyze \
  --validate
```

### Example 9: Batch Processing with Progress

```bash
cat > expressions.txt << EOF
knows(x, y)
likes(y, z)
knows(x, y) AND likes(y, z)
EXISTS x. knows(x, bob)
FORALL x. person(x) -> mortal(x)
EOF

tensorlogic batch expressions.txt
```

### Example 10: Interactive REPL Session

```bash
tensorlogic repl
```

```
tensorlogic> .domain Person 100
βœ“ Added domain 'Person' with size 100

tensorlogic> .strategy fuzzy_godel
βœ“ Strategy set to: fuzzy_godel

tensorlogic> EXISTS x IN Person. knows(x, alice)
βœ“ Compilation successful
  2 tensors, 2 nodes, depth 2

tensorlogic> .history
   1: .domain Person 100
   2: .strategy fuzzy_godel
   3: EXISTS x IN Person. knows(x, alice)

tensorlogic> .exit
```

## Integration

### With Graphviz

Generate PNG visualization:

```bash
tensorlogic "knows(x, y)" --output-format dot | dot -Tpng -o graph.png
```

### With jq (JSON Processing)

Extract tensor count:

```bash
tensorlogic "knows(x, y)" --output-format json | jq '.tensors | length'
```

### In Scripts

```bash
#!/bin/bash
EXPR="knows(x, y) AND likes(y, z)"

if tensorlogic "$EXPR" --output-format stats --validate --quiet; then
    echo "βœ“ Compilation successful"
else
    echo "βœ— Compilation failed"
    exit 1
fi
```

### With Make

```makefile
.PHONY: compile watch

compile:
	tensorlogic expression.tl --validate --analyze

watch:
	tensorlogic watch expression.tl
```

## Troubleshooting

### Command Not Found

Make sure `~/.cargo/bin` is in your PATH:

```bash
export PATH="$HOME/.cargo/bin:$PATH"
```

### Parsing Errors

Use `--debug` to see detailed parsing information:

```bash
tensorlogic "your expression" --debug
```

### Validation Failures

Check free variables and domains:

```bash
tensorlogic "EXISTS x. p(x, y)" \
  --domain Domain:10 \
  --debug \
  --validate
```

### Configuration Issues

Show current configuration:

```bash
tensorlogic config show
```

Show config file path:

```bash
tensorlogic config path
```

Reinitialize configuration:

```bash
tensorlogic config init
```

## Environment Variables

| Variable | Description |
|----------|-------------|
| `TENSORLOGIC_CONFIG` | Custom config file path |
| `EDITOR` | Editor for `config edit` command (default: `vi`) |

Example:

```bash
export TENSORLOGIC_CONFIG=~/.config/tensorlogic.toml
export EDITOR=nano
tensorlogic config edit
```

## Performance Tips

1. **Use batch mode** for multiple expressions
2. **Enable validation** only when needed
3. **Use quiet mode** (`-q`) in scripts
4. **Disable colors** (`--no-color`) for log files
5. **Use analysis** (`--analyze`) to identify bottlenecks

## Development

### Building

```bash
cargo build -p tensorlogic-cli
```

### Testing

```bash
cargo test -p tensorlogic-cli
```

### Running from Source

```bash
cargo run -p tensorlogic-cli -- --help
```

### Code Structure

```
src/
β”œβ”€β”€ main.rs       - Main entry point and command routing
β”œβ”€β”€ cli.rs        - Clap CLI definitions
β”œβ”€β”€ config.rs     - Configuration file support
β”œβ”€β”€ parser.rs     - Enhanced expression parser
β”œβ”€β”€ output.rs     - Colored output formatting
β”œβ”€β”€ analysis.rs   - Graph metrics and analysis
β”œβ”€β”€ repl.rs       - Interactive REPL mode
β”œβ”€β”€ batch.rs      - Batch processing
β”œβ”€β”€ watch.rs      - File watching
└── completion.rs - Shell completion generation
```

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.

## License

Licensed under Apache 2.0 License. See [LICENSE](../../LICENSE) for details.

## See Also

- **Main README**: [README.md]../../README.md
- **Project Guide**: [CLAUDE.md]../../CLAUDE.md
- **Meta Crate**: [tensorlogic]../tensorlogic/README.md
- **Compiler Documentation**: [tensorlogic-compiler]../tensorlogic-compiler/README.md
- **IR Documentation**: [tensorlogic-ir]../tensorlogic-ir/README.md

## Resources

- **Repository**: https://github.com/cool-japan/tensorlogic
- **Documentation**: https://docs.rs/tensorlogic-cli
- **Issues**: https://github.com/cool-japan/tensorlogic/issues

---

**Part of the COOLJAPAN Ecosystem**

For questions and support, please open an issue on [GitHub](https://github.com/cool-japan/tensorlogic/issues).