text:
###############################################################################
#
#   Residue.jl : generic residue rings (modulo a principal ideal)
#
###############################################################################

export ResidueRing, inv, modulus, data

###############################################################################
#
#   Data type and parent object methods
#
###############################################################################

parent_type(::Type{Res{T}}) where T <: RingElement = ResRing{T}

elem_type(::Type{ResRing{T}}) where {T <: RingElement} = Res{T}

doc"""
    base_ring{T <: RingElement}(S::Nemo.ResRing{T})
> Return the base ring $R$ of the given residue ring $S = R/(a)$.
"""
base_ring(S::Nemo.ResRing{T}) where {T <: RingElement} = S.base_ring::parent_type(T)

doc"""
    base_ring(r::Nemo.ResElem)
> Return the base ring $R$ of the residue ring $R/(a)$ that the supplied
> element $r$ belongs to.
"""
base_ring(r::Nemo.ResElem) = base_ring(parent(r))

doc"""
    parent(a::Nemo.ResElem)
> Return the parent object of the given residue element.
"""
parent(a::Nemo.ResElem) = a.parent

isdomain_type(a::Type{T}) where T <: Nemo.ResElem = false

function isexact_type(a::Type{T}) where {S <: RingElement, T <: Nemo.ResElem{S}}
   return isexact_type(S)
end

function check_parent_type(a::Nemo.ResRing{T}, b::Nemo.ResRing{T}) where {T <: RingElement}
   # exists only to check types of parents agree
end

function check_parent(a::Nemo.ResElem, b::Nemo.ResElem)
   if parent(a) != parent(b)
      check_parent_type(parent(a), parent(b))
      parent(a).modulus != parent(b).modulus && error("Incompatible moduli in residue operation") #CF: maybe extend to divisibility?
   end
end

###############################################################################
#
#   Basic manipulation
#
###############################################################################

function Base.hash(a::Nemo.ResElem, h::UInt)
   b = 0x539c1c8715c1adc2%UInt
   return xor(b, xor(hash(data(a), h), h))
end

doc"""
    modulus(R::Nemo.ResRing)
> Return the modulus $a$ of the given residue ring $S = R/(a)$.
"""
function modulus(S::Nemo.ResRing)
   return S.modulus
end

doc"""
    modulus(R::Nemo.ResRing)
> Return the modulus $a$ of the residue ring $S = R/(a)$ that the supplied
> residue $r$ belongs to.
"""
function modulus(r::Nemo.ResElem)
   return modulus(parent(r))
end

data(a::Nemo.ResElem) = a.data

doc"""
    zero(R::Nemo.ResRing)
> Return the zero element of the given residue ring, i.e. $0 \pmod{a}$ where
> $a$ is the modulus of the residue ring.
"""
zero(R::Nemo.ResRing) = R(0)

doc"""
    one(R::Nemo.ResRing)
> Return $1 \pmod{a}$ where $a$ is the modulus of the residue ring.
"""
one(R::Nemo.ResRing) = R(1)

doc"""
    iszero(a::Nemo.ResElem)
> Return `true` if the supplied element $a$ is zero in the residue ring it
> belongs to, otherwise return `false`.
"""
iszero(a::Nemo.ResElem) = iszero(data(a))

doc"""
    isone(a::Nemo.ResElem)
> Return `true` if the supplied element $a$ is one in the residue ring it
> belongs to, otherwise return `false`.
"""
isone(a::Nemo.ResElem) = isone(data(a))

doc"""
    isunit(a::Nemo.ResElem)
> Return `true` if the supplied element $a$ is invertible in the residue ring
> it belongs to, otherwise return `false`.
"""
function isunit(a::Nemo.ResElem)
   g = gcd(data(a), modulus(a))
   return isone(g)
end

deepcopy_internal(a::Nemo.ResElem, dict::ObjectIdDict) =
   parent(a)(deepcopy(data(a)))

###############################################################################
#
#   Canonicalisation
#
###############################################################################

function canonical_unit(x::Nemo.ResElem{<:Union{Integer, RingElem}})
 #the simple return x does not work
  # - if x == 0, this is not a unit
  # - if R is not a field....
  if iszero(x)
    return one(parent(x))
  end
  g = gcd(modulus(x), data(x))
  u = divexact(data(x), g)
  a, b = ppio(modulus(x), u)
  if isone(a)
    r = u
  elseif isone(b)
    r = b
  else
    r = crt(one(parent(a)), a, u, b)
  end
  return parent(x)(r)
end

###############################################################################
#
#   AbstractString I/O
#
###############################################################################

function show(io::IO, x::Nemo.ResElem)
   print(io, data(x))
end

function show(io::IO, a::Nemo.ResRing)
   print(io, "Residue ring of ", base_ring(a), " modulo ", modulus(a))
end

needs_parentheses(x::Nemo.ResElem) = needs_parentheses(data(x))

isnegative(x::Nemo.ResElem) = isnegative(data(x))

show_minus_one(::Type{Res{T}}) where {T <: RingElement} = true

###############################################################################
#
#   Unary operations
#
###############################################################################

doc"""
    -(a::Nemo.ResElem)
> Return $-a$.
"""
function -(a::Nemo.ResElem)
   parent(a)(-data(a))
end

###############################################################################
#
#   Binary operators
#
###############################################################################

doc"""
    +{T <: RingElement}(a::Nemo.ResElem{T}, b::Nemo.ResElem{T})
> Return $a + b$.
"""
function +(a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   check_parent(a, b)
   return parent(a)(data(a) + data(b))
end

doc"""
    -{T <: RingElement}(a::Nemo.ResElem{T}, b::Nemo.ResElem{T})
> Return $a - b$.
"""
function -(a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   check_parent(a, b)
   return parent(a)(data(a) - data(b))
end

doc"""
    *{T <: RingElement}(a::Nemo.ResElem{T}, b::Nemo.ResElem{T})
> Return $a\times b$.
"""
function *(a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   check_parent(a, b)
   return parent(a)(data(a) * data(b))
end

###############################################################################
#
#   Ad hoc binary operations
#
###############################################################################

doc"""
    *(a::Nemo.ResElem, b::Union{Integer, Rational, AbstractFloat})
> Return $a\times b$.
"""
*(a::Nemo.ResElem, b::Union{Integer, Rational, AbstractFloat}) = parent(a)(data(a) * b)

doc"""
    *{T <: RingElem}(a::Nemo.ResElem{T}, b::T)
> Return $a\times b$.
"""
*(a::Nemo.ResElem{T}, b::T) where {T <: RingElem} = parent(a)(data(a) * b)

doc"""
    *(a::Union{Integer, Rational, AbstractFloat}, b::Nemo.ResElem)
> Return $a\times b$.
"""
*(a::Union{Integer, Rational, AbstractFloat}, b::Nemo.ResElem) = parent(b)(a * data(b))

doc"""
    *{T <: RingElem}(a::T, b::Nemo.ResElem{T})
> Return $a\times b$.
"""
*(a::T, b::Nemo.ResElem{T}) where {T <: RingElem} = parent(b)(a * data(b))

doc"""
    +(a::Nemo.ResElem, b::Union{Integer, Rational, AbstractFloat})
> Return $a + b$.
"""
+(a::Nemo.ResElem, b::Union{Integer, Rational, AbstractFloat}) = parent(a)(data(a) + b)

doc"""
    +{T <: RingElem}(a::Nemo.ResElem{T}, b::T)
> Return $a + b$.
"""
+(a::Nemo.ResElem{T}, b::T) where {T <: RingElem} = parent(a)(data(a) + b)

doc"""
    +(a::Union{Integer, Rational, AbstractFloat}, b::Nemo.ResElem)
> Return $a + b$.
"""
+(a::Union{Integer, Rational, AbstractFloat}, b::Nemo.ResElem) = parent(b)(a + data(b))

doc"""
    +{T <: RingElem}(a::T, b::Nemo.ResElem{T})
> Return $a + b$.
"""
+(a::T, b::Nemo.ResElem{T}) where {T <: RingElem} = parent(b)(a + data(b))

doc"""
    -(a::Nemo.ResElem, b::Union{Integer, Rational, AbstractFloat})
> Return $a - b$.
"""
-(a::Nemo.ResElem, b::Union{Integer, Rational, AbstractFloat}) = parent(a)(data(a) - b)

doc"""
    -{T <: RingElem}(a::Nemo.ResElem{T}, b::T)
> Return $a - b$.
"""
-(a::Nemo.ResElem{T}, b::T) where {T <: RingElem} = parent(a)(data(a) - b)

doc"""
    -(a::Union{Integer, Rational, AbstractFloat}, b::Nemo.ResElem)
> Return $a - b$.
"""
-(a::Union{Integer, Rational, AbstractFloat}, b::Nemo.ResElem) = parent(b)(a - data(b))

doc"""
    -{T <: RingElem}(a::T, b::Nemo.ResElem{T})
> Return $a - b$.
"""
-(a::T, b::Nemo.ResElem{T}) where {T <: RingElem} = parent(b)(a - data(b))

###############################################################################
#
#   Powering
#
###############################################################################

doc"""
    ^(a::Nemo.ResElem, b::Int)
> Return $a^b$.
"""
function ^(a::Nemo.ResElem, b::Int)
   parent(a)(powmod(data(a), b, modulus(a)))
end

###############################################################################
#
#   Comparison
#
###############################################################################

doc"""
    =={T <: RingElement}(x::Nemo.ResElem{T}, y::Nemo.ResElem{T})
> Return `true` if $x == y$ arithmetically, otherwise return `false`. Recall
> that power series to different precisions may still be arithmetically
> equal to the minimum of the two precisions.
"""
function ==(a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   check_parent(a, b)
   return data(a) == data(b)
end

doc"""
    isequal{T <: RingElement}(x::Nemo.ResElem{T}, y::Nemo.ResElem{T})
> Return `true` if $x == y$ exactly, otherwise return `false`. This function is
> useful in cases where the data of the residues are inexact, e.g. power series
> Only if the power series are precisely the same, to the same precision, are
> they declared equal by this function.
"""
function isequal(a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   check_parent(a, b)
   return isequal(data(a), data(b))
end

###############################################################################
#
#   Ad hoc comparison
#
###############################################################################

doc"""
    ==(x::Nemo.ResElem, y::Union{Integer, Rational, AbstractFloat})
> Return `true` if $x == y$ arithmetically, otherwise return `false`.
"""
function ==(a::Nemo.ResElem, b::Union{Integer, Rational, AbstractFloat})
   z = base_ring(a)(b)
   return data(a) == mod(z, modulus(a))
end

doc"""
    ==(x::Union{Integer, Rational, AbstractFloat}, y::Nemo.ResElem)
> Return `true` if $x == y$ arithmetically, otherwise return `false`.
"""
function ==(a::Union{Integer, Rational, AbstractFloat}, b::Nemo.ResElem)
   z = base_ring(b)(a)
   return data(b) == mod(z, modulus(b))
end

doc"""
    =={T <: RingElem}(x::Nemo.ResElem{T}, y::T)
> Return `true` if $x == y$ arithmetically, otherwise return `false`.
"""
function ==(a::Nemo.ResElem{T}, b::T) where {T <: RingElem}
   z = base_ring(a)(b)
   return data(a) == mod(z, modulus(a))
end

doc"""
    =={T <: RingElem}(x::T, y::Nemo.ResElem{T})
> Return `true` if $x == y$ arithmetically, otherwise return `false`.
"""
function ==(a::T, b::Nemo.ResElem{T}) where {T <: RingElem}
   z = base_ring(b)(a)
   return data(b) == mod(z, modulus(b))
end

###############################################################################
#
#   Inversion
#
###############################################################################

doc"""
    inv(a::Nemo.ResElem)
> Return the inverse of the element $a$ in the residue ring. If an impossible
> inverse is encountered, an exception is raised.
"""
function inv(a::Nemo.ResElem)
   g, ainv = gcdinv(data(a), modulus(a))
   if g != 1
      error("Impossible inverse in inv")
   end
   return parent(a)(ainv)
end

###############################################################################
#
#   Exact division
#
###############################################################################

doc"""
    divexact{T <: RingElement}(a::Nemo.ResElem{T}, b::Nemo.ResElem{T})
> Return $a/b$ where the quotient is expected to be exact.
"""
function divexact(a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   check_parent(a, b)
   fl, q = divides(a, b)
   if !fl
      error("Impossible inverse in divexact")
   end
   return q
end

function divides(a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   check_parent(a, b)
   iszero(b) && error("Division by zero in divides")
   if iszero(a)
      return true, a
   end
   A = data(a)
   B = data(b)
   R = parent(a)
   m = modulus(R)
   gb = gcd(B, m)
   ub = divexact(B, gb)
   q, r = divrem(A, gb)
   if !iszero(r)
     return false, b
   end
   _, x = ppio(m, ub)
   rs = R(q*invmod(ub, x))
   return true, rs
end

###############################################################################
#
#   GCD
#
###############################################################################

doc"""
    gcd{T <: RingElement}(a::Nemo.ResElem{T}, b::Nemo.ResElem{T})
> Return a greatest common divisor of $a$ and $b$ if one exists. This is done
> by taking the greatest common divisor of the data associated with the
> supplied residues and taking its greatest common divisor with the modulus.
"""
function gcd(a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   check_parent(a, b)
   return parent(a)(gcd(gcd(data(a), modulus(a)), data(b)))
end

###############################################################################
#
#   Unsafe functions
#
###############################################################################

function zero!(a::Nemo.ResElem{T}) where {T <: RingElement}
   a.data = zero!(a.data)
   return a
end

function mul!(c::Nemo.ResElem{T}, a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   c.data = mod(data(a)*data(b), modulus(a))
   return c
end

function addeq!(c::Nemo.ResElem{T}, a::Nemo.ResElem{T}) where {T <: RingElement}
   c.data = mod(c.data + data(a), modulus(a))
   return c
end

function add!(c::Nemo.ResElem{T}, a::Nemo.ResElem{T}, b::Nemo.ResElem{T}) where {T <: RingElement}
   c.data = mod(data(a) + data(b), modulus(a))
   return c
end

###############################################################################
#
#   Random functions
#
###############################################################################

function rand(S::Nemo.ResRing{T}, v...) where {T <: RingElement}
   R = base_ring(S)
   return S(rand(R, v...))
end

###############################################################################
#
#   Promotion rules
#
###############################################################################

promote_rule(::Type{Res{T}}, ::Type{Res{T}}) where T <: RingElement = Res{T}

function promote_rule(::Type{Res{T}}, ::Type{U}) where {T <: RingElement, U <: RingElement}
   promote_rule(T, U) == T ? Res{T} : Union{}
end

###############################################################################
#
#   Parent object call overloading
#
###############################################################################

function (a::ResRing{T})(b::RingElement) where {T <: RingElement}
   return a(base_ring(a)(b))
end

function (a::ResRing{T})() where {T <: RingElement}
   z = Res{T}(zero(base_ring(a)))
   z.parent = a
   return z
end

function (a::ResRing{T})(b::Integer) where {T <: RingElement}
   z = Res{T}(mod(base_ring(a)(b), modulus(a)))
   z.parent = a
   return z
end

function (a::ResRing{T})(b::T) where {T <: RingElem}
   base_ring(a) != parent(b) && error("Operation on incompatible objects")
   z = Res{T}(mod(b, modulus(a)))
   z.parent = a
   return z
end

function (a::ResRing{T})(b::Nemo.ResElem{T}) where {T <: RingElement}
   a != parent(b) && error("Operation on incompatible objects")
   return b
end

###############################################################################
#
#   ResidueRing constructor
#
###############################################################################

doc"""
    ResidueRing{T <: RingElement}(R::Nemo.Ring, a::RingElement; cached::Bool=true)
> Create the residue ring $R/(a)$ where $a$ is an element of the ring $R$. We
> require $a \neq 0$. If `cached == true` (the default) then the resulting
> residue ring parent object is cached and returned for any subsequent calls
> to the constructor with the same base ring $R$ and element $a$.
"""
function ResidueRing(R::Nemo.Ring, a::RingElement; cached::Bool = true)
   iszero(a) && throw(DivideError())
   T = elem_type(R)

   return ResRing{T}(R(a), cached)
end


text:
export BrickletSilentStepperV2SpeedRamping
struct BrickletSilentStepperV2SpeedRamping
    acceleration::Integer
    deacceleration::Integer
end

export BrickletSilentStepperV2StepConfiguration
struct BrickletSilentStepperV2StepConfiguration
    step_resolution::Integer
    interpolation::Bool
end

export BrickletSilentStepperV2BasicConfiguration
struct BrickletSilentStepperV2BasicConfiguration
    standstill_current::Integer
    motor_run_current::Integer
    standstill_delay_time::Integer
    power_down_time::Integer
    stealth_threshold::Integer
    coolstep_threshold::Integer
    classic_threshold::Integer
    high_velocity_chopper_mode::Bool
end

export BrickletSilentStepperV2SpreadcycleConfiguration
struct BrickletSilentStepperV2SpreadcycleConfiguration
    slow_decay_duration::Integer
    enable_random_slow_decay::Bool
    fast_decay_duration::Integer
    hysteresis_start_value::Integer
    hysteresis_end_value::Integer
    sine_wave_offset::Integer
    chopper_mode::Integer
    comparator_blank_time::Integer
    fast_decay_without_comparator::Bool
end

export BrickletSilentStepperV2StealthConfiguration
struct BrickletSilentStepperV2StealthConfiguration
    enable_stealth::Bool
    amplitude::Integer
    gradient::Integer
    enable_autoscale::Bool
    force_symmetric::Bool
    freewheel_mode::Integer
end

export BrickletSilentStepperV2CoolstepConfiguration
struct BrickletSilentStepperV2CoolstepConfiguration
    minimum_stallguard_value::Integer
    maximum_stallguard_value::Integer
    current_up_step_width::Integer
    current_down_step_width::Integer
    minimum_current::Integer
    stallguard_threshold_value::Integer
    stallguard_mode::Integer
end

export BrickletSilentStepperV2MiscConfiguration
struct BrickletSilentStepperV2MiscConfiguration
    disable_short_to_ground_protection::Bool
    synchronize_phase_frequency::Integer
end

export BrickletSilentStepperV2DriverStatus
struct BrickletSilentStepperV2DriverStatus
    open_load::Integer
    short_to_ground::Integer
    over_temperature::Integer
    motor_stalled::Bool
    actual_motor_current::Integer
    full_step_active::Bool
    stallguard_result::Integer
    stealth_voltage_amplitude::Integer
end

export BrickletSilentStepperV2AllData
struct BrickletSilentStepperV2AllData
    current_velocity::Integer
    current_position::Integer
    remaining_steps::Integer
    input_voltage::Integer
    current_consumption::Integer
end

export BrickletSilentStepperV2GPIOConfiguration
struct BrickletSilentStepperV2GPIOConfiguration
    debounce::Integer
    stop_deceleration::Integer
end

export BrickletSilentStepperV2SPITFPErrorCount
struct BrickletSilentStepperV2SPITFPErrorCount
    error_count_ack_checksum::Integer
    error_count_message_checksum::Integer
    error_count_frame::Integer
    error_count_overflow::Integer
end

export BrickletSilentStepperV2Identity
struct BrickletSilentStepperV2Identity
    uid::String
    connected_uid::String
    position::Char
    hardware_version::Vector{Integer}
    firmware_version::Vector{Integer}
    device_identifier::Integer
end

export BrickletSilentStepperV2
"""
Silently drives one bipolar stepper motor with up to 46V and 1.6A per phase
"""
mutable struct BrickletSilentStepperV2 <: TinkerforgeDevice
    ipcon::IPConnection
    deviceInternal::PyObject

    """
    Creates an object with the unique device ID *uid* and adds it to
    the IP Connection *ipcon*.
    """
    function BrickletSilentStepperV2(uid::String, ipcon::IPConnection)
        package = pyimport("tinkerforge.bricklet_silent_stepper_v2")
        deviceInternal = package.BrickletSilentStepperV2(uid, ipcon.ipconInternal)

        return new(ipcon, deviceInternal)
    end
end

export set_max_velocity
"""
    $(SIGNATURES)

Sets the maximum velocity of the stepper motor.
This function does *not* start the motor, it merely sets the maximum
velocity the stepper motor is accelerated to. To get the motor running use
either :func:`Set Target Position`, :func:`Set Steps`, :func:`Drive Forward` or
:func:`Drive Backward`.
"""
function set_max_velocity(device::BrickletSilentStepperV2, velocity)
    device.deviceInternal.set_max_velocity(velocity)
end

export get_max_velocity
"""
    $(SIGNATURES)

Returns the velocity as set by :func:`Set Max Velocity`.
"""
function get_max_velocity(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_max_velocity()
end

export get_current_velocity
"""
    $(SIGNATURES)

Returns the *current* velocity of the stepper motor.
"""
function get_current_velocity(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_current_velocity()
end

export set_speed_ramping
"""
    $(SIGNATURES)

Sets the acceleration and deacceleration of the stepper motor.
An acceleration of 1000 means, that
every second the velocity is increased by 1000 *steps/s*.

For example: If the current velocity is 0 and you want to accelerate to a
velocity of 8000 *steps/s* in 10 seconds, you should set an acceleration
of 800 *steps/s²*.

An acceleration/deacceleration of 0 means instantaneous
acceleration/deacceleration (not recommended)
"""
function set_speed_ramping(device::BrickletSilentStepperV2, acceleration, deacceleration)
    device.deviceInternal.set_speed_ramping(acceleration, deacceleration)
end

export get_speed_ramping
"""
    $(SIGNATURES)

Returns the acceleration and deacceleration as set by
:func:`Set Speed Ramping`.
"""
function get_speed_ramping(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_speed_ramping()
end

export full_brake
"""
    $(SIGNATURES)

Executes an active full brake.

.. warning::
 This function is for emergency purposes,
 where an immediate brake is necessary. Depending on the current velocity and
 the strength of the motor, a full brake can be quite violent.

Call :func:`Stop` if you just want to stop the motor.
"""
function full_brake(device::BrickletSilentStepperV2)
    device.deviceInternal.full_brake()
end

export set_current_position
"""
    $(SIGNATURES)

Sets the current steps of the internal step counter. This can be used to
set the current position to 0 when some kind of starting position
is reached (e.g. when a CNC machine reaches a corner).
"""
function set_current_position(device::BrickletSilentStepperV2, position)
    device.deviceInternal.set_current_position(position)
end

export get_current_position
"""
    $(SIGNATURES)

Returns the current position of the stepper motor in steps. On startup
the position is 0. The steps are counted with all possible driving
functions (:func:`Set Target Position`, :func:`Set Steps`, :func:`Drive Forward` or
:func:`Drive Backward`). It also is possible to reset the steps to 0 or
set them to any other desired value with :func:`Set Current Position`.
"""
function get_current_position(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_current_position()
end

export set_target_position
"""
    $(SIGNATURES)

Sets the target position of the stepper motor in steps. For example,
if the current position of the motor is 500 and :func:`Set Target Position` is
called with 1000, the stepper motor will drive 500 steps forward. It will
use the velocity, acceleration and deacceleration as set by
:func:`Set Max Velocity` and :func:`Set Speed Ramping`.

A call of :func:`Set Target Position` with the parameter *x* is equivalent to
a call of :func:`Set Steps` with the parameter
(*x* - :func:`Get Current Position`).
"""
function set_target_position(device::BrickletSilentStepperV2, position)
    device.deviceInternal.set_target_position(position)
end

export get_target_position
"""
    $(SIGNATURES)

Returns the last target position as set by :func:`Set Target Position`.
"""
function get_target_position(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_target_position()
end

export set_steps
"""
    $(SIGNATURES)

Sets the number of steps the stepper motor should run. Positive values
will drive the motor forward and negative values backward.
The velocity, acceleration and deacceleration as set by
:func:`Set Max Velocity` and :func:`Set Speed Ramping` will be used.
"""
function set_steps(device::BrickletSilentStepperV2, steps)
    device.deviceInternal.set_steps(steps)
end

export get_steps
"""
    $(SIGNATURES)

Returns the last steps as set by :func:`Set Steps`.
"""
function get_steps(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_steps()
end

export get_remaining_steps
"""
    $(SIGNATURES)

Returns the remaining steps of the last call of :func:`Set Steps`.
For example, if :func:`Set Steps` is called with 2000 and
:func:`Get Remaining Steps` is called after the motor has run for 500 steps,
it will return 1500.
"""
function get_remaining_steps(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_remaining_steps()
end

export set_step_configuration
"""
    $(SIGNATURES)

Sets the step resolution from full-step up to 1/256-step.

If interpolation is turned on, the Silent Stepper Bricklet 2.0 will always interpolate
your step inputs as 1/256-step. If you use full-step mode with interpolation, each
step will generate 256 1/256 steps.

For maximum torque use full-step without interpolation. For maximum resolution use
1/256-step. Turn interpolation on to make the Stepper driving less noisy.

If you often change the speed with high acceleration you should turn the
interpolation off.
"""
function set_step_configuration(device::BrickletSilentStepperV2, step_resolution, interpolation)
    device.deviceInternal.set_step_configuration(step_resolution, interpolation)
end

export get_step_configuration
"""
    $(SIGNATURES)

Returns the step mode as set by :func:`Set Step Configuration`.
"""
function get_step_configuration(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_step_configuration()
end

export drive_forward
"""
    $(SIGNATURES)

Drives the stepper motor forward until :func:`Drive Backward` or
:func:`Stop` is called. The velocity, acceleration and deacceleration as
set by :func:`Set Max Velocity` and :func:`Set Speed Ramping` will be used.
"""
function drive_forward(device::BrickletSilentStepperV2)
    device.deviceInternal.drive_forward()
end

export drive_backward
"""
    $(SIGNATURES)

Drives the stepper motor backward until :func:`Drive Forward` or
:func:`Stop` is triggered. The velocity, acceleration and deacceleration as
set by :func:`Set Max Velocity` and :func:`Set Speed Ramping` will be used.
"""
function drive_backward(device::BrickletSilentStepperV2)
    device.deviceInternal.drive_backward()
end

export stop
"""
    $(SIGNATURES)

Stops the stepper motor with the deacceleration as set by
:func:`Set Speed Ramping`.
"""
function stop(device::BrickletSilentStepperV2)
    device.deviceInternal.stop()
end

export get_input_voltage
"""
    $(SIGNATURES)

Returns the external input voltage. The external input voltage is
given via the black power input connector on the Silent Stepper Bricklet 2.0.

If there is an external input voltage and a stack input voltage, the motor
will be driven by the external input voltage. If there is only a stack
voltage present, the motor will be driven by this voltage.

.. warning::
 This means, if you have a high stack voltage and a low external voltage,
 the motor will be driven with the low external voltage. If you then remove
 the external connection, it will immediately be driven by the high
 stack voltage
"""
function get_input_voltage(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_input_voltage()
end

export set_motor_current
"""
    $(SIGNATURES)

Sets the current with which the motor will be driven.

.. warning::
 Do not set this value above the specifications of your stepper motor.
 Otherwise it may damage your motor.
"""
function set_motor_current(device::BrickletSilentStepperV2, current)
    device.deviceInternal.set_motor_current(current)
end

export get_motor_current
"""
    $(SIGNATURES)

Returns the current as set by :func:`Set Motor Current`.
"""
function get_motor_current(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_motor_current()
end

export set_enabled
"""
    $(SIGNATURES)

Enables/Disables the driver chip. The driver parameters can be configured (maximum velocity,
acceleration, etc) before it is enabled.

.. warning::
 Disabling the driver chip while the motor is still turning can damage the
 driver chip. The motor should be stopped calling :func:`Stop` function
 before disabling the motor power. The :func:`Stop` function will **not**
 wait until the motor is actually stopped. You have to explicitly wait for the
 appropriate time after calling the :func:`Stop` function before calling
 the :func:`Set Enabled` with false function.
"""
function set_enabled(device::BrickletSilentStepperV2, enabled)
    device.deviceInternal.set_enabled(enabled)
end

export get_enabled
"""
    $(SIGNATURES)

Returns *true* if the stepper driver is enabled, *false* otherwise.
"""
function get_enabled(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_enabled()
end

export set_basic_configuration
"""
    $(SIGNATURES)

Sets the basic configuration parameters for the different modes (Stealth, Coolstep, Classic).

* Standstill Current: This value can be used to lower the current during stand still. This might
  be reasonable to reduce the heating of the motor and the Bricklet 2.0. When the motor is in standstill
  the configured motor phase current will be driven until the configured
  Power Down Time is elapsed. After that the phase current will be reduced to the standstill
  current. The elapsed time for this reduction can be configured with the Standstill Delay Time.
  The maximum allowed value is the configured maximum motor current
  (see :func:`Set Motor Current`).

* Motor Run Current: The value sets the motor current when the motor is running.
  Use a value of at least one half of the global maximum motor current for a good
  microstep performance. The maximum allowed value is the current
  motor current. The API maps the entered value to 1/32 ... 32/32 of the maximum
  motor current. This value should be used to change the motor current during motor movement,
  whereas the global maximum motor current should not be changed while the motor is moving
  (see :func:`Set Motor Current`).

* Standstill Delay Time: Controls the duration for motor power down after a motion
  as soon as standstill is detected and the Power Down Time is expired. A high Standstill Delay
  Time results in a smooth transition that avoids motor jerk during power down.

* Power Down Time: Sets the delay time after a stand still.

* Stealth Threshold: Sets the upper threshold for Stealth mode.
  If the velocity of the motor goes above this value, Stealth mode is turned
  off. Otherwise it is turned on. In Stealth mode the torque declines with high speed.

* Coolstep Threshold: Sets the lower threshold for Coolstep mode.
  The Coolstep Threshold needs to be above the Stealth Threshold.

* Classic Threshold: Sets the lower threshold for classic mode.
  In classic mode the stepper becomes more noisy, but the torque is maximized.

* High Velocity Chopper Mode: If High Velocity Chopper Mode is enabled, the stepper control
  is optimized to run the stepper motors at high velocities.

If you want to use all three thresholds make sure that
Stealth Threshold < Coolstep Threshold < Classic Threshold.
"""
function set_basic_configuration(device::BrickletSilentStepperV2, standstill_current, motor_run_current, standstill_delay_time, power_down_time, stealth_threshold, coolstep_threshold, classic_threshold, high_velocity_chopper_mode)
    device.deviceInternal.set_basic_configuration(standstill_current, motor_run_current, standstill_delay_time, power_down_time, stealth_threshold, coolstep_threshold, classic_threshold, high_velocity_chopper_mode)
end

export get_basic_configuration
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Basic Configuration`.
"""
function get_basic_configuration(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_basic_configuration()
end

export set_spreadcycle_configuration
"""
    $(SIGNATURES)

Note: If you don't know what any of this means you can very likely keep all of
the values as default!

Sets the Spreadcycle configuration parameters. Spreadcycle is a chopper algorithm which actively
controls the motor current flow. More information can be found in the TMC2130 datasheet on page
47 (7 spreadCycle and Classic Chopper).

* Slow Decay Duration: Controls duration of off time setting of slow decay phase.
  0 = driver disabled, all bridges off. Use 1 only with Comparator Blank time >= 2.

* Enable Random Slow Decay: Set to false to fix chopper off time as set by Slow Decay Duration.
  If you set it to true, Decay Duration is randomly modulated.

* Fast Decay Duration: Sets the fast decay duration. This parameters is
  only used if the Chopper Mode is set to Fast Decay.

* Hysteresis Start Value: Sets the hysteresis start value. This parameter is
  only used if the Chopper Mode is set to Spread Cycle.

* Hysteresis End Value: Sets the hysteresis end value. This parameter is
  only used if the Chopper Mode is set to Spread Cycle.

* Sine Wave Offset: Sets the sine wave offset. This parameters is
  only used if the Chopper Mode is set to Fast Decay. 1/512 of the value becomes added to the absolute
  value of the sine wave.

* Chopper Mode: 0 = Spread Cycle, 1 = Fast Decay.

* Comparator Blank Time: Sets the blank time of the comparator. Available values are

  * 0 = 16 clocks,
  * 1 = 24 clocks,
  * 2 = 36 clocks and
  * 3 = 54 clocks.

  A value of 1 or 2 is recommended for most applications.

* Fast Decay Without Comparator: If set to true the current comparator usage for termination of the
  fast decay cycle is disabled.
"""
function set_spreadcycle_configuration(device::BrickletSilentStepperV2, slow_decay_duration, enable_random_slow_decay, fast_decay_duration, hysteresis_start_value, hysteresis_end_value, sine_wave_offset, chopper_mode, comparator_blank_time, fast_decay_without_comparator)
    device.deviceInternal.set_spreadcycle_configuration(slow_decay_duration, enable_random_slow_decay, fast_decay_duration, hysteresis_start_value, hysteresis_end_value, sine_wave_offset, chopper_mode, comparator_blank_time, fast_decay_without_comparator)
end

export get_spreadcycle_configuration
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Basic Configuration`.
"""
function get_spreadcycle_configuration(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_spreadcycle_configuration()
end

export set_stealth_configuration
"""
    $(SIGNATURES)

Note: If you don't know what any of this means you can very likely keep all of
the values as default!

Sets the configuration relevant for Stealth mode.

* Enable Stealth: If set to true the stealth mode is enabled, if set to false the
  stealth mode is disabled, even if the speed is below the threshold set in :func:`Set Basic Configuration`.

* Amplitude: If autoscale is disabled, the PWM amplitude is scaled by this value. If autoscale is enabled,
  this value defines the maximum PWM amplitude change per half wave.

* Gradient: If autoscale is disabled, the PWM gradient is scaled by this value. If autoscale is enabled,
  this value defines the maximum PWM gradient. With autoscale a value above 64 is recommended,
  otherwise the regulation might not be able to measure the current.

* Enable Autoscale: If set to true, automatic current control is used. Otherwise the user defined
  amplitude and gradient are used.

* Force Symmetric: If true, A symmetric PWM cycle is enforced. Otherwise the PWM value may change within each
  PWM cycle.

* Freewheel Mode: The freewheel mode defines the behavior in stand still if the Standstill Current
  (see :func:`Set Basic Configuration`) is set to 0.
"""
function set_stealth_configuration(device::BrickletSilentStepperV2, enable_stealth, amplitude, gradient, enable_autoscale, force_symmetric, freewheel_mode)
    device.deviceInternal.set_stealth_configuration(enable_stealth, amplitude, gradient, enable_autoscale, force_symmetric, freewheel_mode)
end

export get_stealth_configuration
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Stealth Configuration`.
"""
function get_stealth_configuration(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_stealth_configuration()
end

export set_coolstep_configuration
"""
    $(SIGNATURES)

Note: If you don't know what any of this means you can very likely keep all of
the values as default!

Sets the configuration relevant for Coolstep.

* Minimum Stallguard Value: If the Stallguard result falls below this value*32, the motor current
  is increased to reduce motor load angle. A value of 0 turns Coolstep off.

* Maximum Stallguard Value: If the Stallguard result goes above
  (Min Stallguard Value + Max Stallguard Value + 1) * 32, the motor current is decreased to save
  energy.

* Current Up Step Width: Sets the up step increment per Stallguard value. The value range is 0-3,
  corresponding to the increments 1, 2, 4 and 8.

* Current Down Step Width: Sets the down step decrement per Stallguard value. The value range is 0-3,
  corresponding to the decrements 1, 2, 8 and 16.

* Minimum Current: Sets the minimum current for Coolstep current control. You can choose between
  half and quarter of the run current.

* Stallguard Threshold Value: Sets the level for stall output (see :func:`Get Driver Status`).
  A lower value gives a higher sensitivity. You have to find a suitable value for your
  motor by trial and error, 0 works for most motors.

* Stallguard Mode: Set to 0 for standard resolution or 1 for filtered mode. In filtered mode the Stallguard
  signal will be updated every four full-steps.
"""
function set_coolstep_configuration(device::BrickletSilentStepperV2, minimum_stallguard_value, maximum_stallguard_value, current_up_step_width, current_down_step_width, minimum_current, stallguard_threshold_value, stallguard_mode)
    device.deviceInternal.set_coolstep_configuration(minimum_stallguard_value, maximum_stallguard_value, current_up_step_width, current_down_step_width, minimum_current, stallguard_threshold_value, stallguard_mode)
end

export get_coolstep_configuration
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Coolstep Configuration`.
"""
function get_coolstep_configuration(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_coolstep_configuration()
end

export set_misc_configuration
"""
    $(SIGNATURES)

Note: If you don't know what any of this means you can very likely keep all of
the values as default!

Sets miscellaneous configuration parameters.

* Disable Short To Ground Protection: Set to false to enable short to ground protection, otherwise
  it is disabled.

* Synchronize Phase Frequency: With this parameter you can synchronize the chopper for both phases
  of a two phase motor to avoid the occurrence of a beat. The value range is 0-15. If set to 0,
  the synchronization is turned off. Otherwise the synchronization is done through the formula
  f_sync = f_clk/(value*64). In Classic Mode the synchronization is automatically switched off.
  f_clk is 12.8MHz.
"""
function set_misc_configuration(device::BrickletSilentStepperV2, disable_short_to_ground_protection, synchronize_phase_frequency)
    device.deviceInternal.set_misc_configuration(disable_short_to_ground_protection, synchronize_phase_frequency)
end

export get_misc_configuration
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Misc Configuration`.
"""
function get_misc_configuration(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_misc_configuration()
end

export set_error_led_config
"""
    $(SIGNATURES)

Configures the error LED to be either turned off, turned on, blink in
heartbeat mode or show an error.

If the LED is configured to show errors it has three different states:

* Off: No error present.
* 250ms interval blink: Overtemperature warning.
* 1s interval blink: Input voltage too small.
* full red: motor disabled because of short to ground in phase a or b or because of overtemperature.
"""
function set_error_led_config(device::BrickletSilentStepperV2, config)
    device.deviceInternal.set_error_led_config(config)
end

export get_error_led_config
"""
    $(SIGNATURES)

Returns the LED configuration as set by :func:`Set Error LED Config`
"""
function get_error_led_config(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_error_led_config()
end

export get_driver_status
"""
    $(SIGNATURES)

Returns the current driver status.

* Open Load: Indicates if an open load is present on phase A, B or both. This could mean that there is a problem
  with the wiring of the motor. False detection can occur in fast motion as well as during stand still.

* Short To Ground: Indicates if a short to ground is present on phase A, B or both. If this is detected the driver
  automatically becomes disabled and stays disabled until it is enabled again manually.

* Over Temperature: The over temperature indicator switches to "Warning" if the driver IC warms up. The warning flag
  is expected during long duration stepper uses. If the temperature limit is reached the indicator switches
  to "Limit". In this case the driver becomes disabled until it cools down again.

* Motor Stalled: Is true if a motor stall was detected.

* Actual Motor Current: Indicates the actual current control scaling as used in Coolstep mode.
  It represents a multiplier of 1/32 to 32/32 of the
  ``Motor Run Current`` as set by :func:`Set Basic Configuration`. Example: If a ``Motor Run Current``
  of 1000mA was set and the returned value is 15, the ``Actual Motor Current`` is 16/32*1000mA = 500mA.

* Stallguard Result: Indicates the load of the motor. A lower value signals a higher load. Per trial and error
  you can find out which value corresponds to a suitable torque for the velocity used in your application.
  After that you can use this threshold value to find out if a motor stall becomes probable and react on it (e.g.
  decrease velocity).
  During stand still this value can not be used for stall detection, it shows the chopper on-time for motor coil A.

* Stealth Voltage Amplitude: Shows the actual PWM scaling. In Stealth mode it can be used to detect motor load and
  stall if autoscale is enabled (see :func:`Set Stealth Configuration`).
"""
function get_driver_status(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_driver_status()
end

export set_minimum_voltage
"""
    $(SIGNATURES)

Sets the minimum voltage, below which the :cb:`Under Voltage` callback
is triggered. The minimum possible value that works with the Silent Stepper
Bricklet 2.0 is 8V.
You can use this function to detect the discharge of a battery that is used
to drive the stepper motor. If you have a fixed power supply, you likely do
not need this functionality.
"""
function set_minimum_voltage(device::BrickletSilentStepperV2, voltage)
    device.deviceInternal.set_minimum_voltage(voltage)
end

export get_minimum_voltage
"""
    $(SIGNATURES)

Returns the minimum voltage as set by :func:`Set Minimum Voltage`.
"""
function get_minimum_voltage(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_minimum_voltage()
end

export set_time_base
"""
    $(SIGNATURES)

Sets the time base of the velocity and the acceleration of the Silent Stepper
Bricklet 2.0.

For example, if you want to make one step every 1.5 seconds, you can set
the time base to 15 and the velocity to 10. Now the velocity is
10steps/15s = 1steps/1.5s.
"""
function set_time_base(device::BrickletSilentStepperV2, time_base)
    device.deviceInternal.set_time_base(time_base)
end

export get_time_base
"""
    $(SIGNATURES)

Returns the time base as set by :func:`Set Time Base`.
"""
function get_time_base(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_time_base()
end

export get_all_data
"""
    $(SIGNATURES)

Returns the following parameters: The current velocity,
the current position, the remaining steps, the stack voltage, the external
voltage and the current consumption of the stepper motor.

The current consumption is calculated by multiplying the ``Actual Motor Current``
value (see :func:`Set Basic Configuration`) with the ``Motor Run Current``
(see :func:`Get Driver Status`). This is an internal calculation of the
driver, not an independent external measurement.

The current consumption calculation was broken up to firmware 2.0.1, it is fixed
since firmware 2.0.2.

There is also a callback for this function, see :cb:`All Data` callback.
"""
function get_all_data(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_all_data()
end

export set_all_callback_configuration
"""
    $(SIGNATURES)

Sets the period with which the :cb:`All Data` callback is triggered
periodically. A value of 0 turns the callback off.
"""
function set_all_callback_configuration(device::BrickletSilentStepperV2, period)
    device.deviceInternal.set_all_callback_configuration(period)
end

export get_all_data_callback_configuraton
"""
    $(SIGNATURES)

Returns the period as set by :func:`Set All Callback Configuration`.
"""
function get_all_data_callback_configuraton(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_all_data_callback_configuraton()
end

export set_gpio_configuration
"""
    $(SIGNATURES)

Sets the GPIO configuration for the given channel.
You can configure a debounce and the deceleration that is used if the action is
configured as ``normal stop``. See :func:`Set GPIO Action`.
"""
function set_gpio_configuration(device::BrickletSilentStepperV2, channel, debounce, stop_deceleration)
    device.deviceInternal.set_gpio_configuration(channel, debounce, stop_deceleration)
end

export get_gpio_configuration
"""
    $(SIGNATURES)

Returns the GPIO configuration for a channel as set by :func:`Set GPIO Configuration`.
"""
function get_gpio_configuration(device::BrickletSilentStepperV2, channel)
    return device.deviceInternal.get_gpio_configuration(channel)
end

export set_gpio_action
"""
    $(SIGNATURES)

Sets the GPIO action for the given channel.

The action can be a normal stop, a full brake or a callback. Each for a rising
edge or falling edge. The actions are a bitmask they can be used at the same time.
You can for example trigger a full brake and a callback at the same time or for
rising and falling edge.

The deceleration speed for the normal stop can be configured with
:func:`Set GPIO Configuration`.
"""
function set_gpio_action(device::BrickletSilentStepperV2, channel, action)
    device.deviceInternal.set_gpio_action(channel, action)
end

export get_gpio_action
"""
    $(SIGNATURES)

Returns the GPIO action for a channel as set by :func:`Set GPIO Action`.
"""
function get_gpio_action(device::BrickletSilentStepperV2, channel)
    return device.deviceInternal.get_gpio_action(channel)
end

export get_gpio_state
"""
    $(SIGNATURES)

Returns the GPIO state for both channels. True if the state is ``high`` and
false if the state is ``low``.
"""
function get_gpio_state(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_gpio_state()
end

export get_spitfp_error_count
"""
    $(SIGNATURES)

Returns the error count for the communication between Brick and Bricklet.

The errors are divided into

* ACK checksum errors,
* message checksum errors,
* framing errors and
* overflow errors.

The errors counts are for errors that occur on the Bricklet side. All
Bricks have a similar function that returns the errors on the Brick side.
"""
function get_spitfp_error_count(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_spitfp_error_count()
end

export set_bootloader_mode
"""
    $(SIGNATURES)

Sets the bootloader mode and returns the status after the requested
mode change was instigated.

You can change from bootloader mode to firmware mode and vice versa. A change
from bootloader mode to firmware mode will only take place if the entry function,
device identifier and CRC are present and correct.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function set_bootloader_mode(device::BrickletSilentStepperV2, mode)
    return device.deviceInternal.set_bootloader_mode(mode)
end

export get_bootloader_mode
"""
    $(SIGNATURES)

Returns the current bootloader mode, see :func:`Set Bootloader Mode`.
"""
function get_bootloader_mode(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_bootloader_mode()
end

export set_write_firmware_pointer
"""
    $(SIGNATURES)

Sets the firmware pointer for :func:`Write Firmware`. The pointer has
to be increased by chunks of size 64. The data is written to flash
every 4 chunks (which equals to one page of size 256).

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function set_write_firmware_pointer(device::BrickletSilentStepperV2, pointer)
    device.deviceInternal.set_write_firmware_pointer(pointer)
end

export write_firmware
"""
    $(SIGNATURES)

Writes 64 Bytes of firmware at the position as written by
:func:`Set Write Firmware Pointer` before. The firmware is written
to flash every 4 chunks.

You can only write firmware in bootloader mode.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function write_firmware(device::BrickletSilentStepperV2, data)
    return device.deviceInternal.write_firmware(data)
end

export set_status_led_config
"""
    $(SIGNATURES)

Sets the status LED configuration. By default the LED shows
communication traffic between Brick and Bricklet, it flickers once
for every 10 received data packets.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is will show heartbeat by default.
"""
function set_status_led_config(device::BrickletSilentStepperV2, config)
    device.deviceInternal.set_status_led_config(config)
end

export get_status_led_config
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Status LED Config`
"""
function get_status_led_config(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_status_led_config()
end

export get_chip_temperature
"""
    $(SIGNATURES)

Returns the temperature as measured inside the microcontroller. The
value returned is not the ambient temperature!

The temperature is only proportional to the real temperature and it has bad
accuracy. Practically it is only useful as an indicator for
temperature changes.
"""
function get_chip_temperature(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_chip_temperature()
end

export reset
"""
    $(SIGNATURES)

Calling this function will reset the Bricklet. All configurations
will be lost.

After a reset you have to create new device objects,
calling functions on the existing ones will result in
undefined behavior!
"""
function reset(device::BrickletSilentStepperV2)
    device.deviceInternal.reset()
end

export write_uid
"""
    $(SIGNATURES)

Writes a new UID into flash. If you want to set a new UID
you have to decode the Base58 encoded UID string into an
integer first.

We recommend that you use Brick Viewer to change the UID.
"""
function write_uid(device::BrickletSilentStepperV2, uid)
    device.deviceInternal.write_uid(uid)
end

export read_uid
"""
    $(SIGNATURES)

Returns the current UID as an integer. Encode as
Base58 to get the usual string version.
"""
function read_uid(device::BrickletSilentStepperV2)
    return device.deviceInternal.read_uid()
end

export get_identity
"""
    $(SIGNATURES)

Returns the UID, the UID where the Bricklet is connected to,
the position, the hardware and firmware version as well as the
device identifier.

The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
A Bricklet connected to an :ref:`Isolator Bricklet <isolator_bricklet>` is always at
position 'z'.

The device identifier numbers can be found :ref:`here <device_identifier>`.
|device_identifier_constant|
"""
function get_identity(device::BrickletSilentStepperV2)
    return device.deviceInternal.get_identity()
end

export register_callback
"""
Registers the given *function* with the given *callback_id*.
"""
function register_callback(device::BrickletSilentStepperV2, callback_id, function_)
    if isnothing(function_)
        device.registered_callbacks.pop(callback_id, None)
    else
        device.registered_callbacks[callback_id] = function_
    end
end

ext: jl


text:
function isPrime(n)
    for i = 2:Int(floor(sqrt(n)))
        if n % i == 0;
            return false
        end
    end
    return true
end

max_stars_repo_path: Utility Functions/PrimeCheck.jl

max_issues_repo_path: Utility Functions/PrimeCheck.jl

max_forks_repo_path: Utility Functions/PrimeCheck.jl


text:
using Ripserer
using StaticArrays
using Test

using Ripserer: _binomial, _vertices, coboundary, boundary

struct FakeFiltration <: Ripserer.AbstractFiltration{Int,Int} end
function Ripserer.unsafe_simplex(
    ::Type{Simplex{D,Int,Int}}, ::FakeFiltration, vertices
) where {D}
    return Simplex{D,Int,Int}(index(vertices), 1)
end
Ripserer.nv(::FakeFiltration) = 20
Ripserer.simplex_type(::Type{FakeFiltration}, D) = Simplex{D,Int,Int}

struct FakeFiltrationWithThreshold <: Ripserer.AbstractFiltration{Int,Int} end
function Ripserer.unsafe_simplex(
    ::Type{Simplex{D,Int,Int}}, ::FakeFiltrationWithThreshold, vertices
) where {D}
    if maximum(vertices) > 10
        return nothing
    else
        return Simplex{D,Int,Int}(index(vertices), 1)
    end
end
Ripserer.nv(::FakeFiltrationWithThreshold) = 20
Ripserer.simplex_type(::Type{FakeFiltrationWithThreshold}, D) = Simplex{D,Int,Int}

@testset "Internal functions" begin
    @testset "_binomial" begin
        @test all(_binomial(n, Val(k)) == binomial(n, k) for n in 0:1000 for k in 0:7)
    end

    @testset "index" begin
        @test index((3, 2, 1)) === 1
        @test index(Int32.((4, 3, 2, 1))) === Int32(1)
        @test index(SVector(101, 100, 20, 15, 3)) ==
            1 +
              binomial(101 - 1, 5) +
              binomial(100 - 1, 4) +
              binomial(20 - 1, 3) +
              binomial(15 - 1, 2) +
              binomial(3 - 1, 1)
    end

    @testset "_vertices" begin
        for i in 1:3:10, N in 1:5
            @test index(_vertices(i, Val(N))) == i
            @test length(_vertices(i, Val(N))) == N
            @test begin
                @inferred _vertices(i, Val(N))
                true
            end
        end
    end
end

@testset "Simplex" begin
    @testset "Constructors" begin
        @test Simplex{1}([2, 1], 1) == Simplex{1}(1, 1)
        @test Simplex{1}((1, 3), 1) == Simplex{1}(2, 1)
        @test Simplex{2}([5, 2, 1], 1) == Simplex{2}(5, 1)
    end

    @testset "AbstractSimplex interface" begin
        for D in (0, 2, 4), T in (Float64, Float32, Int), I in (Int32, Int64, Int128)
            @testset "Simplex{$D, $T, $I}" begin
                b = T(9)
                i = I(100)
                sx = Simplex{D}(i, b)

                @testset "Type stuff" begin
                    @test sx ≡ Simplex{D,T,I}(i, b)
                    @test typeof(sx) ≡ Simplex{D,T,I}
                    D > 0 && @test_throws DomainError Simplex{-D}(i, b)
                    @test eltype(sx) == I
                end

                @testset "Getters" begin
                    @test index(sx) == i
                    @test index(-sx) == i
                    @test birth(sx) ≡ b
                end

                @testset "Equality, hashing" begin
                    @test sx == sx
                    @test sx != Simplex{D + 1}(i, b)
                    @test sx == Simplex{D}(i, b + 1)
                    @test isequal(sx, Simplex{D}(i, b + 1))
                    @test hash(sx) == hash(Simplex{D}(i, b + 1))
                    @test hash(sx) == hash(index(sx))
                end

                @testset "Signs" begin
                    @test +sx === sx
                    @test sx == -sx
                    @test sx ≡ -(-sx)
                    @test sign(sx) == 1
                    @test sign(-sx) == -1
                    @test abs(sx) ≡ sx
                    @test abs(-sx) ≡ sx
                    @test dim(sx) == D
                end

                @testset "Ordering" begin
                    @test sx < Simplex{D}(I(i + 1), b + 1)
                    @test sx > Simplex{D}(I(i - 1), b - 1)

                    @test sx < Simplex{D}(I(i - 1), b)
                    @test sx > Simplex{D}(I(i + 1), b)
                end

                @testset "vertices, iteration, indexing" begin
                    verts = vertices(sx)

                    @test eltype(sx) == eltype(verts)
                    @test length(sx) == length(verts) == D + 1
                    @test Simplex{D}(verts, birth(sx)) ≡ sx
                    @test tuple(sx...) == verts
                    @test (1:1000)[sx] == SVector(verts)

                    @test begin
                        @inferred vertices(sx)
                        true
                    end
                end

                @testset "Printing" begin
                    @test sprint(show, sx) == "+Simplex{$D}($(vertices(sx)), $(b))"
                    @test sprint(show, -sx) == "-Simplex{$D}($(vertices(sx)), $(b))"
                    @test sprint((i, s) -> show(i, MIME"text/plain"(), s), sx) ==
                        "$D-dimensional Simplex(index=$i, birth=$b):\n  +$(vertices(sx))"
                end
            end
        end
    end

    @testset "Coboundary" begin
        @testset "number of cofacets" begin
            for dim in 1:5
                simplex = Simplex{dim}(10, 1)
                simplex_vxs = vertices(simplex)
                cob = []
                for cofacet in coboundary(FakeFiltration(), simplex)
                    push!(cob, cofacet)
                end
                @test length(cob) == 20 - dim - 1
                @test all(isequal(1), birth.(cob))
                @test all(issubset(simplex_vxs, vertices(c)) for c in cob)
                @test issorted(cob; by=index, rev=true)
            end
        end
        @testset "number of cofacets, all_cofacets=false" begin
            for dim in 1:5
                cob = Simplex{dim + 1,Int,Int}[]
                for idx in binomial(20, dim + 1):-1:1
                    simplex = Simplex{dim}(idx, 1)
                    for cofacet in coboundary(FakeFiltration(), simplex, Val(false))
                        push!(cob, cofacet)
                    end
                end
                @test sort(index.(abs.(cob))) == 1:binomial(20, dim + 2)
            end
        end
        @testset "number of cofacets, thresholding" begin
            for dim in 1:5
                simplex = Simplex{dim}(10, 1)
                simplex_vxs = vertices(simplex)
                cob = []
                for cofacet in coboundary(FakeFiltrationWithThreshold(), simplex)
                    push!(cob, cofacet)
                end
                @test length(cob) == 10 - dim - 1
                @test all(isequal(1), birth.(cob))
                @test all(issubset(simplex_vxs, vertices(c)) for c in cob)
                @test issorted(cob; by=index, rev=true)
            end
        end
        @testset "type stability" begin
            for dim in 1:10
                simplex = Simplex{dim}(10, 1)
                @test begin
                    @inferred coboundary(FakeFiltration(), simplex)
                    true
                end
                cobiter = coboundary(FakeFiltration(), simplex)
                @static if VERSION ≥ v"1.1.0"
                    @test begin
                        @inferred Union{
                            Nothing,Tuple{Simplex{dim + 1,Int,Int},Tuple{Int,Int}}
                        } iterate(cobiter)
                        true
                    end
                    @test begin
                        @inferred Union{
                            Nothing,Tuple{Simplex{dim + 1,Int,Int},Tuple{Int,Int}}
                        } iterate(cobiter, (13, dim + 1))
                        true
                    end
                end
            end
        end
    end

    @testset "Boundary" begin
        @testset "number of facets" begin
            for dim in 1:5
                simplex = Simplex{dim}(10, 1)
                simplex_vxs = vertices(simplex)
                bnd = []
                for facet in boundary(FakeFiltration(), simplex)
                    push!(bnd, facet)
                end
                @test length(bnd) == dim + 1
                @test all(isequal(1), birth.(bnd))
                @test all(issubset(vertices(f), simplex_vxs) for f in bnd)
            end
        end
        @testset "type stability" begin
            for dim in 1:10
                simplex = Simplex{dim}(10, 1)
                @test begin
                    @inferred boundary(FakeFiltration(), simplex)
                    true
                end
                biter = boundary(FakeFiltration(), simplex)
                @static if VERSION ≥ v"1.1.0"
                    @test begin
                        @inferred Union{Nothing,Tuple{Simplex{dim - 1,Int,Int},Int}} iterate(
                            biter
                        )
                        true
                    end
                    @test begin
                        @inferred Union{Nothing,Tuple{Simplex{dim - 1,Int,Int},Int}} iterate(
                            biter, 1
                        )
                        true
                    end
                end
            end
        end
    end
end


text:
"""
    MatrixTDist(ν, M, Σ, Ω)
```julia
ν::Real            positive degrees of freedom
M::AbstractMatrix  n x p location
Σ::AbstractPDMat   n x n scale
Ω::AbstractPDMat   p x p scale
```
The [matrix *t*-distribution](https://en.wikipedia.org/wiki/Matrix_t-distribution)
generalizes the multivariate *t*-distribution to ``n\\times p`` real
matrices ``\\mathbf{X}``. If ``\\mathbf{X}\\sim \\textrm{MT}_{n,p}(\\nu,\\mathbf{M},\\boldsymbol{\\Sigma},
\\boldsymbol{\\Omega})``, then its probability density function is

```math
f(\\mathbf{X} ; \\nu,\\mathbf{M},\\boldsymbol{\\Sigma}, \\boldsymbol{\\Omega}) =
c_0 \\left|\\mathbf{I}_n + \\boldsymbol{\\Sigma}^{-1}(\\mathbf{X} - \\mathbf{M})\\boldsymbol{\\Omega}^{-1}(\\mathbf{X}-\\mathbf{M})^{\\rm{T}}\\right|^{-\\frac{\\nu+n+p-1}{2}},
```

where

```math
c_0=\\frac{\\Gamma_p\\left(\\frac{\\nu+n+p-1}{2}\\right)}{(\\pi)^\\frac{np}{2} \\Gamma_p\\left(\\frac{\\nu+p-1}{2}\\right)} |\\boldsymbol{\\Omega}|^{-\\frac{n}{2}} |\\boldsymbol{\\Sigma}|^{-\\frac{p}{2}}.
```

If the joint distribution ``p(\\mathbf{S},\\mathbf{X})=p(\\mathbf{S})p(\\mathbf{X}|\\mathbf{S})``
is given by

```math
\\begin{aligned}
\\mathbf{S}&\\sim \\textrm{IW}_n(\\nu + n - 1, \\boldsymbol{\\Sigma})\\\\
\\mathbf{X}|\\mathbf{S}&\\sim \\textrm{MN}_{n,p}(\\mathbf{M}, \\mathbf{S}, \\boldsymbol{\\Omega}),
\\end{aligned}
```

then the marginal distribution of ``\\mathbf{X}`` is
``\\textrm{MT}_{n,p}(\\nu,\\mathbf{M},\\boldsymbol{\\Sigma},\\boldsymbol{\\Omega})``.
"""
struct MatrixTDist{T <: Real, TM <: AbstractMatrix, TΣ <: AbstractPDMat, TΩ <: AbstractPDMat} <: ContinuousMatrixDistribution
    ν::T
    M::TM
    Σ::TΣ
    Ω::TΩ
    logc0::T
end

#  -----------------------------------------------------------------------------
#  Constructors
#  -----------------------------------------------------------------------------

function MatrixTDist(ν::T, M::AbstractMatrix{T}, Σ::AbstractPDMat{T}, Ω::AbstractPDMat{T}) where T <: Real
    n, p = size(M)
    0 < ν < Inf || throw(ArgumentError("degrees of freedom must be positive and finite."))
    n == dim(Σ) || throw(ArgumentError("Number of rows of M must equal dim of Σ."))
    p == dim(Ω) || throw(ArgumentError("Number of columns of M must equal dim of Ω."))
    logc0 = matrixtdist_logc0(Σ, Ω, ν)
    R = Base.promote_eltype(T, logc0)
    prom_M = convert(AbstractArray{R}, M)
    prom_Σ = convert(AbstractArray{R}, Σ)
    prom_Ω = convert(AbstractArray{R}, Ω)
    MatrixTDist{R, typeof(prom_M), typeof(prom_Σ), typeof(prom_Ω)}(R(ν), prom_M, prom_Σ, prom_Ω, R(logc0))
end

function MatrixTDist(ν::Real, M::AbstractMatrix, Σ::AbstractPDMat, Ω::AbstractPDMat)
    T = Base.promote_eltype(ν, M, Σ, Ω)
    MatrixTDist(convert(T, ν), convert(AbstractArray{T}, M), convert(AbstractArray{T}, Σ), convert(AbstractArray{T}, Ω))
end

MatrixTDist(ν::Real, M::AbstractMatrix, Σ::Union{AbstractMatrix, LinearAlgebra.Cholesky}, Ω::Union{AbstractMatrix, LinearAlgebra.Cholesky}) = MatrixTDist(ν, M, PDMat(Σ), PDMat(Ω))
MatrixTDist(ν::Real, M::AbstractMatrix, Σ::AbstractPDMat, Ω::Union{AbstractMatrix, LinearAlgebra.Cholesky}) = MatrixTDist(ν, M, Σ, PDMat(Ω))
MatrixTDist(ν::Real, M::AbstractMatrix, Σ::Union{AbstractMatrix, LinearAlgebra.Cholesky}, Ω::AbstractPDMat) = MatrixTDist(ν, M, PDMat(Σ), Ω)

#  -----------------------------------------------------------------------------
#  REPL display
#  -----------------------------------------------------------------------------

 show(io::IO, d::MatrixTDist) = show_multline(io, d, [(:ν, d.ν), (:M, d.M), (:Σ, Matrix(d.Σ)), (:Ω, Matrix(d.Ω))])

#  -----------------------------------------------------------------------------
#  Conversion
#  -----------------------------------------------------------------------------

function convert(::Type{MatrixTDist{T}}, d::MatrixTDist) where T <: Real
    MM = convert(AbstractArray{T}, d.M)
    ΣΣ = convert(AbstractArray{T}, d.Σ)
    ΩΩ = convert(AbstractArray{T}, d.Ω)
    MatrixTDist{T, typeof(MM), typeof(ΣΣ), typeof(ΩΩ)}(T(d.ν), MM, ΣΣ, ΩΩ, T(d.logc0))
end

function convert(::Type{MatrixTDist{T}}, ν, M::AbstractMatrix, Σ::AbstractPDMat, Ω::AbstractPDMat, logc0) where T <: Real
    MM = convert(AbstractArray{T}, M)
    ΣΣ = convert(AbstractArray{T}, Σ)
    ΩΩ = convert(AbstractArray{T}, Ω)
    MatrixTDist{T, typeof(MM), typeof(ΣΣ), typeof(ΩΩ)}(T(ν), MM, ΣΣ, ΩΩ, T(logc0))
end

#  -----------------------------------------------------------------------------
#  Properties
#  -----------------------------------------------------------------------------

size(d::MatrixTDist) = size(d.M)

rank(d::MatrixTDist) = minimum( size(d) )

insupport(d::MatrixTDist, X::Matrix) = isreal(X) && size(X) == size(d)

function mean(d::MatrixTDist)
    n, p = size(d)
    d.ν + p - n > 1 || throw(ArgumentError("mean only defined for df + p - n > 1"))
    return d.M
end

mode(d::MatrixTDist) = d.M

cov(d::MatrixTDist, ::Val{true}=Val(true)) = d.ν <= 2 ? throw(ArgumentError("cov only defined for df > 2")) : Matrix(kron(d.Ω, d.Σ)) ./ (d.ν - 2)

cov(d::MatrixTDist, ::Val{false}) = ((n, p) = size(d); reshape(cov(d), n, p, n, p))

var(d::MatrixTDist) = d.ν <= 2 ? throw(ArgumentError("var only defined for df > 2")) : reshape(diag(cov(d)), size(d))

params(d::MatrixTDist) = (d.ν, d.M, d.Σ, d.Ω)

@inline partype(d::MatrixTDist{T}) where {T <: Real} = T

#  -----------------------------------------------------------------------------
#  Evaluation
#  -----------------------------------------------------------------------------

function matrixtdist_logc0(Σ::AbstractPDMat, Ω::AbstractPDMat, ν::Real)
    #  returns the natural log of the normalizing constant for the pdf
    n = dim(Σ)
    p = dim(Ω)
    term1 = logmvgamma(p, (ν + n + p - 1) / 2)
    term2 = - (n * p / 2) * logπ
    term3 = - logmvgamma(p, (ν + p - 1) / 2)
    term4 = (-n / 2) * logdet(Ω)
    term5 = (-p / 2) * logdet(Σ)
    term1 + term2 + term3 + term4 + term5
end

function logkernel(d::MatrixTDist, X::AbstractMatrix)
    n, p = size(d)
    A = X - d.M
    (-(d.ν + n + p - 1) / 2) * logdet( I + (d.Σ \ A) * (d.Ω \ A') )
end

#  -----------------------------------------------------------------------------
#  Sampling
#  -----------------------------------------------------------------------------

#  Theorem 4.2.1 in Gupta and Nagar (1999)

function _rand!(rng::AbstractRNG, d::MatrixTDist, A::AbstractMatrix)
    n, p = size(d)
    S = rand(rng, InverseWishart(d.ν + n - 1, d.Σ) )
    A .= rand(rng, MatrixNormal(d.M, S, d.Ω) )
end

#  -----------------------------------------------------------------------------
#  Relationship with Multivariate t
#  -----------------------------------------------------------------------------
#  if a t-distributed random matrix is in fact just a row or column,
#  it is equivalent to a t-distributed random vector.
#  -----------------------------------------------------------------------------

function MvTDist(MT::MatrixTDist)
    n, p = size(MT)
    all([n, p] .> 1) && throw(ArgumentError("Row or col dim of `MatrixTDist` must be 1 to coerce to `MvTDist`"))
    ν, M, Σ, Ω = params(MT)
    MvTDist(ν, vec(M), (1 / ν) * kron(Σ, Ω))
end

#  -----------------------------------------------------------------------------
#  Test utils
#  -----------------------------------------------------------------------------

function _univariate(d::MatrixTDist)
    check_univariate(d)
    ν, M, Σ, Ω = params(d)
    μ = M[1]
    σ = sqrt( Matrix(Σ)[1] * Matrix(Ω)[1] / ν )
    return LocationScale(μ, σ, TDist(ν))
end

_multivariate(d::MatrixTDist) = MvTDist(d)

function _rand_params(::Type{MatrixTDist}, elty, n::Int, p::Int)
    ν = elty( n + p + 1 + abs(10randn()) )
    M = randn(elty, n, p)
    Σ = (X = 2rand(elty, n, n) .- 1; X * X')
    Ω = (Y = 2rand(elty, p, p) .- 1; Y * Y')
    return ν, M, Σ, Ω
end


text:
### A Pluto.jl notebook ###
# v0.14.9

using Markdown
using InteractiveUtils

# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
    quote
        local el = $(esc(element))
        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
        el
    end
end

# ╔═╡ a760fb60-3f05-11ec-1040-258671c4c205
begin
	using Plots
	using DifferentialEquations
	using PlutoUI
end

# ╔═╡ 3d606a54-b43e-4846-a06e-8028f1576267
md"# Climate Change Modelling"

# ╔═╡ c101002d-6918-4f6d-af97-8eebcd609be9
md"""
#### 1) Unrealistic Heating Model(**Earth Baking Model**)
"""

# ╔═╡ d8ddb39f-08f6-450a-ab57-b47aa0251492
md"There are many Climate Change Models This is a simple graph of one, where we assume that from each year after 1850 we emmit green house gases"

# ╔═╡ 0f8cc3ec-c355-4f6e-801b-f660250b727b
md"""
This model can be expressed as
> **Cₜ = C₀ * ϵ (simplified Equation)**
where Cₜ is the temperature at time 𝓉 C₀ is the temperature at 1850 and ϵ is the factor by which the temperature increases
"""

# ╔═╡ 34ea6628-81bc-4b78-bf09-8394f326543c
md"""
This model is completly unrealistic as it says that we would have a temperature of around 800°C which cannot hold life
"""

# ╔═╡ 4bb137bd-1ab5-4ee2-9371-050c206e5577
md"""
#### 2) **Healthy Earth Model** (With no human induced green house gases)
"""

# ╔═╡ ee7eb18a-2978-49c8-a3a4-de76cb877d9d
md"""
Another way to model the earth climate is by introducing the cooling mechanisim of earth where a sun ray hits the earth temperature (**heating**)(𝒮) and the earth reflects the sun rays back to space(**cooling**)(α)
"""

# ╔═╡ c0a9fd3c-a601-447a-8ac6-32091303a2d5
md"""
Model can be expressed as
> **cooling of earth = 𝒮(1 - α)/4**
where 𝒮 is the incoming solar radiation with a value of **1368 W/m²** and
α is the reflectivity of the earth with a value of **0.3** \
\
So combing The heating and cooling equations we get the equation for a healthy
Earth Simulation
> **Health Earth Simulation = Cooling Of Earth - Heating of Earth**
"""

# ╔═╡ dcb1a918-cbfb-47e4-ad75-9827e46735c3
md"""
> Below here is a simulation of a **Healthly Earth Temperature Simulation** where if you adjust the slider which the starting point of Earth's temperature, Earth will always cool itself down This process occured for millions and millions of years without the intervention of **human induced green house gases**
"""

# ╔═╡ d2860b33-0434-4e33-8817-e2e35b958992
md"Earth Start Temperature $(@bind start_temp Slider(0.1:0.01:25.1,show_value=true)) °C"

# ╔═╡ ef7e8293-bc42-4b38-81b2-c4a1d2ca7235
md"""
# Climate Change!
"""

# ╔═╡ d35ee881-7353-46e1-8e9f-15a5ecbc12ce
md"""
#### 3) Temperature Rise With **Human Induced Green House Gases Model**
"""

# ╔═╡ 223453e4-3642-4953-a942-53effa6c126b
md"""
We can model climate change by equation
> **Cₜ = (cooling effect - heating effect) + human induced effect**
"""

# ╔═╡ 16488cb8-a129-4dff-a575-887407ed316c
md"""
> Slider Controls The Start **Temperature At 1850**, As you can see a **cooling effect occurs in the early 1850s** and after the industrial revolution the **human induced effect take place**
"""

# ╔═╡ 628ece4f-024e-440a-9183-e5d8011ecfcc
md"Human induced Climate Change Modelling °C  = $(@bind human_temp Slider(0.1:0.01:25.1,show_value=true)) °C"

# ╔═╡ b53a82f4-45a3-4657-8cb9-e4f09715570c

# ╔═╡ 4e88e20b-066c-4144-a913-e9be59a2395d
gr();

# ╔═╡ 26940047-17c7-4c55-9e94-27149af0e4f5
begin
	S = 1368.0
	α = 0.3
	C =  51.0
	temp0 = 14.10
	B = 1.5
	forcing_coef = 5.0
	CO2_PreIndustrial = 280.0
end;

# ╔═╡ 3f866044-279c-41c4-a34f-ba505332813d
p2 = ODEProblem((temp,p,t) -> (1/C) * B * (temp0 - temp),start_temp,(0.0,180.0));

# ╔═╡ 51482521-ef60-4cab-80ea-d68f21879f2e
begin
	plot(solve(p2),ylim=(0,35.0),label= "Healthy Earth Temperature",xlabel="Number Year",ylabel = "Number Temperature Scale")
	hline!( [14.1,14.1] ,c=:black,ls=:dash,label="Earth Temperature At 1850 PreIndustrial Age 14°C")
	title!("Healthy Earth Temperature Simulation")
	# annotate!(91.0,15.8,text("Global Temperature At 1850"))
end

# ╔═╡ 5aeef5ee-866b-488a-ab8e-757f9224b086
greenhouse_effect(CO2) = forcing_coef * log(CO2/CO2_PreIndustrial);

# ╔═╡ 14d6487f-62fc-40e6-9802-b0f6476e28e9
CO2(t) = CO2_PreIndustrial * (1 + (t/220)^3);

# ╔═╡ a32cbb16-29b9-4cb6-acec-9345a47e0c94
p3 = ODEProblem((temp,p,t) -> (1/C) * (B * (temp0 - temp) +  greenhouse_effect(CO2(t)) ),human_temp,(0.0,200.0));

# ╔═╡ 4c626313-91b7-42d2-bc1e-32ac704dd749
begin
	plot(solve(p3),xlabel="Number Year",ylabel="Temperature",label="Earth Temperature",ylims=(10.1,21.5),xlims=(0.0,181.0))
	hline!([temp0,temp0],c = :black,ls = :dash,label="Global Temperature At 1850 14°C")
	plot!([0, 51], [0.0, 0.5], fillrange=[25.1, 25.1], color=:lightblue, alpha=0.2, label="Pre Industrial Time")
	plot!([100.1, 181.3], [0.0, 0.5], fillrange=[25.1, 25.1], color=:red, alpha=0.2, label="Industrial Time Green House Gas Emission")
	# annotate!(53,15.8,text("Global Temperature At 1850"))
end

# ╔═╡ 670ec61d-0175-4f1d-9b52-a31576824c77
greenhouse_effect(CO2(159));

# ╔═╡ a17a3b04-4a46-446d-bf4b-00e119c0ef2a
absorbed_solar_radiation = S * (1 - α)/4;

# ╔═╡ 01d5f55c-452d-4848-966a-be20cc1ae0f4
p1 = ODEProblem((temp, p, t) -> (1/C) * absorbed_solar_radiation,temp0,(0.0,350.0));

# ╔═╡ 69f3aadc-21c4-46d1-8d7d-818057d144cc
begin
	plot(solve(p1),xlabel="years since 1850",xlims=(0.0,201.1),ylabel="temperature",label="Earth Temperature")
	hline!( [14.1,14.1] ,c=:black,ls=:dash,label="Global Earth Temperature At 1850 14°C")
end

# ╔═╡ 8d4e7794-bdf9-4ffa-8716-aebef40cfc0e
temp_human = @bind start_temp_human Slider(0.1:0.01:25.1,show_value=true);

# ╔═╡ 54cafc8c-aac2-40b5-ba23-ef93045ba60e
gr();

# ╔═╡ Cell order:
# ╟─a760fb60-3f05-11ec-1040-258671c4c205
# ╟─3d606a54-b43e-4846-a06e-8028f1576267
# ╟─c101002d-6918-4f6d-af97-8eebcd609be9
# ╟─d8ddb39f-08f6-450a-ab57-b47aa0251492
# ╟─0f8cc3ec-c355-4f6e-801b-f660250b727b
# ╟─69f3aadc-21c4-46d1-8d7d-818057d144cc
# ╟─34ea6628-81bc-4b78-bf09-8394f326543c
# ╟─4bb137bd-1ab5-4ee2-9371-050c206e5577
# ╟─ee7eb18a-2978-49c8-a3a4-de76cb877d9d
# ╟─c0a9fd3c-a601-447a-8ac6-32091303a2d5
# ╟─dcb1a918-cbfb-47e4-ad75-9827e46735c3
# ╟─d2860b33-0434-4e33-8817-e2e35b958992
# ╟─51482521-ef60-4cab-80ea-d68f21879f2e
# ╟─ef7e8293-bc42-4b38-81b2-c4a1d2ca7235
# ╟─d35ee881-7353-46e1-8e9f-15a5ecbc12ce
# ╟─223453e4-3642-4953-a942-53effa6c126b
# ╟─16488cb8-a129-4dff-a575-887407ed316c
# ╟─628ece4f-024e-440a-9183-e5d8011ecfcc
# ╟─4c626313-91b7-42d2-bc1e-32ac704dd749
# ╟─b53a82f4-45a3-4657-8cb9-e4f09715570c
# ╟─3f866044-279c-41c4-a34f-ba505332813d
# ╟─5aeef5ee-866b-488a-ab8e-757f9224b086
# ╟─4e88e20b-066c-4144-a913-e9be59a2395d
# ╟─a32cbb16-29b9-4cb6-acec-9345a47e0c94
# ╟─670ec61d-0175-4f1d-9b52-a31576824c77
# ╟─14d6487f-62fc-40e6-9802-b0f6476e28e9
# ╟─26940047-17c7-4c55-9e94-27149af0e4f5
# ╟─a17a3b04-4a46-446d-bf4b-00e119c0ef2a
# ╟─01d5f55c-452d-4848-966a-be20cc1ae0f4
# ╟─8d4e7794-bdf9-4ffa-8716-aebef40cfc0e
# ╟─54cafc8c-aac2-40b5-ba23-ef93045ba60e

max_stars_repo_path: Climate Change Modelling.jl

max_stars_repo_name: thesuperboy/Climate-Change

max_issues_repo_path: Climate Change Modelling.jl

max_issues_repo_name: thesuperboy/Climate-Change

max_forks_repo_path: Climate Change Modelling.jl

max_forks_repo_name: thesuperboy/Climate-Change