If / Else / Where

Instance of: operation of control flow

AKA:

Distinct from:

English:

Formalization:

\[ \]

Cites: Wikipedia ; Wikidata ; Wolfram

Code

ifelse: Conditional Element Selection

Examples:

if(TRUE){
  "A"
} else {
  "B"
}
[1] "A"
ifelse(TRUE, "A", "B" )
[1] "A"

if and if else

Examples:

Note do not use & or you will get a different result


if True:
  print("A")
else:
  print("B")
A

if False:
  print("1")
elif True:
  print("2")
else:
  print("3")
2

numpy.where You can use np.where masks as a kind of vectorized if else statement, choosing between elements from either A or B

Examples:


import numpy as np
x=np.array(True) #
np.where(x , "A", "B")
array('A', dtype='<U1')

The first option in jax is to use where statements as in the numpy example


import jax.numpy as jnp
x=jnp.array(True) #
#TypeError: Value 'A' with dtype <U1 is not a valid JAX array type. Only arrays of numeric types are supported by JAX.
WARNING:jax._src.lib.xla_bridge:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)
jnp.where(x , 1, 2) #Note jax doesn't allow string types
DeviceArray(1, dtype=int32, weak_type=True)

If doing autograd if statements have more constraints.

Control Flow * In jax, grad works through if statements unconstrained

Examples:

import jax.numpy as jnp
a=jnp.array(True)
b=jnp.array(False)
jnp.logical_and(a, b)
DeviceArray(False, dtype=bool)

https://www.w3schools.com/sql/sql_operators.asp https://www.databasestar.com/sql-boolean-data-type/#:~:text=SQL%20Server%20Boolean,TRUE%20and%200%20for%20FALSE.

library(DBI)
# Create an ephemeral in-memory RSQLite database
#con <- dbConnect(RSQLite::SQLite(), dbname = ":memory:")
#dbListTables(con)
#dbWriteTable(con, "mtcars", mtcars)
#dbListTables(con)

#Configuration failed because libpq was not found. Try installing:
#* deb: libpq-dev libssl-dev (Debian, Ubuntu, etc)
#install.packages('RPostgres')
#remotes::install_github("r-dbi/RPostgres")
#Took forever because my file permissions were broken
#pg_lsclusters
require(RPostgres)
Loading required package: RPostgres
# Connect to the default postgres database
#I had to follow these instructions and create both a username and database that matched my ubuntu name
#https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart
con <- dbConnect(RPostgres::Postgres())
SELECT TRUE AND FALSE;
1 records
?column?
FALSE
SELECT TRUE AND TRUE;
1 records
?column?
TRUE

https://pytorch.org/docs/stable/generated/torch.logical_and.html

import torch
a = torch.tensor(True)
b = torch.tensor(False)
torch.logical_and(a, b)
tensor(False)

0.0.1 Tensorflow

https://www.tensorflow.org/api_docs/python/tf/math/logical_and

import tensorflow as tf
a = tf.constant(True)
b = tf.constant(False)
tf.math.logical_and(a, b)
<tf.Tensor: shape=(), dtype=bool, numpy=False>