# math

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"open testing\nopen rust.rust_operators\nopen rust","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  open testing
  open rust.rust_operators
  open rust
  """,
  timeout: 300_000
)
```

## complex

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"nominal complex t = $'num_complex::Complex<`t>'\n\ninl complex forall t. ((re : t), (im : t)) : complex t =\n    !\\\\((re, im), $'\"num_complex::Complex::new($0, $1)\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  nominal complex t = $'num_complex::Complex<`t>'

  inl complex forall t. ((re : t), (im : t)) : complex t =
      !\\((re, im), $'"num_complex::Complex::new($0, $1)"')
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex\n\ncomplex (0f64, 0f64)\n|> sm'.format'\n|> sm'.from_std_string\n|> _assert_eq \"0+0i\"","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex

  complex (0f64, 0f64)
  |> sm'.format'
  |> sm'.from_std_string
  |> _assert_eq "0+0i"
  """,
  timeout: 300_000
)
```

## re

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl re forall t. (c : complex t) : t =\n    !\\\\(c, $'\"$0.re\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl re forall t. (c : complex t) : t =
      !\\(c, $'"$0.re"')
  """,
  timeout: 300_000
)
```

## im

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl im forall t. (c : complex t) : t =\n    !\\\\(c, $'\"$0.im\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl im forall t. (c : complex t) : t =
      !\\(c, $'"$0.im"')
  """,
  timeout: 300_000
)
```

## complex_unbox

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl complex_unbox forall t. (c : complex t) =\n    re c, im c","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl complex_unbox forall t. (c : complex t) =
      re c, im c
  """,
  timeout: 300_000
)
```

## (~.^)

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl (~.^) c = complex c","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl (~.^) c = complex c
  """,
  timeout: 300_000
)
```

## complex_eq

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl complex_eq forall t. (a : complex t) (b : complex t) : bool =\n    !\\\\((a, b), $'\"$0 == $1\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl complex_eq forall t. (a : complex t) (b : complex t) : bool =
      !\\((a, b), $'"$0 == $1"')
  """,
  timeout: 300_000
)
```

## (.=)

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl (.=) a b = complex_eq a b","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl (.=) a b = complex_eq a b
  """,
  timeout: 300_000
)
```

## equable complex

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"instance equable complex t = complex_eq","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  instance equable complex t = complex_eq
  """,
  timeout: 300_000
)
```

## complex_add

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl complex_add forall t. (a : complex t) (b : complex t) : complex t =\n    !\\\\((a, b), $'\"$0 + $1\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl complex_add forall t. (a : complex t) (b : complex t) : complex t =
      !\\((a, b), $'"$0 + $1"')
  """,
  timeout: 300_000
)
```

## (.+)

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl (.+) a b = complex_add a b","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl (.+) a b = complex_add a b
  """,
  timeout: 300_000
)
```

## complex_sub

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl complex_sub forall t. (a : complex t) (b : complex t) : complex t =\n    !\\\\((a, b), $'\"$0 - $1\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl complex_sub forall t. (a : complex t) (b : complex t) : complex t =
      !\\((a, b), $'"$0 - $1"')
  """,
  timeout: 300_000
)
```

## (.-)

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl (.-) a b = complex_sub a b","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl (.-) a b = complex_sub a b
  """,
  timeout: 300_000
)
```

## complex_mult

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl complex_mult forall t. (a : complex t) (b : complex t) : complex t =\n    !\\\\((a, b), $'\"$0 * $1\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl complex_mult forall t. (a : complex t) (b : complex t) : complex t =
      !\\((a, b), $'"$0 * $1"')
  """,
  timeout: 300_000
)
```

## (.*)

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl (.*) a b = complex_mult a b","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl (.*) a b = complex_mult a b
  """,
  timeout: 300_000
)
```

## complex_div

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl complex_div forall t. (a : complex t) (b : complex t) : complex t =\n    !\\\\((a, b), $'\"$0 / $1\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl complex_div forall t. (a : complex t) (b : complex t) : complex t =
      !\\((a, b), $'"$0 / $1"')
  """,
  timeout: 300_000
)
```

## (./)

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl (./) a b = complex_div a b","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl (./) a b = complex_div a b
  """,
  timeout: 300_000
)
```

## powc

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl powc forall t. (s : complex t) (c : complex t) : complex t =\n    !\\\\((c, s), $'\"num_complex::Complex::powc($0, $1)\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl powc forall t. (s : complex t) (c : complex t) : complex t =
      !\\((c, s), $'"num_complex::Complex::powc($0, $1)"')
  """,
  timeout: 300_000
)
```

## (.**)

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl (.**) a b = powc b a","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl (.**) a b = powc b a
  """,
  timeout: 300_000
)
```

## complex_sin

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl complex_sin forall t. (c : complex t) : complex t =\n    !\\\\(c, $'\"$0.sin()\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl complex_sin forall t. (c : complex t) : complex t =
      !\\(c, $'"$0.sin()"')
  """,
  timeout: 300_000
)
```

## conj

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl conj forall t. (c : complex t) : complex t =\n    !\\\\(c, $'\"$0.conj()\"')","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl conj forall t. (c : complex t) : complex t =
      !\\(c, $'"$0.conj()"')
  """,
  timeout: 300_000
)
```

## zeta

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl zeta log (gamma : complex f64 -> complex f64) (s : complex f64) : complex f64 =\n    // inl rec zeta count gamma s =\n    inl rec zeta forall t {number}.\n        (count : t)\n        (gamma : complex f64 -> complex f64)\n        (s : complex f64)\n        : complex f64\n        =\n        if log then\n            !\\\\((count, s), $'\"println\\!(\\\\\\\"zeta / count: {:?} / s: {:?}\\\\\\\", $0, $1)\"')\n        if re s > 1 then\n            (.^(0, 0), (am.init 10000i32 id : a i32 _))\n            ||> am.fold fun acc n =>\n                acc .+ (.^(1, 0) ./ (.^(n |> convert.f64, 0) .** s))\n        else\n            inl gamma_term = gamma (.^(1, 0) .- s)\n            inl sin_term = .^(pi, 0) .* s ./ .^(2, 0) |> complex_sin\n            inl one_minus_s = .^(1 - re s, -(im s))\n            inl mirror_term =\n                if re one_minus_s <= 1\n                then .^(0, 0)\n                else\n                    if count <= 3\n                    then zeta (count + 1) gamma one_minus_s\n                    else one_minus_s\n            inl reflection_formula =\n                .^(2, 0) .* (.^(pi, 0) .** s) .* sin_term .* gamma_term .* mirror_term\n            reflection_formula\n    join zeta 0i32 gamma s","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl zeta log (gamma : complex f64 -> complex f64) (s : complex f64) : complex f64 =
      // inl rec zeta count gamma s =
      inl rec zeta forall t {number}.
          (count : t)
          (gamma : complex f64 -> complex f64)
          (s : complex f64)
          : complex f64
          =
          if log then
              !\\((count, s), $'"println\!(\\\"zeta / count: {:?} / s: {:?}\\\", $0, $1)"')
          if re s > 1 then
              (.^(0, 0), (am.init 10000i32 id : a i32 _))
              ||> am.fold fun acc n =>
                  acc .+ (.^(1, 0) ./ (.^(n |> convert.f64, 0) .** s))
          else
              inl gamma_term = gamma (.^(1, 0) .- s)
              inl sin_term = .^(pi, 0) .* s ./ .^(2, 0) |> complex_sin
              inl one_minus_s = .^(1 - re s, -(im s))
              inl mirror_term =
                  if re one_minus_s <= 1
                  then .^(0, 0)
                  else
                      if count <= 3
                      then zeta (count + 1) gamma one_minus_s
                      else one_minus_s
              inl reflection_formula =
                  .^(2, 0) .* (.^(pi, 0) .** s) .* sin_term .* gamma_term .* mirror_term
              reflection_formula
      join zeta 0i32 gamma s
  """,
  timeout: 300_000
)
```

## bound

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"nominal bound t = $'pyo3::Bound<`t>'","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  nominal bound t = $'pyo3::Bound<`t>'
  """,
  timeout: 300_000
)
```

## python

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"nominal python = $'pyo3::Python'","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  nominal python = $'pyo3::Python'
  """,
  timeout: 300_000
)
```

## pymodule

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"nominal pymodule = $'pyo3::types::PyModule'","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  nominal pymodule = $'pyo3::types::PyModule'
  """,
  timeout: 300_000
)
```

## pyany

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"nominal pyany = $'pyo3::PyAny'","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  nominal pyany = $'pyo3::PyAny'
  """,
  timeout: 300_000
)
```

## pyerr

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"nominal pyerr = $'pyo3::PyErr'","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  nominal pyerr = $'pyo3::PyErr'
  """,
  timeout: 300_000
)
```

## eval

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl module_from_code (py : python) (code : string) : _ (bound pymodule) _ =\n    inl py = join py\n    inl code = code |> sm'.to_std_string |> sm'.new_c_string\n    inl empty = \"\" |> sm'.to_std_string |> sm'.new_c_string\n    !\\\\(code, $'\"pyo3::types::PyModule::from_code(!py, &$0, &!empty, &!empty)\"')\n    |> resultm.map_error'' fun (x : pyerr) => x |> sm'.format'\n\ninl use_pyanymethods () =\n    global \"use pyo3::prelude::PyAnyMethods;\"\n\ninl getattr (attr : string) (module : bound pymodule) : _ (bound pyany) _ =\n    inl attr = join attr\n    inl attr = attr |> sm'.as_str\n    inl module = join module\n    use_pyanymethods ()\n    !\\\\(attr, $'\"!module.getattr($0)\"')\n    |> resultm.map_error'' fun (x : pyerr) => x |> sm'.format'\n\ninl call forall t. (args : t) (module : bound pyany) : _ (bound pyany) _ =\n    inl args = join args\n    inl module = join module\n    inl result : resultm.result' (bound pyany) pyerr =\n        // pairs are plain Rust tuples: pyo3 takes the tuple as the call's args\n        !\\($'\"pyo3::prelude::PyAnyMethods::call(&!module, !args, None)\"') : resultm.result' (bound pyany) pyerr\n    result\n    |> resultm.map_error'' fun (x : pyerr) => x |> sm'.format'\n\ninl extract forall t. (result : bound pyany) : _ t _ =\n    inl result = join result\n    use_pyanymethods ()\n    !\\($'\"!result.extract()\"')\n    |> resultm.map_error'' fun (x : pyerr) => x |> sm'.format'\n\ninl eval py code (args : pair bool (pair f64 f64)) : _ (_ f64) sm'.std_string =\n    inl code =\n        code\n        |> module_from_code py\n        |> resultm.unwrap'\n    inl fn =\n        code\n        |> getattr \"fn\"\n        |> resultm.unwrap'\n\n    fn\n    |> call args\n    |> resultm.try'\n    |> extract\n    |> resultm.try'\n    |> complex\n    |> Ok\n    |> resultm.box\n\ninl call1_ log py s (code : string) =\n    inl code = join code\n\n    inl s = new_pair (re s) (im s)\n    inl args = new_pair log s\n\n    eval py code args\n\ninl call1_ log name py s line =\n    inl s = join s\n    join\n        ;[\n            \"import sys\"\n            \"import traceback\"\n            \"import re\"\n            \"count = 0\"\n            \"memory_address_pattern = re.compile(r' at 0x[0-9a-fA-F]+')\"\n            \"def trace_calls(frame, event, arg):\"\n            \"    global count\"\n            \"    count += 1\"\n            \"    if count < 200:\"\n            \"        try:\"\n            \"            args = { k: v for k, v in frame.f_locals.items() if frame.f_code.co_name != 'make_mpc' and k not in ['ctx'] and not callable(v) }\"\n            \"            args_str = ', '.join([ f\\\"{k}={re.sub(memory_address_pattern, ' at 0x<?>', repr(v))}\\\" for k, v in args.items() ])\"\n            \"            print(f\\\"{event}(__NAME__) / f_code.co_name: {frame.f_code.co_name} / f_locals: {args_str} / f_lineno: {frame.f_lineno} / f_code.co_filename: {frame.f_code.co_filename.split('site-packages')[-1]} / f_back.f_lineno: { '' if frame.f_back is None else frame.f_back.f_lineno } / f_back.f_code.co_filename: { '' if frame.f_back is None else frame.f_back.f_code.co_filename.split('site-packages')[-1] } / arg: {re.sub(memory_address_pattern, ' at 0x<?>', repr(arg))}\\\", flush=True)\"\n            \"        except ValueError as e:\"\n            \"            print(f'__NAME__ / e: {e}', flush=True)\"\n            \"        return trace_calls\"\n            \"import mpmath\"\n            \"def fn(log, s):\"\n            \"    global count\"\n            \"    if log:\"\n            \"        print(f'__NAME__ / s: {s} / count: {count}', flush=True)\"\n            \"    s = complex(*s)\"\n            \"    try:\"\n            \"        if log: sys.settrace(trace_calls)\"\n            line\n            \"        if log:\"\n            \"            sys.settrace(None)\"\n            \"            print(f'__NAME__ / result: {s} / count: {count}', flush=True)\"\n            \"    except ValueError as e:\"\n            \"        if s.real == 1:\"\n            \"            s = complex(float('inf'), 0)\"\n            \"    return (s.real, s.imag)\"\n        ]\n        |> fun lines => (a lines : _ i32 _) |> sm'.concat_array \"\\n\" |> sm'.replace \"__NAME__\" name\n        |> call1_ log py s\n\ninl gamma_ log py s =\n    call1_ log \"gamma_\" py s \"        s = mpmath.gamma(s)\"\n\ninl zeta_ log py s =\n    call1_ log \"zeta_\" py s \"        s = mpmath.zeta(s)\"","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl module_from_code (py : python) (code : string) : _ (bound pymodule) _ =
      inl py = join py
      inl code = code |> sm'.to_std_string |> sm'.new_c_string
      inl empty = "" |> sm'.to_std_string |> sm'.new_c_string
      !\\(code, $'"pyo3::types::PyModule::from_code(!py, &$0, &!empty, &!empty)"')
      |> resultm.map_error'' fun (x : pyerr) => x |> sm'.format'

  inl use_pyanymethods () =
      global "use pyo3::prelude::PyAnyMethods;"

  inl getattr (attr : string) (module : bound pymodule) : _ (bound pyany) _ =
      inl attr = join attr
      inl attr = attr |> sm'.as_str
      inl module = join module
      use_pyanymethods ()
      !\\(attr, $'"!module.getattr($0)"')
      |> resultm.map_error'' fun (x : pyerr) => x |> sm'.format'

  inl call forall t. (args : t) (module : bound pyany) : _ (bound pyany) _ =
      inl args = join args
      inl module = join module
      inl result : resultm.result' (bound pyany) pyerr =
          // pairs are plain Rust tuples: pyo3 takes the tuple as the call's args
          !\($'"pyo3::prelude::PyAnyMethods::call(&!module, !args, None)"') : resultm.result' (bound pyany) pyerr
      result
      |> resultm.map_error'' fun (x : pyerr) => x |> sm'.format'

  inl extract forall t. (result : bound pyany) : _ t _ =
      inl result = join result
      use_pyanymethods ()
      !\($'"!result.extract()"')
      |> resultm.map_error'' fun (x : pyerr) => x |> sm'.format'

  inl eval py code (args : pair bool (pair f64 f64)) : _ (_ f64) sm'.std_string =
      inl code =
          code
          |> module_from_code py
          |> resultm.unwrap'
      inl fn =
          code
          |> getattr "fn"
          |> resultm.unwrap'

      fn
      |> call args
      |> resultm.try'
      |> extract
      |> resultm.try'
      |> complex
      |> Ok
      |> resultm.box

  inl call1_ log py s (code : string) =
      inl code = join code

      inl s = new_pair (re s) (im s)
      inl args = new_pair log s

      eval py code args

  inl call1_ log name py s line =
      inl s = join s
      join
          ;[
              "import sys"
              "import traceback"
              "import re"
              "count = 0"
              "memory_address_pattern = re.compile(r' at 0x[0-9a-fA-F]+')"
              "def trace_calls(frame, event, arg):"
              "    global count"
              "    count += 1"
              "    if count < 200:"
              "        try:"
              "            args = { k: v for k, v in frame.f_locals.items() if frame.f_code.co_name != 'make_mpc' and k not in ['ctx'] and not callable(v) }"
              "            args_str = ', '.join([ f\"{k}={re.sub(memory_address_pattern, ' at 0x<?>', repr(v))}\" for k, v in args.items() ])"
              "            print(f\"{event}(__NAME__) / f_code.co_name: {frame.f_code.co_name} / f_locals: {args_str} / f_lineno: {frame.f_lineno} / f_code.co_filename: {frame.f_code.co_filename.split('site-packages')[-1]} / f_back.f_lineno: { '' if frame.f_back is None else frame.f_back.f_lineno } / f_back.f_code.co_filename: { '' if frame.f_back is None else frame.f_back.f_code.co_filename.split('site-packages')[-1] } / arg: {re.sub(memory_address_pattern, ' at 0x<?>', repr(arg))}\", flush=True)"
              "        except ValueError as e:"
              "            print(f'__NAME__ / e: {e}', flush=True)"
              "        return trace_calls"
              "import mpmath"
              "def fn(log, s):"
              "    global count"
              "    if log:"
              "        print(f'__NAME__ / s: {s} / count: {count}', flush=True)"
              "    s = complex(*s)"
              "    try:"
              "        if log: sys.settrace(trace_calls)"
              line
              "        if log:"
              "            sys.settrace(None)"
              "            print(f'__NAME__ / result: {s} / count: {count}', flush=True)"
              "    except ValueError as e:"
              "        if s.real == 1:"
              "            s = complex(float('inf'), 0)"
              "    return (s.real, s.imag)"
          ]
          |> fun lines => (a lines : _ i32 _) |> sm'.concat_array "\n" |> sm'.replace "__NAME__" name
          |> call1_ log py s

  inl gamma_ log py s =
      call1_ log "gamma_" py s "        s = mpmath.gamma(s)"

  inl zeta_ log py s =
      call1_ log "zeta_" py s "        s = mpmath.zeta(s)"
  """,
  timeout: 300_000
)
```

## run_test

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl run_test log (fn : (complex f64 -> complex f64) * (complex f64 -> complex f64) -> ()) =\n    inl fn_ (py : python) : resultm.result' () pyerr =\n        inl nan () =\n            !\\($'\"f64::NAN\"')\n        inl gamma__ = fun (s : complex f64) =>\n            inl result = gamma_ log py s\n            if log then\n                inl s = join s\n                !\\($'\"println\\!(\\\\\\\"gamma__ / s: {:?} / result: {:?}\\\\\\\", !s, !result)\"')\n            result |> resultm.ok' |> optionm'.unbox |> optionm'.default_value .^(nan (), nan ())\n        inl zeta__ = fun (s : complex f64) =>\n            inl result = zeta_ log py s\n\n            inl z = zeta true gamma__ s\n\n            if log then\n                inl s = join s\n                !\\($'\"println\\!(\\\\\\\"zeta__ / s: {:?} / result: {:?} / z: {:?}\\\\\\\", !s, !result, !z)\"')\n\n    //             re result - re x |> abs\n    //             |> _assert_lt 0.001\n\n    //             im result - im x |> abs\n    //             |> _assert_lt 0.001\n\n            result |> resultm.ok' |> optionm'.unbox |> optionm'.default_value .^(nan (), nan ())\n        join fn (zeta__, gamma__)\n\n        Ok ()\n        |> resultm.box\n\n    join\n        !\\($'\"pyo3::Python::initialize()\"') : ()\n\n        !\\($'\"let __run_test = pyo3::Python::attach(|py| -> pyo3::PyResult<()> { //\"')\n\n        let x' = fn_ (!\\($'\"py\"') : python)\n        // native Rust clones method arguments and PyErr isn't Clone: keep the Result in place\n        inl x' : resultm.result' () pyerr = x'\n\n        inl closure_fix = 2u8, 1u8\n        x' |> rust.fix_closure closure_fix\n\n        (!\\($'\"__run_test\"') : _ () pyerr)\n        |> resultm.unwrap'","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl run_test log (fn : (complex f64 -> complex f64) * (complex f64 -> complex f64) -> ()) =
      inl fn_ (py : python) : resultm.result' () pyerr =
          inl nan () =
              !\($'"f64::NAN"')
          inl gamma__ = fun (s : complex f64) =>
              inl result = gamma_ log py s
              if log then
                  inl s = join s
                  !\($'"println\!(\\\"gamma__ / s: {:?} / result: {:?}\\\", !s, !result)"')
              result |> resultm.ok' |> optionm'.unbox |> optionm'.default_value .^(nan (), nan ())
          inl zeta__ = fun (s : complex f64) =>
              inl result = zeta_ log py s

              inl z = zeta true gamma__ s

              if log then
                  inl s = join s
                  !\($'"println\!(\\\"zeta__ / s: {:?} / result: {:?} / z: {:?}\\\", !s, !result, !z)"')

      //             re result - re x |> abs
      //             |> _assert_lt 0.001

      //             im result - im x |> abs
      //             |> _assert_lt 0.001

              result |> resultm.ok' |> optionm'.unbox |> optionm'.default_value .^(nan (), nan ())
          join fn (zeta__, gamma__)

          Ok ()
          |> resultm.box

      join
          !\($'"pyo3::Python::initialize()"') : ()

          !\($'"let __run_test = pyo3::Python::attach(|py| -> pyo3::PyResult<()> { //"')

          let x' = fn_ (!\($'"py"') : python)
          // native Rust clones method arguments and PyErr isn't Clone: keep the Result in place
          inl x' : resultm.result' () pyerr = x'

          inl closure_fix = 2u8, 1u8
          x' |> rust.fix_closure closure_fix

          (!\($'"__run_test"') : _ () pyerr)
          |> resultm.unwrap'
  """,
  timeout: 300_000
)
```

## test_zeta_at_known_values_

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_zeta_at_known_values_ log = run_test log fun zeta, gamma =>\n    ;[\n        .^(2, 0), pi ** 2 / 6\n        .^(-1, 0), -1 / 12\n    ]\n    |> fun x => a x : _ i32 _\n    |> am.iter fun s, e =>\n        inl result = zeta s\n\n        result |> im |> _assert_eq 0\n        re result - e |> abs |> _assert_lt 0.0001","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_zeta_at_known_values_ log = run_test log fun zeta, gamma =>
      ;[
          .^(2, 0), pi ** 2 / 6
          .^(-1, 0), -1 / 12
      ]
      |> fun x => a x : _ i32 _
      |> am.iter fun s, e =>
          inl result = zeta s

          result |> im |> _assert_eq 0
          re result - e |> abs |> _assert_lt 0.0001
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_zeta_at_known_values_ true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_zeta_at_known_values_ true
  """,
  timeout: 300_000
)
```

## test_zeta_at_2_minus2

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_zeta_at_2_minus2 log = run_test log fun zeta, gamma =>\n    inl s = .^(2, -2)\n    inl result = zeta s\n\n    (re result - 0.8673) |> abs |> _assert_lt 0.001\n    (im result - 0.2750) |> abs |> _assert_lt 0.001","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_zeta_at_2_minus2 log = run_test log fun zeta, gamma =>
      inl s = .^(2, -2)
      inl result = zeta s

      (re result - 0.8673) |> abs |> _assert_lt 0.001
      (im result - 0.2750) |> abs |> _assert_lt 0.001
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_zeta_at_2_minus2 true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_zeta_at_2_minus2 true
  """,
  timeout: 300_000
)
```

## test_trivial_zero_at_negative_even___

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_trivial_zero_at_negative_even___ log = run_test log fun zeta, gamma =>\n    (join listm'.init_series -2f64 -40 -2)\n    |> listm.iter fun n =>\n        inl s = .^(n, 0)\n        inl result = zeta s\n\n        result |> re |> _assert_eq 0\n        result |> im |> _assert_eq 0","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_trivial_zero_at_negative_even___ log = run_test log fun zeta, gamma =>
      (join listm'.init_series -2f64 -40 -2)
      |> listm.iter fun n =>
          inl s = .^(n, 0)
          inl result = zeta s

          result |> re |> _assert_eq 0
          result |> im |> _assert_eq 0
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_trivial_zero_at_negative_even___ true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_trivial_zero_at_negative_even___ true
  """,
  timeout: 300_000
)
```

## test_non_trivial_zero___

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_non_trivial_zero___ log = run_test log fun zeta, gamma =>\n    ;[\n        .^(0.5, 14.134725)\n        .^(0.5, 21.022040)\n        .^(0.5, 25.010857)\n        .^(0.5, 30.424876)\n        .^(0.5, 32.935062)\n        .^(0.5, 37.586178)\n    ]\n    |> fun x => a x : _ i32 _\n    |> am.iter fun x =>\n            inl result = zeta x\n            result |> re |> abs |> _assert_lt 0.0001\n            result |> im |> abs |> _assert_lt 0.0001","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_non_trivial_zero___ log = run_test log fun zeta, gamma =>
      ;[
          .^(0.5, 14.134725)
          .^(0.5, 21.022040)
          .^(0.5, 25.010857)
          .^(0.5, 30.424876)
          .^(0.5, 32.935062)
          .^(0.5, 37.586178)
      ]
      |> fun x => a x : _ i32 _
      |> am.iter fun x =>
              inl result = zeta x
              result |> re |> abs |> _assert_lt 0.0001
              result |> im |> abs |> _assert_lt 0.0001
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_non_trivial_zero___ true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_non_trivial_zero___ true
  """,
  timeout: 300_000
)
```

## test_real_part_greater_than_one___

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_real_part_greater_than_one___ log = run_test log fun zeta, gamma =>\n    inl points = ;[ 2; 3; 4; 5; 10; 20; 50 ]\n    (a points : _ i32 _)\n    |> am.iter fun point =>\n        inl s = .^(point, 0)\n        inl result = zeta s\n        result |> re |> _assert_gt 0\n        result |> im |> _assert_eq 0","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_real_part_greater_than_one___ log = run_test log fun zeta, gamma =>
      inl points = ;[ 2; 3; 4; 5; 10; 20; 50 ]
      (a points : _ i32 _)
      |> am.iter fun point =>
          inl s = .^(point, 0)
          inl result = zeta s
          result |> re |> _assert_gt 0
          result |> im |> _assert_eq 0
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_real_part_greater_than_one___ true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_real_part_greater_than_one___ true
  """,
  timeout: 300_000
)
```

## test_zeta_at_1___

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_zeta_at_1___ log = run_test log fun zeta, gamma =>\n    inl s = .^(1, 0)\n    inl result = zeta s\n    result |> re |> _assert_eq limit.max\n    result |> im |> _assert_eq 0","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_zeta_at_1___ log = run_test log fun zeta, gamma =>
      inl s = .^(1, 0)
      inl result = zeta s
      result |> re |> _assert_eq limit.max
      result |> im |> _assert_eq 0
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_zeta_at_1___ true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_zeta_at_1___ true
  """,
  timeout: 300_000
)
```

## test_symmetry_across_real_axis___

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_symmetry_across_real_axis___ log = run_test log fun zeta, gamma =>\n    inl s = .^(2, 10)\n    inl result_positive_im = zeta s\n    inl result_negative_im = zeta .^(re s, -(im s))\n    inl conj = result_negative_im |> conj\n    result_positive_im |> re |> _assert_eq (conj |> re)\n    result_positive_im |> im |> _assert_eq (conj |> im)","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_symmetry_across_real_axis___ log = run_test log fun zeta, gamma =>
      inl s = .^(2, 10)
      inl result_positive_im = zeta s
      inl result_negative_im = zeta .^(re s, -(im s))
      inl conj = result_negative_im |> conj
      result_positive_im |> re |> _assert_eq (conj |> re)
      result_positive_im |> im |> _assert_eq (conj |> im)
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_symmetry_across_real_axis___ true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_symmetry_across_real_axis___ true
  """,
  timeout: 300_000
)
```

## test_behavior_near_origin___

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_behavior_near_origin___ log = run_test log fun zeta, gamma =>\n    inl s = .^(0.01, 0.01)\n    inl result = zeta s\n    result |> re |> _assert_lt limit.max\n    result |> im |> _assert_lt limit.max","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_behavior_near_origin___ log = run_test log fun zeta, gamma =>
      inl s = .^(0.01, 0.01)
      inl result = zeta s
      result |> re |> _assert_lt limit.max
      result |> im |> _assert_lt limit.max
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_behavior_near_origin___ true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_behavior_near_origin___ true
  """,
  timeout: 300_000
)
```

## test_imaginary_axis

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_imaginary_axis log = run_test log fun zeta, gamma =>\n    (join [ 10; 20; 30; 40; 50; 60; 70; 80; 90; 100 ])\n    |> listm.iter fun s =>\n        inl s = .^(0, s)\n        inl result = zeta s\n        result |> re |> _assert_ne 0\n        result |> im |> _assert_ne 0","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_imaginary_axis log = run_test log fun zeta, gamma =>
      (join [ 10; 20; 30; 40; 50; 60; 70; 80; 90; 100 ])
      |> listm.iter fun s =>
          inl s = .^(0, s)
          inl result = zeta s
          result |> re |> _assert_ne 0
          result |> im |> _assert_ne 0
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_imaginary_axis true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_imaginary_axis true
  """,
  timeout: 300_000
)
```

## test_critical_strip

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_critical_strip log = run_test log fun zeta, gamma =>\n    (join [\n        .^(0.5, 14.134725)\n        .^(0.75, 20.5)\n        .^(1.25, 30.1)\n        .^(0.25, 40.0)\n        .^(1.0, 50.0)\n    ])\n    |> listm.iter fun s =>\n        inl result = zeta s\n        result |> re |> _assert_ne 0\n        result |> im |> _assert_ne 0","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_critical_strip log = run_test log fun zeta, gamma =>
      (join [
          .^(0.5, 14.134725)
          .^(0.75, 20.5)
          .^(1.25, 30.1)
          .^(0.25, 40.0)
          .^(1.0, 50.0)
      ])
      |> listm.iter fun s =>
          inl result = zeta s
          result |> re |> _assert_ne 0
          result |> im |> _assert_ne 0
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_critical_strip true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_critical_strip true
  """,
  timeout: 300_000
)
```

## test_reflection_formula_for_specific_value

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_reflection_formula_for_specific_value log = run_test log fun zeta, gamma =>\n    (join [\n        .^(3, 4)\n        .^(2.5, -3.5)\n        .^(1.5, 2.5)\n        .^(0.5, 14.134725)\n    ])\n    |> listm.iter fun s =>\n        inl lhs = zeta s\n        inl reflection_coefficient =\n            (.^(2, 0) .** s)\n            .* (.^(pi, 0) .** (s .- .^(1, 0)))\n            .* (.^(pi, 0) .* s ./ .^(2, 0) |> complex_sin)\n            .* gamma (.^(1, 0) .- s)\n\n        inl one_minus_s = .^(1 - re s, -(im s))\n        inl rhs = reflection_coefficient .* zeta one_minus_s\n\n        re lhs - re rhs |> abs |> _assert_lt 0.0001\n        im lhs - im rhs |> abs |> _assert_lt 0.0001","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_reflection_formula_for_specific_value log = run_test log fun zeta, gamma =>
      (join [
          .^(3, 4)
          .^(2.5, -3.5)
          .^(1.5, 2.5)
          .^(0.5, 14.134725)
      ])
      |> listm.iter fun s =>
          inl lhs = zeta s
          inl reflection_coefficient =
              (.^(2, 0) .** s)
              .* (.^(pi, 0) .** (s .- .^(1, 0)))
              .* (.^(pi, 0) .* s ./ .^(2, 0) |> complex_sin)
              .* gamma (.^(1, 0) .- s)

          inl one_minus_s = .^(1 - re s, -(im s))
          inl rhs = reflection_coefficient .* zeta one_minus_s

          re lhs - re rhs |> abs |> _assert_lt 0.0001
          im lhs - im rhs |> abs |> _assert_lt 0.0001
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_reflection_formula_for_specific_value true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_reflection_formula_for_specific_value true
  """,
  timeout: 300_000
)
```

## test_euler_product_formula

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl test_euler_product_formula log = run_test log fun zeta, gamma =>\n    inl s_values = join [ 2; 2.5; 3; 3.5; 4; 4.5; 5 ]\n    inl primes = join [ 2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59; 61; 67; 71 ]\n    s_values\n    |> listm.iter fun s_re =>\n        inl s = .^(s_re, 0)\n        inl product =\n            (1, primes)\n            ||> listm.fold fun acc x =>\n                acc * 1 / (1 - x ** -s_re)\n\n        inl result = zeta s\n        re result - product |> abs |> _assert_lt 0.01\n        result |> im |> _assert_lt 0.01","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl test_euler_product_formula log = run_test log fun zeta, gamma =>
      inl s_values = join [ 2; 2.5; 3; 3.5; 4; 4.5; 5 ]
      inl primes = join [ 2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59; 61; 67; 71 ]
      s_values
      |> listm.iter fun s_re =>
          inl s = .^(s_re, 0)
          inl product =
              (1, primes)
              ||> listm.fold fun acc x =>
                  acc * 1 / (1 - x ** -s_re)

          inl result = zeta s
          re result - product |> abs |> _assert_lt 0.01
          result |> im |> _assert_lt 0.01
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///- --test\n///> rust -d num-complex pyo3='=0.26.0'\n\ntest_euler_product_formula true","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///- --test
  ///> rust -d num-complex pyo3='=0.26.0'

  test_euler_product_formula true
  """,
  timeout: 300_000
)
```

## graph

<!-- livebook:{"spiral_code":"mermaid"} -->

```mermaid
graph TD
    zeta("zeta()") --> convert
    zeta --> f["f()"]
    f --> mpc_f["mpc_zeta()"]
    f --> mpf_f["mpf_zeta()"]
    convert --> from_float
    from_float --> from_man_exp
    from_man_exp --> python_bitcount
    python_bitcount --> _normalize
    _normalize --> make_mpc
    make_mpc --> mpc_zeta["mpc_zeta()"]
    mpc_zeta --> mpf_zeta["mpf_zeta()"]
    mpf_zeta --> to_int
    to_int --> mpf_zeta_int["mpf_zeta_int()"]
    mpf_zeta_int --> borwein_coefficients
    borwein_coefficients --> from_man_exp_2("from_man_exp()")
    from_man_exp_2 --> python_bitcount_2("python_bitcount()")
    python_bitcount_2 --> _normalize_2("_normalize()")
    _normalize_2 --> make_mpc_2("make_mpc()")
    make_mpc_2 --> stop_trace
    mpf_zeta_int --> mpf_bernoulli
    mpf_bernoulli --> bernoulli_size
    bernoulli_size --> mpf_rdiv_int
    mpf_rdiv_int --> python_bitcount_3("python_bitcount()")
    python_bitcount_3 --> _normalize1
    _normalize1 --> from_man_exp_3("from_man_exp()")
    from_man_exp_3 --> _normalize_3("_normalize()")
    _normalize_3 --> mpf_sub
    mpf_sub --> mpf_add
    mpf_add --> mpf_neg
    mpf_neg --> _normalize1_2("_normalize1()")
    _normalize1_2 --> from_int
    from_int --> mpf_div
    mpf_div --> python_bitcount_4("python_bitcount()")
    python_bitcount_4 --> _normalize1_3("_normalize1()")
    _normalize1_3 --> make_mpc_3("make_mpc()")
    make_mpc_3 --> final_stop["stop_trace()"]
```

<!-- livebook:{"spiral_code":"mermaid"} -->

```mermaid
graph TD
    zeta_rust("zeta() - Rust") --> num_traits("num-traits")
    zeta_rust --> num_bigint("num-bigint")
    zeta_rust --> rust_decimal("rust_decimal for precision")
    zeta_rust --> error_handling("Rust Error Handling")

    num_traits --> num_traits_usage("Use for common traits")
    num_bigint --> bigint_operations("Arbitrary-precision arithmetic operations")
    rust_decimal --> decimal_operations("High-precision decimal operations")
    error_handling --> result_type("Use Result<T, E> for error handling")

    bigint_operations --> convert_rust("convert() - Rust")
    bigint_operations --> normalize_rust("_normalize() - Rust")

    convert_rust --> from_float_rust("from_float() - Rust")
    from_float_rust --> from_man_exp_rust("from_man_exp() - Rust")
    from_man_exp_rust --> bitcount_rust("bitcount() - Rust")
    bitcount_rust --> normalize_rust
    normalize_rust --> mpc_zeta_rust("mpc_zeta() - Rust")
    mpc_zeta_rust --> mpf_zeta_rust("mpf_zeta() - Rust")
    mpf_zeta_rust --> to_int_rust("to_int() - Rust")
    to_int_rust --> mpf_zeta_int_rust("mpf_zeta_int() - Rust")

    mpf_zeta_int_rust --> borwein_coefficients_rust("borwein_coefficients() - Rust")
    borwein_coefficients_rust --> from_man_exp_rust_2("from_man_exp() - Rust")
    from_man_exp_rust_2 --> bitcount_rust_2("bitcount() - Rust")
    bitcount_rust_2 --> normalize_rust_2("_normalize() - Rust")
    normalize_rust_2 --> make_mpc_rust("make_mpc() - Rust")

    mpf_zeta_int_rust --> mpf_bernoulli_rust("mpf_bernoulli() - Rust")
    mpf_bernoulli_rust --> bernoulli_size_rust("bernoulli_size() - Rust")
    bernoulli_size_rust --> mpf_rdiv_int_rust("mpf_rdiv_int() - Rust")
    mpf_rdiv_int_rust --> bitcount_rust_3("bitcount() - Rust")
    bitcount_rust_3 --> normalize1_rust("_normalize1() - Rust")
    normalize1_rust --> from_man_exp_rust_3("from_man_exp() - Rust")
    from_man_exp_rust_3 --> normalize_rust_3("_normalize() - Rust")
    normalize_rust_3 --> mpf_sub_rust("mpf_sub() - Rust")
    mpf_sub_rust --> mpf_add_rust("mpf_add() - Rust")
    mpf_add_rust --> mpf_neg_rust("mpf_neg() - Rust")
    mpf_neg_rust --> normalize1_rust_2("_normalize1() - Rust")
    normalize1_rust_2 --> from_int_rust("from_int() - Rust")
    from_int_rust --> mpf_div_rust("mpf_div() - Rust")
    mpf_div_rust --> bitcount_rust_4("bitcount() - Rust")
    bitcount_rust_4 --> normalize1_rust_3("_normalize1() - Rust")

    style zeta_rust fill:#f9f,stroke:#333,stroke-width:4px
    style num_traits fill:#bbf,stroke:#333,stroke-width:2px
    style num_bigint fill:#bbf,stroke:#333,stroke-width:2px
    style rust_decimal fill:#bbf,stroke:#333,stroke-width:2px
    style error_handling fill:#bbf,stroke:#333,stroke-width:2px
    style bigint_operations fill:#bfb,stroke:#333,stroke-width:2px
    style decimal_operations fill:#bfb,stroke:#333,stroke-width:2px
    style result_type fill:#bfb,stroke:#333,stroke-width:2px
```

## tests

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"inl tests () =\n    testing.run_tests_log {\n        test_zeta_at_known_values_\n        test_zeta_at_2_minus2\n        test_trivial_zero_at_negative_even___\n        test_non_trivial_zero___\n        test_real_part_greater_than_one___\n        test_zeta_at_1___\n        test_symmetry_across_real_axis___\n        test_behavior_near_origin___\n        test_imaginary_axis\n        test_critical_strip\n        test_reflection_formula_for_specific_value\n        test_euler_product_formula\n    }","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  inl tests () =
      testing.run_tests_log {
          test_zeta_at_known_values_
          test_zeta_at_2_minus2
          test_trivial_zero_at_negative_even___
          test_non_trivial_zero___
          test_real_part_greater_than_one___
          test_zeta_at_1___
          test_symmetry_across_real_axis___
          test_behavior_near_origin___
          test_imaginary_axis
          test_critical_strip
          test_reflection_formula_for_specific_value
          test_euler_product_formula
      }
  """,
  timeout: 300_000
)
```

<!-- livebook:{"chunks":null,"kind":"Elixir.Spiral.Kino.SmartCell","attrs":{"timeout":300,"source":"///> _\n\ninl run_main (_args : array_base string) : i32 =\n    inl value = 1i32\n    console.write_line (sm'.(++#) \"value: \" (value |> sm'.obj_to_string))\n    0i32\n\n/// Native Rust test runner (the Rust arm of `main`): runs the test called `name`, or every test when `name` is empty;\n/// 1 for an unknown name.\ninl run_native_tests (name : string) : i32 =\n    inl name = join name\n    inl run (test_name : string) (fn : bool -> ()) (found : bool) : bool =\n        if name = \"\" || name = test_name then\n            fn false\n            true\n        else found\n    inl found =\n        false\n        |> run \"test_zeta_at_known_values_\" test_zeta_at_known_values_\n        |> run \"test_zeta_at_2_minus2\" test_zeta_at_2_minus2\n        |> run \"test_trivial_zero_at_negative_even___\" test_trivial_zero_at_negative_even___\n        |> run \"test_non_trivial_zero___\" test_non_trivial_zero___\n        |> run \"test_real_part_greater_than_one___\" test_real_part_greater_than_one___\n        |> run \"test_zeta_at_1___\" test_zeta_at_1___\n        |> run \"test_symmetry_across_real_axis___\" test_symmetry_across_real_axis___\n        |> run \"test_behavior_near_origin___\" test_behavior_near_origin___\n        |> run \"test_imaginary_axis\" test_imaginary_axis\n        |> run \"test_critical_strip\" test_critical_strip\n        |> run \"test_reflection_formula_for_specific_value\" test_reflection_formula_for_specific_value\n        |> run \"test_euler_product_formula\" test_euler_product_formula\n    if found then 0i32\n    else\n        console.write_line (sm'.(++#) \"unknown test: \" name)\n        1i32\n\n/// Native Rust `#[test]` wrappers: `cargo test` runs each test through `spiral_main` on a 1 GiB-stack thread with its\n/// name in `SPIRAL_TEST_NAME` (a thread local, so the harness's parallel test threads don't share it).\ninl native_test_wrappers () =\n    global \"thread_local! { static SPIRAL_TEST_NAME: std::cell::RefCell<Option<std::rc::Rc<str>>> = const { std::cell::RefCell::new(None) }; }\"\n    global \"#[cfg(test)]\\nfn spiral_test(name: &'static str) {\\n    let code = std::thread::Builder::new().stack_size(1 << 30).spawn(move || { SPIRAL_TEST_NAME.with(|x| *x.borrow_mut() = Some(std::rc::Rc::from(name))); spiral_main() }).unwrap().join().unwrap();\\n    assert_eq!(code, 0);\\n}\"\n    global \"#[cfg(test)]\\nmod spiral_tests {\\n    macro_rules! tests { ($($name:ident),*) => { $(#[test] fn $name() { super::spiral_test(stringify!($name)) })* } }\\n    tests!(test_zeta_at_known_values_, test_zeta_at_2_minus2, test_trivial_zero_at_negative_even___, test_non_trivial_zero___, test_real_part_greater_than_one___, test_zeta_at_1___, test_symmetry_across_real_axis___, test_behavior_near_origin___, test_imaginary_axis, test_critical_strip, test_reflection_formula_for_specific_value, test_euler_product_formula);\\n}\"\n\n/// Native Rust (`--backend Rust`, see build.ps1): a bin crate whose\n/// `cargo run -- <test>` runs one test (no argument: all of them) and whose `cargo test` runs the `#[test]` wrappers.\ninl main () : () =\n    native_test_wrappers ()\n    inl name =\n        $'SPIRAL_TEST_NAME.with(|x| x.borrow().clone()).unwrap_or_else(|| Rc::<str>::from(std::env::args().nth(1).unwrap_or_default()))'\n        : string\n    inl code = run_native_tests name\n    $'if !code \\!= 0 { std::process::exit(!code) }' : ()","print_code":false},"livebook_object":"smart_cell"} -->

```elixir
Spiral.Kino.eval!(
  ~S"""
  ///> _

  inl run_main (_args : array_base string) : i32 =
      inl value = 1i32
      console.write_line (sm'.(++#) "value: " (value |> sm'.obj_to_string))
      0i32

  /// Native Rust test runner (the Rust arm of `main`): runs the test called `name`, or every test when `name` is empty;
  /// 1 for an unknown name.
  inl run_native_tests (name : string) : i32 =
      inl name = join name
      inl run (test_name : string) (fn : bool -> ()) (found : bool) : bool =
          if name = "" || name = test_name then
              fn false
              true
          else found
      inl found =
          false
          |> run "test_zeta_at_known_values_" test_zeta_at_known_values_
          |> run "test_zeta_at_2_minus2" test_zeta_at_2_minus2
          |> run "test_trivial_zero_at_negative_even___" test_trivial_zero_at_negative_even___
          |> run "test_non_trivial_zero___" test_non_trivial_zero___
          |> run "test_real_part_greater_than_one___" test_real_part_greater_than_one___
          |> run "test_zeta_at_1___" test_zeta_at_1___
          |> run "test_symmetry_across_real_axis___" test_symmetry_across_real_axis___
          |> run "test_behavior_near_origin___" test_behavior_near_origin___
          |> run "test_imaginary_axis" test_imaginary_axis
          |> run "test_critical_strip" test_critical_strip
          |> run "test_reflection_formula_for_specific_value" test_reflection_formula_for_specific_value
          |> run "test_euler_product_formula" test_euler_product_formula
      if found then 0i32
      else
          console.write_line (sm'.(++#) "unknown test: " name)
          1i32

  /// Native Rust `#[test]` wrappers: `cargo test` runs each test through `spiral_main` on a 1 GiB-stack thread with its
  /// name in `SPIRAL_TEST_NAME` (a thread local, so the harness's parallel test threads don't share it).
  inl native_test_wrappers () =
      global "thread_local! { static SPIRAL_TEST_NAME: std::cell::RefCell<Option<std::rc::Rc<str>>> = const { std::cell::RefCell::new(None) }; }"
      global "#[cfg(test)]\nfn spiral_test(name: &'static str) {\n    let code = std::thread::Builder::new().stack_size(1 << 30).spawn(move || { SPIRAL_TEST_NAME.with(|x| *x.borrow_mut() = Some(std::rc::Rc::from(name))); spiral_main() }).unwrap().join().unwrap();\n    assert_eq!(code, 0);\n}"
      global "#[cfg(test)]\nmod spiral_tests {\n    macro_rules! tests { ($($name:ident),*) => { $(#[test] fn $name() { super::spiral_test(stringify!($name)) })* } }\n    tests!(test_zeta_at_known_values_, test_zeta_at_2_minus2, test_trivial_zero_at_negative_even___, test_non_trivial_zero___, test_real_part_greater_than_one___, test_zeta_at_1___, test_symmetry_across_real_axis___, test_behavior_near_origin___, test_imaginary_axis, test_critical_strip, test_reflection_formula_for_specific_value, test_euler_product_formula);\n}"

  /// Native Rust (`--backend Rust`, see build.ps1): a bin crate whose
  /// `cargo run -- <test>` runs one test (no argument: all of them) and whose `cargo test` runs the `#[test]` wrappers.
  inl main () : () =
      native_test_wrappers ()
      inl name =
          $'SPIRAL_TEST_NAME.with(|x| x.borrow().clone()).unwrap_or_else(|| Rc::<str>::from(std::env::args().nth(1).unwrap_or_default()))'
          : string
      inl code = run_native_tests name
      $'if !code \!= 0 { std::process::exit(!code) }' : ()
  """,
  timeout: 300_000
)
```
