licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.3.3 | f958c49f3f4f812d6eb2725f102896a0ead72172 | docs | 3451 | # ClimateMARGO.jl
A Julia implementation of **MARGO**, an idealized framework for the **O**ptimization of four climate change control strategies: **M**itigation, **A**daptation, **R**emoval of carbon dioxide, and **G**eoengineering by solar radiation management.
ClimateMARGO.jl couples together a very simple model of Earth's physical climate with a very simple economic model of climate damages (and the costs of "controls" that reduce those damages). Our design philosophy is that the MARGO model should be *as simple as possible* while still producing quasi-realistic climate trajectories over the next few hundred years.
Compared to more conventional *Integrated Assessment Models (IAMs)*, MARGO is:
* **Faster**: The algorithm solves convex optimization problems in less than 100 milliseconds (most use cases), meaning the model can be run interactively in real-time and that both large-ensemble, high-dimensional, and stochastic optimizations are all computationally feasible.
* **More accessible**: The ClimateMARGO.jl package is free to use and is accessible in several different forms depending on the user's programming experience and use case:
* *An [interactive web-app](https://margo.plutojl.org/introduction.html)* – For interactive exploration of climate storylines (and their sensitivity to model parameters).
* *Importing ClimateMARGO.jl* – For users proficient in Julia who want to use the MARGO model for education or scientific research.
* *Forking ClimateMARGO.jl* – For users wanting to extend or fundamentally modify the MARGO model source code, e.g. for their own scientific or policy research.
* **More interpretable**: The entire model algorithm is simple enough to be expressed in a single closed-form math equation and is determined by only a handful of intuitive free parameters (see also the MARGO flowchart below).
* **More transparent**: The MARGO model is developed as an entirely open-source Julia package, *ClimateMARGO.jl*, complete with documentation, in-depth tutorials, and example applications.
* **More general**: By including all four of the primary climate controls in the default configuration, more common configurations like "Mitigation-only" experiments are straight-forward to implement by simply turning unwanted features off.
* **More explicitly value-dependent**: Rather than burying important value-dependent choices in various obscure economic and social parameters, we abstract away many of the complexities to yield a small number of intuitive parameters, which can be easily modified by users.
* **More extendable**: The modular and interpretable nature of the Julia source implementation means that existing features can be easily modified and new features are easily added.

!!! warning "Don't take MARGO's results too seriously"
The extreme simplicity of the MARGO model also means its *quantitative* results should be taken with a handful of salt. MARGO should instead be used to explore underlying *patterns* and *relative* climate outcomes.
## Getting help
If you are interested in using ClimateMARGO.jl or are trying to figure out how to use it, please feel free to ask us questions and get in touch! Please feel free to [open an issue](https://github.com/ClimateMARGO/ClimateMARGO.jl/issues/new) if you have any questions, comments, suggestions, etc!
| ClimateMARGO | https://github.com/ClimateMARGO/ClimateMARGO.jl.git |
|
[
"MIT"
] | 0.3.3 | f958c49f3f4f812d6eb2725f102896a0ead72172 | docs | 1374 | # Installation instructions
We recommend installing ClimateMARGO with the built-in Julia package manager, because this installs a stable, tagged release. You can install the latest version of ClimateMARGO using the built-in package manager (accessed by pressing `]` in the Julia command prompt) to add the package and instantiate/build all dependencies. It is recommended that you create a new self-contained julia environment to install ClimateMARGO in.
```julia
julia>]
(v1.7) pkg> activate .
(v1.7) pkg> add ClimateMARGO
(v1.7) pkg> instantiate
```
The command `activate .` will create (if not yet existent) and activate a new environment with the name of the parent folder.
ClimateMARGO.jl can be updated to the latest tagged release from the package manager by typing
```julia
(v1.7) pkg> update ClimateMARGO
```
In some cases, it may be useful to install versions of ClimateMARGO from a development branch named [Branch name], which can be done by typing
```julia
(v1.7) pkg> add https://github.com/ClimateMARGO/ClimateMARGO.jl#[Branch name]
```
At this time (and until ClimateMARGO v1.0.0), updating should be done with care, as ClimateMARGO is under rapid development and breaking changes to the user API occur often. But if anything does happen, please open an issue!
!!! warn "Use Julia 1.5 or newer"
ClimateMARGO requires at least Julia v1.5 to run.
| ClimateMARGO | https://github.com/ClimateMARGO/ClimateMARGO.jl.git |
|
[
"MIT"
] | 0.3.3 | f958c49f3f4f812d6eb2725f102896a0ead72172 | docs | 5346 | # Optimization
## Supported optimization problems
The following optimization problems are currently supported in MARGO:
- Cost-benefit optimization
- Cost-effectiveness optimization
All of these constraints rely on the concept of discounting to convert a time-series of costs and benefits into a single scalar-valued objective function.
!!! ukw "Time discounting"
Mathematically, a time-series ``g(t)`` is converted into a single scalar-valued function ``G`` by multiplying the time-series by a discount factor ``(1 - \rho)^{t-t_{0}}`` and integrating in time,
```math
G = \int_{t_{0}}^{\infty}\, g(t) (1 - \rho)^{t-t_{0}}\, \text{d}t
```
A great deal of the climate economic literature concerns methods (or philosophies) for determining the discount rate, with commonly cited values ranging all the way from 0% to 5%. Values larger than the growth rate of the economy result in de-valuing of future generations, which some argue is unethical.
Discounting is also mathematically convenient because it generally guarantees the objective function is bounded, which makes interpreting (and numerically solving) the optimization problem a lot easier.
### Cost-benefit analysis
A natural and widely-used approach is cost-benefit analysis, in which the cost ``\mathcal{C}_{M, R, G, A}`` of deploying climate controls is balanced against the benefits ``\mathcal{B}_{M, R, G, A}`` of the avoided climate damages. Formally, we aim to maximize the net present benefits:
```math
\max \left\{ \int_{t_{0}}^{t_{f}}
\left(\mathcal{B}_{M, R, G, A} - \mathcal{C}_{M, R, G, A} \right) (1 + \rho)^{-(t-t_{0})} \, \text{d}t \right\},
```
where ``\rho`` is a social discount rate that determines the annual depreciation of future costs and benefits of climate control to society. There are different views about the appropriate non-zero discount rate to apply to multi-generational social utility. Here, we choose a discount rate of ``\rho = 2\%`` equal to the exogeneous economic growth rate of ``\gamma = 2\%``, on the low end of values used in the literature, motivated by our preference towards inter-generational equity.
### Cost-effectiveness of keeping below a warming threshold
The conventional cost-benefit approach to understanding climate change is limited by the poorly understood damage function, which is likely to continue being revised as more is learned about its behavior at high levels of forcing. An alternative approach, which presently guides global climate policy negotiations, is to prescribe a threshold of climate damages– or temperatures, as in the Paris Climate Agreement– which is not to be surpassed.
In this implementation, we aim to find the lowest net present costs of control deployments
```math
\min\left\{\int_{t_{0}}^{t_{f}} \mathcal{C}_{M,R,G,A} (1 + \rho)^{-(t-t_{0})} \text{ d}t\right\}
```
which keep controlled damages below the level corresponding to a chosen temperature threshold,
``\beta (T_{M,R,G})^{2} (1 - A(t)) < \beta (T^{\star})^{2}``, which we rewrite
```math
T_{M,R,G,A} < T^{\star},
```
where ``T_{M,R,G,A}`` is the "adapted temperature".
## Additional constraints
For each control ``\alpha \in \mathcal{A} = \{ M, R, G, A\}``, we assert a maximum deployment rate
```math
\left\|\frac{\text{d}\alpha}{\text{d}t}\right\| \le \dot{\alpha},
```
as a crude parameterization of social, technological, and economic inertia, which acts to forbid implausibly aggressive deployment and phase-out scenarios (see Appendix A2 for more discussion). We set ``\dot{M} \equiv \dot{R} \equiv 1/40``years``^{-1}`` in line with the most ambitious climate goals and ``\dot{G} = 1/20``years``^{-1}`` to reflect the technological simplicity of attaining a large SRM forcing relative to mitigation and carbon dioxide removal. We interpret adaptation deployment costs as buying insurance against future damages at a fixed annual rate ``\mathcal{C}_{A} A^{2}``, with ``\dot{A} = 0``, which can be increased or decreased upon re-evaluation at a later date.
We also set a control readiness condition which optionally limits how soon each control is "ready" to be deployed. In particular, in the default configuration we set ``t_{R} = 2030`` and ``t_{G} = 2050`` because carbon dioxide removal has not yet been deployed at a climatically significant scale and solar radiation management does not yet exist as a socio-technological system.
## Optimization algorithm
We use the [Interior Point Optimizer](https://github.com/coin-or/Ipopt), an open source software package for large-scale nonlinear optimization, to minimize objective functions representing benefits and costs to society subject to assumed policy constraints. In practice, the control variables ``\alpha \in \mathcal{A} = \{ M, R, G, A\}`` are discretized into ``N = (t_{f} - t_{0}) / \delta t`` timesteps (default ``\delta t = 5`` years, ``N = 36``) resulting in a ``4N``-dimensional optimization problem. In the default (deterministic and convex) configuration, the model takes only ``\mathcal{O}(10 \text{ms})`` to solve after just-in-time compiling and effectively provides user feedback in real time. This makes the model amenable to our forthcoming interactive web application, which is inspired by the impactful [En-ROADS model web application](https://en-roads.climateinteractive.org/scenario.html).
| ClimateMARGO | https://github.com/ClimateMARGO/ClimateMARGO.jl.git |
|
[
"MIT"
] | 0.3.3 | f958c49f3f4f812d6eb2725f102896a0ead72172 | docs | 11251 | # Theory
The theory below formulates the simple default configuration of the MARGO model. We invite users to modify these equations or add additional ones, as required by their use cases. For a full description of the model, see the [original ClimateMARGO.jl publication](https://iopscience.iop.org/article/10.1088/1748-9326/ac243e) in *Environmental Research Letters* (and its supplementary information).
## The causal chain of climate suffering
It is helpful to conceptualize climate change as a four step process that connects the human-caused emissions of greenhouse gases (GHGs) to the eventual climate suffering (or damages) that they cause. This four-step framing reflects the four major human actions (or controls) which can sever these links to reduce climate suffering: **M**itigation of GHG emissions (e.g. switching away from fossil fuels), **R**emoval of carbon dioxide from the atmosphere (e.g. by planting trees or storing biofuel emissions underground), **G**eoengineering by solar radiation management (e.g. injecting sulfate aerosols into the stratosphere to reduce incoming sunlight), or **A**dapting to the changed climate (e.g. relocating coastal communities displaced by rising seas or expanding indoor air conditioning to fight off intensifying heat waves).
```math
\text{Emissions}\,
\overset{\text{Mitigation}}{\nRightarrow}\,
\text{GHGs}\,
\overset{\text{Removal}}{\nRightarrow}\,
\text{Forcing}\,
\overset{\text{Geoengineering}}{\nRightarrow}\,
\text{Warming}\,
\overset{\text{Adaptation}}{\nRightarrow}\,
\text{Suffering}.
```
Letting climate change run rampant would clearly cause a lot of suffering; however, climate controls that slow or stop climate change are not free either. MARGO empowers users to explore the trade-offs between climate controls and climate suffering by employing an optimization framework commonly used in the climate-economics community. In this section, we develop a simple theory - a set of mathematical equations – which capture the key aspects of the entire causal chain of climate damages.

!!! ukw "Tuning MARGO's free parameters"
We have attempted to make reasonable choices for the default values of MARGO's parameters in the equations below. Some of these, such as the climate physics variables, are well justified based on the best climate science research; others, such as the socio-economic parameters, are chosen based on our values (or those represented in the academic climate change literature). We encourage users to question these choices and plug their own values into ClimateMARGO. If you feel strongly that we should change some of the default values included in the model code, please reach out to us by [opening an issue](https://github.com/ClimateMARGO/ClimateMARGO.jl/labels/criticism) on Github.
## Greenhouse gas emissions
Since carbon dioxide (CO``_{2}``) is the dominant anthropogenic greenhouse gas, it dramatically simplifies the model to bundle all of the other gases into an equivalent concentration CO``_{2e}``, which produces an equivalent greenhouse effect. In MARGO, CO``_{2e}`` is emitted at a rate ``q(t)``, with only a fraction ``r`` remaining in the atmosphere after a few years, net of uptake by the ocean and terrestrial biosphere.
!!! note "Climate control: Emissions mitigation"
GHG emissions are reduced by a **M**itigation factor ``(1-M(t))``, becoming ``q(t)(1-M(t))``, where ``M(t)`` varies between 0% (high-emissions baseline) and 100% (full decarbonization).
## Greenhouse gas concentrations
CO``_{2e}`` continues to accumulate in the atmosphere and its concentrations ``c(t)= c_{0} + \int_{t_{0}}^{t} rq(t')\text{ d}t' \,`` will increase as long as the emissions ``q(t)`` are greater than zero.
!!! note "Climate control: Carbon dioxide removal"
**R**emoval of CO``_{2e}``, in contrast to mitigation, is de-coupled from instantaneous emissions and is expressed as the percentage of 2020 baseline emissions that are removed from the atmosphere in a given year, ``q_{0}R(t)``. A value of ``R=100\%`` corresponds to removing ``60`` GtCO``_{2e}`` per year, which is roughly equal to a recent upper-bound estimate of the global potential for negative emission technologies.
A useful diagnostic quantity is the effective emissions
```math
rq(t)(1-M(t)) - rq_{0}R(t),
```
which is the annual rate of CO``_{2e}`` accumulation in the atmosphere, including negative contributions from both emissions mitigation and CDR.
The change in CO``_{2e}`` concentrations is simply the integral of the effective emissions over time,
```math
c_{M,R}(t) = c_{0} + \int_{t_{0}}^{t} rq(t')(1-M(t')) \text{ d}t' - rq_{0} \int_{t_{0}}^{t} R(t')\text{ d}t'.
```
## Radiative forcing
Increasing CO``_{2e}`` concentrations strengthen the greenhouse effect, reducing outgoing longwave radiation and causing an increased radiative forcing of ``F(t) = a \ln(c(t)/c_{0})``, which exerts a warming effect on Earth's surface.
!!! note "Climate control: Solar geo-engineering"
**G**eoengineering by solar radiation management acts to offset a fraction of the CO``_{2e}`` forcing,
```math
F_{M,R,G}(t) = F_{M,R}(t) - G(t) F_{\infty},
```
where ``F_{M,R} = a \ln(c_{M,R}(t) / c_{0})`` is the controlled CO``_{2e}`` forcing (i.e. accounting for any mitigation and carbon dioxide removal) and ``F_{\infty} = 8.5`` W/m``^{2}`` is the maximum baseline CO``_{2e}`` forcing, which is attained starting in 2150 when baseline emissions are assumed to reach zero. A value of ``G = 100\%`` thus corresponds to a complete cancellation between the equilibrium warming from baseline CO``_{2e}`` increases and the cooling from a full deployment of SRM.
## Global warming and climate suffering
Near-surface air temperatures eventually increase by ``T(t) = F(t)/B`` to balance the reduced cooling to space, where ``B/(\kappa + B) = 60\%`` of the warming occurs within a few years and the remaining ``\kappa/(B + \kappa) = 40\%`` occurs over the course of several centuries due to ocean heat uptake. The feedback parameter ``B`` includes the effects of all climate feedbacks, except those involving the carbon cycle and the long-term ice sheet response, and the ocean heat uptake rate ``\kappa`` parameterizes the combined effects of advection and diffusion of heat into the deep ocean.
More specifically, the controlled near-surface air temperature evolves according to the total controlled forcing,
```math
T_{M,R,G}(t) - T_{0} = \frac{F_{M,R,G}(t)}{B + \kappa} + \frac{\kappa}{B} \int_{t_{0}}^{t} \frac{e^{\frac{t'-t}{\tau_{D}}}}{\tau_{D}} \frac{F_{M,R,G}(t')}{B+\kappa} \, \text{d}t',
```
where ``T_{0} = 1.1``°C is the present warming relative to preindustrial and ``\tau_{D} = 240`` years is the slow timescale of ocean heat uptake. The first term on the right-hand side represents a fast transient response while the second term represents a slow recalcitrant response due to the thermal inertia of the deep ocean. Climate inertia decouples the temperature response from instantaneous forcing and implies that an additional fraction of short-term warming (or cooling) is locked in for the future, even if radiative forcing is stabilized, as in the case of bringing emissions to zero in our model.
Anthropogenic warming causes a myriad of climate impacts, which result suffering (expressed in an economic model as a loss in welfare or monetary damages) that increase non-linearly with temperature, ``D = \beta T^{2}``, where the damage parameter ``\beta`` is tuned such that a warming of ``2``°C results in damages of ``4\%`` of Gross World Product (GWP).
!!! note "Climate control: Adaptation"
**A**daptation to climate impacts acts to reduce damages by a fraction ``A``. The controlled damages are thus given by
```math
D_{M,R,G,A} = \beta T_{M,R,G} T^{2} (1 - A(t)).
```
Although adaptation does not affect the planetary temperature directly, it is useful to consider an "adapted temperature" ``T_{M,R,G,A}`` which yields controlled damages equivalent to the fully-controlled damages ``\beta (T_{M,R,G,A})^{2} = \beta (T_{M,R,G})^{2} (1 - A(t))`` and is defined
```math
T_{M,R,G,A} \equiv T_{M,R,G} \sqrt{ 1 - A(t) }.
```
## The costs and benefits of climate control
Control costs are summed up across each of the four controls:
```math
\mathcal{C} = \mathcal{C}_{M} M^{3} + \mathcal{C}_{R} R^{3} + \mathcal{C}_{G} G^{3} + \mathcal{C}_{A} A^{3},
```
where the ``C_{*}`` are the hypothetical annual costs of fully deploying that control and the cost functions are assumed to be convex functions of fractional deployment with zero initial marginal cost and are here all taken to be cubic for simplicity, such that marginal costs (their derivatives) increase quadratically.
The benefits of deploying climate controls are the avoided climate damages relative to the high-emissions no-policy baseline scenario,
```math
\mathcal{B} = D - D_{M,R,G,A} = \beta (T^{2} - (T_{M,R,G,A})^{2}).
```
## Optimization: what makes a climate "optimal"?
We use "optimal" in the mathematical sense of "optimization", i.e. the search for the maximum or minimum value of a given "objective function", which depends on a set of "control variables". *Control variables* are variables with unknown values that are solved for, and are different from known "parameters" which are input by the user. For example, the full set of control variables in MARGO is ``\{M(t), R(t), G(t), A(t)\}`` (with ``N`` timesteps in time). An *objective function* is any scalar-valued function of the control variables, meaning it only produces a single value (as opposed to a multi-valued vector). Optimizing MARGO largely consists of defining the objective function to optimize. For example, one might aim to minimize the total costs of climate controls.
An optimization problem can further be customized by added constraints on valid sets of the control variables. For example, in MARGO we impose the constraints $0\% < M(t) < 100\%$ because it does not make any sense to mitigate emissions less than $0\%$ or more than $100\%$ (carbon dioxide removal is treated separately by the $R(t)$ control variable). Similarly, we rule out any combination of control variables that produces unphysical outcomes like negative CO``_{2e}`` concentrations.
Constraints can often be used to add meaning to an otherwise meaningless optimization problem. Consider the example above of minimizing the net costs of climate controls. Without any additional constraints, the solution to the problem is... to do nothing. Zero climate controls costs zero dollars. Suppose we now add in a constraint that the temperature change relative to pre-industrial must not exceed 2°C. While doing nothing still carries no climate control costs, it is no longer a solution to the problem since the resulting warming will overshoot the constraint by several degrees celsius. To see the solution to this problem, see the [Optimization of the default MARGO configuration](@ref) example.
Learn more about the currently implemented objective functions and constraints in [Optimization](@ref).
| ClimateMARGO | https://github.com/ClimateMARGO/ClimateMARGO.jl.git |
|
[
"MIT"
] | 0.3.3 | f958c49f3f4f812d6eb2725f102896a0ead72172 | docs | 25 | # Controls
Coming soon.
| ClimateMARGO | https://github.com/ClimateMARGO/ClimateMARGO.jl.git |
|
[
"MIT"
] | 0.3.3 | f958c49f3f4f812d6eb2725f102896a0ead72172 | docs | 26 | # Economics
Coming soon.
| ClimateMARGO | https://github.com/ClimateMARGO/ClimateMARGO.jl.git |
|
[
"MIT"
] | 0.1.0 | 50fb2cdc94b91ef5595612817c57a6616708739f | code | 412 | using Documenter, LockandKeyLookups
makedocs(;
modules=[LockandKeyLookups],
format=Documenter.HTML(),
pages=[
"Home" => "index.md",
],
repo="https://github.com/caseykneale/LockandKeyLookups.jl/blob/{commit}{path}#L{line}",
sitename="LockandKeyLookups.jl",
authors="Casey Kneale",
assets=String[],
)
deploydocs(;
repo="github.com/caseykneale/LockandKeyLookups.jl",
)
| LockandKeyLookups | https://github.com/caseykneale/LockandKeyLookups.jl.git |
|
[
"MIT"
] | 0.1.0 | 50fb2cdc94b91ef5595612817c57a6616708739f | code | 94 | module LockandKeyLookups
include("Lookups.jl")
export LockandKeyLookup
end # module
| LockandKeyLookups | https://github.com/caseykneale/LockandKeyLookups.jl.git |
|
[
"MIT"
] | 0.1.0 | 50fb2cdc94b91ef5595612817c57a6616708739f | code | 6599 | struct LockandKeyLookup{ A <: Function, B <: Function, C <: Function, K, T }
key::K
tumbler::T
key_lookup_fn::A
pin_lookup_fn::B
emission_fn::C
key_length::Int
tumblers::Vector{ Int }
end
#Sizes of the return collection cannot be known at run time! Base.SizeUnknown() is the secret sauce to make true Julia Generators!
Base.length(::LockandKeyLookup) = Base.SizeUnknown()
Base.IteratorSize(::LockandKeyLookup) = Base.SizeUnknown()
"""
LockandKeyLookup( key, tumbler,
key_lookup_fn, pin_lookup_fn,
emitter_fn = ( k, t ) -> key_lookup_fn( k ) == pin_lookup_fn( t ) )
Instantiates a `LockandKeyLookup` iterable object.
The `key` is the iterator to find a matching condition for across the `tumbler` iterators or internally called "pins".
the `_lookup_fn` functions are the functions used to `select` the data from each iteration for matching.
Ie: `key_lookup_fn` = row -> row[!, [ :id, :time, :address ] ]
`tumbler_lookup_fn` = row -> row[!, [ :row_id, :t, :Address ] ]
The `emitter_fn` is the function used to determine if there is infact a match, by default it asseses if the lookup functions equate.
"""
function LockandKeyLookup( key, tumbler,
key_lookup_fn, pin_lookup_fn,
emitter_fn = ( k, t ) -> k == t)
return LockandKeyLookup( key, tumbler,
key_lookup_fn, pin_lookup_fn,
emitter_fn,
first( size( key ) ), length.(tumbler) )
end
"""
get_smallest_pin( pin_values, not_nothing )::Int
An internal function for the tumbler portion of the iterator. It scans an array of available tumbler iterators - aka Pins - and finds the smallest index.
Note: In cases where there is a tie, the leftmost tied pin will be selected.
In cases where all pins are of type `Nothing` this function returns an integer value of 0.
"""
function get_smallest_pin( pin_values, not_nothing )::Int
is_something = sum( not_nothing )
if is_something == 0
return 0
elseif is_something == 1
return findfirst( not_nothing )
elseif is_something > 1
return findall( not_nothing )[ argmin( pin_values[ not_nothing ] ) ]
end
end
"""
unpack_2tuples( x )
This function unpacks collections of 2-tuples into 2 arrays in one pass.
Note: Nothings are handled by expanding into `(nothing, nothing)`
"""
unpack_2tuples( x ) = collect.(zip( [ isnothing( i ) ? [ i, i ] : i for i in x ]... ) )
"""
Base.iterate( lkl::LockandKeyLookup, state::T = ( iterate( lkl.key ), iterate.(lkl.tumbler) ) ) where T <: Any
This would be the main iterator for a given `LockandKeyLookup` instance.
"""
function Base.iterate( lkl::LockandKeyLookup, state::T = ( iterate( lkl.key ), iterate.(lkl.tumbler) ) ) where T <: Any
# Get Latest Key:Tumbler State
( key_value, key_state ), tumbler_values_and_states = state
tumbler_values_and_states = collect( tumbler_values_and_states )
tumbler_values_and_states = convert(Vector{ Union{ eltype(tumbler_values_and_states), Nothing } }, tumbler_values_and_states)
#( last( key_state ) > lkl.key_length ) && return nothing
tumbler_values, tumbler_states = unpack_2tuples( tumbler_values_and_states )
tumbler_values = convert(Vector{ Union{ eltype(tumbler_values), Nothing } }, tumbler_values)
tumbler_states = convert(Vector{ Union{ eltype(tumbler_states), Nothing } }, tumbler_states)
# Get Lowest Pin
get_key = lkl.key_lookup_fn( key_value )
tumbler_values = collect(tumbler_values)
notnothing = .!isnothing.( tumbler_values )
get_pins = map( x -> isnothing(x) ? x : lkl.pin_lookup_fn( x ), tumbler_values )
smallest_pin = get_smallest_pin( get_pins, notnothing )
(smallest_pin == 0) && return nothing
#pre-allocate output
key_idx, tumbler_idx, pin_idx = last(key_state), smallest_pin, last( tumbler_states[smallest_pin] )
# If match( Key, Lowest Pin )
if lkl.emission_fn( get_key, get_pins[ smallest_pin ] )
tumbler_idx = smallest_pin
pin_idx = last( tumbler_states[ smallest_pin ] )
values_and_states = Base.iterate( lkl.tumbler[ smallest_pin ], tumbler_states[ smallest_pin ] )
tumbler_values[ smallest_pin ], tumbler_states[ smallest_pin ] = isnothing( values_and_states ) ? [nothing,nothing] : values_and_states
#println("111 Kick tumbler match")
else
while ( !lkl.emission_fn( get_key, get_pins[ smallest_pin ] ) )
if get_key < get_pins[ smallest_pin ]
#println("222 Kick key")
while ( get_key < get_pins[ smallest_pin ] )
key_value_and_state = Base.iterate( lkl.key, key_state )
isnothing( key_value_and_state ) && return nothing
( key_value, key_state ) = key_value_and_state
get_key = lkl.key_lookup_fn( key_value )
end
key_idx = last( key_state )
elseif get_key > get_pins[smallest_pin]
#println("333 Kick tumbler")
while ( get_key > get_pins[ smallest_pin ] )
values_and_states = Base.iterate( lkl.tumbler[ smallest_pin ], tumbler_states[ smallest_pin ] )
tumbler_values[ smallest_pin ], tumbler_states[ smallest_pin ] = isnothing( values_and_states ) ? [nothing,nothing] : values_and_states
notnothing = .!isnothing.( tumbler_values )
get_pins = map( x -> isnothing(x) ? x : lkl.pin_lookup_fn( x ), tumbler_values )
smallest_pin = get_smallest_pin( get_pins, notnothing )
( smallest_pin == 0 ) && return nothing
end
key_idx = last( key_state )
end
#Update the tumbler if we have a match
tumbler_idx = smallest_pin
pin_idx = last( tumbler_states[ smallest_pin ] )
if lkl.emission_fn( get_key, get_pins[ smallest_pin ] )
values_and_states = Base.iterate( lkl.tumbler[ smallest_pin ], tumbler_states[ smallest_pin ] )
tumbler_values[ smallest_pin ], tumbler_states[ smallest_pin ] = isnothing( values_and_states ) ? [nothing,nothing] : values_and_states
end
end
end
return ( key_idx => ( tumbler_idx, pin_idx ) ), ( ( key_value, key_state ) , zip( tumbler_values, tumbler_states ) )
end
| LockandKeyLookups | https://github.com/caseykneale/LockandKeyLookups.jl.git |
|
[
"MIT"
] | 0.1.0 | 50fb2cdc94b91ef5595612817c57a6616708739f | code | 5013 | using LockandKeyLookups
using Test, DataFrames
#DEVELOPERS: Useful snippit for debugging
# for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b ] ), X -> X.a, X -> X.b )
# println( i )
# println(b[i[2][2],:b])
# end
@testset "LockandKeyLookups - iterations" begin
# examples...
endrng = 3
a = DataFrame( Dict( :a => 1:1:endrng, :b => 1:1:endrng ) )
b = DataFrame( Dict( :b => 1:1:endrng, :c => 1:1:endrng ) )
#Test single stream complete match
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b ] ), X -> X.a, X -> X.b ) ]
@test all( LKL_result .== [ 1 => ( 1, 1 ) , 2 => ( 1, 2 ), 3 => ( 1, 3 ) ] )
#Test two streams complete match
c = DataFrame( Dict( :b => 1:1:endrng, :c => 1:1:endrng ) )
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b, c ] ), X -> X.a, X -> X.b ) ]
@test all( LKL_result .== [ 1 => ( 1, 1 ), 1 => ( 2, 1 ), 2 => ( 1, 2 ), 2 => ( 2, 2 ), 3 => ( 1, 3 ), 3 => ( 2, 3 ) ] )
#Test 3 streams with heterogeniety of matches
endrng = 10
a = DataFrame( Dict( :a => 1:1:endrng, :b => 1:1:endrng ) )
b = DataFrame( Dict( :b => 1:5:endrng, :c => 1:5:endrng ) )
c = DataFrame( Dict( :b => 6:7:endrng, :c => 6:7:endrng ) )
d = DataFrame( Dict( :b => 6:7:endrng, :c => 6:7:endrng ) )
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b, c, d ] ), X -> X.a, X -> X.b ) ]
@test all( LKL_result .== [ 1 => ( 1, 1 ) , 6 => ( 1, 2 ), 6 => ( 2, 1 ), 6 => ( 3, 1 ) ] )
endrng = 5
a = DataFrame( Dict( :a => 1:2:endrng, :b => 1:2:endrng ) )
b = DataFrame( Dict( :b => 1:1:endrng, :c => 1:1:endrng ) )
#Test sparse key stream!
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b ] ), X -> X.a, X -> X.b ) ]
@test all( LKL_result .== [ 1 => ( 1, 1 ) , 2 => ( 1, 3 ), 3 => ( 1, 5 ) ] )
c = DataFrame( Dict( :b => 1:2:endrng, :c => 1:2:endrng ) )
#Test sparse key stream with 2 pins!
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b, c ] ), X -> X.a, X -> X.b ) ]
@test all( LKL_result .== [ 1 => ( 1, 1 ), 1 => ( 2, 1 ), 2 => ( 1, 3 ), 2 => ( 2, 2 ), 3 => ( 1, 5 ), 3 => ( 2, 3 ) ] )
b = DataFrame( Dict( :b => 2:2:endrng, :c => 2:2:endrng ) )
#Test sparse key stream with NO matches!
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b ] ), X -> X.a, X -> X.b ) ]
@test isempty( LKL_result )
c = DataFrame( Dict( :b => 2:2:20, :c => 2:2:20 ) )
#Test sparse key stream with 2 streams that have NO matches!
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b, c ] ), X -> X.a, X -> X.b ) ]
@test isempty( LKL_result )
a = DataFrame( Dict( :a => 101:2:111, :b => 101:2:111 ) )
b = DataFrame( Dict( :b => 20:1:25, :c => 20:1:25 ) )
c = DataFrame( Dict( :b => 107:1:115, :c => 107:1:115 ) )
#Sparse stream some matching some not
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b,c ] ), X -> X.a, X -> X.c ) ]
@test all( LKL_result .== [ 4 => ( 2, 1 ) , 5 => ( 2, 3 ), 6 => ( 2, 5 ) ] )
end
@testset "LockandKeyLookups - Arbitrary functions" begin
a = DataFrame( Dict( :a => 7:1:11, :b => 7:1:11 ) )
b = DataFrame( Dict( :b => 1:1:22, :c => 1:1:22 ) )
#test changing a value
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b ] ), X -> X.a,
X -> X.b/2.0 ) ]
@test all( LKL_result .== [ 1 => ( 1, 14 ) , 2 => ( 1, 16 ), 3 => ( 1, 18 ), 4 => ( 1, 20 ), 5 => ( 1, 22 ) ] )
#test changing a comparator but not really
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b ] ), X -> X.a,
X -> X.b / 2.0, (k, t) -> (1.0 .* k) == (t ./ 1.0) ) ]
println(LKL_result)
@test all( LKL_result .== [ 1 => ( 1, 14 ) , 2 => ( 1, 16 ), 3 => ( 1, 18 ), 4 => ( 1, 20 ), 5 => ( 1, 22 ) ] )
end
@testset "LockandKeyLookups - Internal code tests..." begin
a = DataFrame( Dict( :a => 1:1:11, :b => 1:1:11 ) )
b = DataFrame( Dict( :b => 1:1:11, :c => 1:1:11 ) )
#test changing a value
LKL_iterator = LockandKeyLookup( eachrow( a ), eachrow.( [ b ] ), X -> X.a, X -> X.b )
@test length( LKL_iterator ) == Base.SizeUnknown()
@test Base.IteratorSize( LKL_iterator ) == Base.SizeUnknown()
#
@test all( LockandKeyLookups.unpack_2tuples( [(1,2), (3,4)] ) .== [[1,3], [2,4] ])
@test all( LockandKeyLookups.unpack_2tuples( [(1,2), nothing, (3,4)] ) .== [[1,nothing,3], [2,nothing,4] ])
end
@testset "LockandKeyLookups - run simple test with arrays" begin
# examples...
a = [ [ 1 2 ];
[ 3 4 ];
[ 5 6] ]
b = [ [ 1 2 ];
[ 3 4 ];
[ 5 6] ]
#Test single stream complete match
LKL_result = [ i for i in LockandKeyLookup( eachrow( a ), eachrow.( [ b ] ), X -> X[:,1], X -> X[:,1] ) ]
@test all( LKL_result .== [ 1 => ( 1, 1 ) , 2 => ( 1, 2 ), 3 => ( 1, 3 ) ] )
end
| LockandKeyLookups | https://github.com/caseykneale/LockandKeyLookups.jl.git |
|
[
"MIT"
] | 0.1.0 | 50fb2cdc94b91ef5595612817c57a6616708739f | docs | 2280 | # LockandKeyLookups
[](https://caseykneale.github.io/LockandKeyLookups.jl/stable)
[](https://caseykneale.github.io/LockandKeyLookups.jl/dev)
[](https://travis-ci.com/caseykneale/LockandKeyLookups.jl)
[](https://codecov.io/gh/caseykneale/LockandKeyLookups.jl)
Ever have `J` streams of data that, maybe don't fit so well in memory. Well you can lazy load them! But... what if you want to do lookups/labelling tasks with some primary Key in another dataframe(`i` rows long)? Do you really want to run the cost of iterating `i` times to do `J` joins? Probably not - well maybe, but - probably not.
That's where LockandKeyLookups comes into play. LockandKeyLookups are iterators that can be instantiated like the following:
```Julia
lakl = LockandKeyLookup( key, tumbler,
key_lookup_fn, pin_lookup_fn,
emitter_fn = ( k, t ) -> k == t)
```
Where the `tumbler` is some array of iterables like `DataFrames`, key is some iterable, and the arguments labelled `_fn` are functions that do the following:
- `key_lookup_fn` & `pin_lookup_fn` : are the functions used to index the key and tumbler pins for a match condition.
- `emitter_fn` : is the function used to assess whether the result of the lookup_fn's between a key and a given pin is satisfied.
so we can iterate these instances in for loops, or collections as usual.
```Julia
[ iter for iter in lakl ]
```
where the structure of the `iter` item is the following `( Key_Index[i] => ( Tumbler_Index[J], Pin_Index[Q] ) ) = iter `
So this gives us a mapping between a single key, and a single pin at a time.

## Caveats
- The items must be sorted by the associated key for this to work!
- Only tested with DataFrames `each(row)` iterables so far.
- Might not be the fastest option. But it's not very steppy, and should work with lazy iterators.
| LockandKeyLookups | https://github.com/caseykneale/LockandKeyLookups.jl.git |
|
[
"MIT"
] | 0.1.0 | 50fb2cdc94b91ef5595612817c57a6616708739f | docs | 86 | # LockandKeyLookups.jl
```@index
```
```@autodocs
Modules = [LockandKeyLookups]
```
| LockandKeyLookups | https://github.com/caseykneale/LockandKeyLookups.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 577 | using Documenter
makedocs(
sitename="Fable.jl",
authors="James Schloss (Leios) and contributors",
pages = [
"General Information" => "index.md",
"Layering" => "layering.md",
"Time Interface" => "time_interface.md",
"Post Processing" => "postprocessing.md",
"Research Directions" => "research_directions.md",
"Examples" => Any[
"Rotating Square" => "examples/swirled_square.md",
"Simple Smears" => "examples/smear.md",
],
],
)
deploydocs(;
repo="github.com/leios/Fable.jl",
)
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1719 | #-------------barnsley.jl------------------------------------------------------#
# This is a simple test to make sure Fable.jl can deal with H operators with
# non-uniform probability. It also shows how to output multiple objects.
#------------------------------------------------------------------------------#
using Fable
scale_and_translate = @fum function scale_and_translate(y, x;
translation = (0.0,0.0),
scale = 1.0)
x = scale*x + translation[2]
y = scale*y + translation[1]
return point(y,x)
end
function barnsley_example(num_particles, num_iterations;
ArrayType = Array,
filename = "out.png")
pos = [0, 0.]
radius = 1
color_1 = [1.,1,1,1]
color_2 = [1.,0,0,1]
color_3 = [0.,1,0,1]
color_4 = [0.,0,1,1]
H = define_barnsley(; color = [color_1, color_2, color_3, color_4])
fo_1 = fo(Flames.identity, Shaders.previous, 1)
fo_2 = fo(scale_and_translate(translation = (0.5, 0.5), scale = 0.5),
Shaders.magenta, 1)
H2 = fee(Hutchinson, (fo_1, fo_2))
layer = FractalLayer(; ArrayType = ArrayType,
world_size = (10, 16), position = (5, 0),
ppu = 1920/16, num_particles = num_particles,
num_iterations = num_iterations, H1 = H, H2 = H2)
run!(layer)
write_image([layer], filename = filename)
end
@info("Created Function: barnsley_example(num_particles, num_iterations;
ArrayType = Array,
filename = 'out.png')")
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 377 | using Fable, Images
function image_example(; input_filename = "check.png",
output_filename = "check_copy.png")
il = ImageLayer(input_filename)
write_image(il; filename = output_filename)
end
@info("Created Function: image_example(; input_filename = 'check.png',
output_filename = 'check_copy.png')")
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 919 | using Fable, Images
function layering_example(num_particles, num_iterations; ArrayType = Array)
world_size = (9*0.15, 16*0.15)
ppu = 1920/world_size[2]
square = define_rectangle(position = [0.0,0.0],
rotation = pi/4,
color = RGBA(1,0,1))
flayer = FractalLayer(; ArrayType = ArrayType, H1 = square,
world_size = world_size, ppu = ppu,
num_particles = num_particles,
num_iterations = num_iterations)
clayer = ColorLayer(RGB(0.5, 0.5, 0.5); world_size = world_size, ppu = ppu,
ArrayType = ArrayType)
layers = [clayer, flayer]
run!(layers)
write_image(layers; filename = "out.png")
end
@info("Created Function: layering_example(num_particles, num_iterations;
ArrayType = Array)")
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 3760 | using Fable, Images
function quick_circle(num_particles, num_iterations; ArrayType = Array,
filename = "out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType)
run!(fl)
write_image(fl; filename = filename)
end
function clip_example(num_particles, num_iterations; ArrayType = Array,
filename = "clip_out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
clip = Clip(; threshold = 0.5, color = RGBA(1, 1, 0, 1))
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [clip])
run!(fl)
write_image(fl; filename = filename)
end
function identity_example(num_particles, num_iterations; ArrayType = Array,
filename = "identity_out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
identity = Identity()
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [identity])
run!(fl)
write_image(fl; filename = filename)
end
function blur_example(num_particles, num_iterations; ArrayType = Array,
filter_size = 3, filename = "blur_out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
blur = Blur(; filter_size = filter_size)
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [blur])
run!(fl)
write_image(fl; filename = filename)
end
function sobel_example(num_particles, num_iterations; ArrayType = Array,
filename = "sobel_out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
sobel = Sobel()
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [sobel])
run!(fl)
write_image(fl; filename = filename)
end
function outline_example(num_particles, num_iterations; ArrayType = Array,
filename = "outline_out.png", linewidth = 1,
object_outline = false)
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
outline = Outline(; linewidth = linewidth, object_outline = object_outline)
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [outline])
run!(fl)
write_image(fl; filename = filename)
end
@info("Created Functions: quick_circle(num_particles, num_iterations;
ArrayType = Array, filename = 'out.png')
clip_example(num_particles, num_iterations;
ArrayType = Array,
filename = 'clip_out.png')
identity_example(num_particles, num_iterations;
ArrayType = Array,
filename = 'identity_out.png')
blur_example(num_particles, num_iterations;
ArrayType = Array, filter_size = 3,
filename = 'blur_out.png')
sobel_example(num_particles, num_iterations;
ArrayType = Array,
filename = 'sobel_out.png')
outline_example(num_particles, num_iterations;
ArrayType = Array,
filename = 'outline_out.png',
linewidth = 1,
object_outline = false)")
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1462 | using Fable
using Images
radial = @fum shader function radial(y, x; origin = (0,0))
r = sqrt((x-origin[2])*(x-origin[2]) + (y-origin[1])*(y-origin[1]))
red = 1
green = min(1, 1/r)
blue = 1
alpha = min(1, 1/r)
return RGBA{Float32}(red, green, blue, alpha)
end
rectangle = @fum shader function rectangle(; position = (0,0), rotation = 0,
scale_x = 1, scale_y = 1)
if in_rectangle(x, y, position, rotation, scale_x, scale_y)
return RGBA(1,1,1,1)
end
return color
end
ellipse = @fum shader function ellipse(; position = (0,0), rotation = 0,
r1 = 1, r2 = 1)
if in_ellipse(x, y, position, rotation, r1, r2)
return RGBA{Float32}(1,1,1,1)
else
return RGBA{Float32}(0,0,0,0)
end
end
function shader_example(fum; ArrayType = Array, filename = "out.png")
layer = ShaderLayer(fum; ArrayType = ArrayType, world_size = (9/4, 4),
ppu = 1920/4)
run!(layer)
write_image(layer; filename = filename)
end
@info("Created Function: shader_example(fum; ArrayType = Array,
filename = 'out.png')\n"*
"Defined fums: rectangle(; position = (0,0), rotation = 0,
scale_x = 1, scale_y = 1)
ellipse(; position = (0,0), rotation = 0,
r1 = 1, r2 = 1)
radial(y, x; origin = (0,0))")
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2619 | using Fable
function sierpinski_example(num_particles, num_iterations, num_frames;
ArrayType = Array, output_type = :video)
if output_type == :video
video_out = open_video((1080, 1920); framerate = 30,
filename = "out.mp4")
end
theta = 0
r = 1
A_1 = fi(:A_1, [r*cos(theta), r*sin(theta)])
B_1 = fi(:B_1, [r*cos(theta + 2*pi/3), r*sin(theta + 2*pi/3)])
C_1 = fi(:C_1, [r*cos(theta + 4*pi/3), r*sin(theta + 4*pi/3)])
A_2 = fi(:A_2, [r*cos(-theta), r*sin(-theta)])
B_2 = fi(:B_2, [r*cos(-theta + 2*pi/3), r*sin(-theta + 2*pi/3)])
C_2 = fi(:C_2, [r*cos(-theta + 4*pi/3), r*sin(-theta + 4*pi/3)])
H = define_triangle(; A = A_1, B = B_1, C = C_1,
color = [[1.0, 0.0, 0.0, 1.0],
[0.0, 1.0, 0.0, 1.0],
[0.0, 0.0, 1.0, 1.0]],
chosen_fx = :sierpinski)
H_2 = define_triangle(A = A_2, B = B_2, C = C_2,
color = [[0.0, 1.0, 1.0, 1.0],
[1.0, 0.0, 1.0, 1.0],
[1.0, 1.0, 0.0, 1.0]],
chosen_fx = :sierpinski)
final_H = fee(Hutchinson, [H, H_2])
layer = FractalLayer(; ArrayType = ArrayType, logscale = false,
world_size = (2.25, 4), ppu = 1920/4,
num_iterations = num_iterations,
num_particles = num_particles, H1 = final_H)
for i = 1:num_frames
theta = 2*pi*(i-1)/num_frames
set!(A_1, [r*cos(theta), r*sin(theta)])
set!(B_1, [r*cos(theta + 2*pi/3), r*sin(theta + 2*pi/3)])
set!(C_1, [r*cos(theta + 4*pi/3), r*sin(theta + 4*pi/3)])
set!(A_2, [r*cos(-theta), r*sin(-theta)])
set!(B_2, [r*cos(-theta + 2*pi/3), r*sin(-theta + 2*pi/3)])
set!(C_2, [r*cos(-theta + 4*pi/3), r*sin(-theta + 4*pi/3)])
run!(layer)
if output_type == :video
write_video!(video_out, [layer])
elseif output_type == :image
filename = "check"*lpad(i,5,"0")*".png"
write_image([layer]; filename=filename)
end
zero!(layer)
end
if (output_type == :video)
close_video(video_out)
end
end
@info("Created Function: sierpinski_example(num_particles, num_iterations,
num_frames; ArrayType = Array,
output_type = :video)\n"*
"output_type can be {:video, :image}")
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2508 | using Fable
function smear_example(num_particles, num_iterations, total_frames;
ArrayType = Array, output_type = :video)
FloatType = Float32
# define image domain
world_size = (9, 16)
ppu = 1920 / 16
res = (1080, 1920)
layer = FractalLayer(; ArrayType = ArrayType, FloatType = FloatType,
world_size = world_size, ppu = ppu,
num_particles = num_particles,
num_iterations = num_iterations)
# defining video parameters
if output_type == :video
video_out = open_video(res; framerate = 30, filename = "out.mp4")
end
# define ball parameters
object_position = fi("object_position", [-2.0, -2.0])
ball = define_circle(; position = object_position,
radius = 1.0,
color = (1,1,1))
# fractal inputs to track changes in position, scale, and theta for smear
scale = fi("scale", (1,1))
theta = fi("theta", 0)
# first defining the fractal user method
smear = Smears.stretch_and_rotate(object_position = object_position,
scale = scale, theta = theta)
# now turning it into a fractal operator
smear_transform = fee(Hutchinson, fo(smear))
layer.H1 = ball
layer.H2 = smear_transform
for i = 1:total_frames
# changing ball position
radius = 1.0
pos = [-2.0+4*(i-1)/(total_frames-1),
-2.0+4*(i-1)/(total_frames-1)]
# creating a value that grows as it gets closer to total_frames / 2
# and shrinks as it gets closer to total_frames
scale_x = 2 - abs((i-1)*2-(total_frames-1))/(total_frames-1)
# modifying fractal inputs for smear
set!(object_position, pos)
set!(scale, (1,scale_x))
set!(theta, pi/4)
run!(layer)
if output_type == :video
write_video!(video_out, [layer])
elseif output_type == :image
filename = "check"*lpad(i,5,"0")*".png"
write_image([layer]; filename=filename)
end
# clearing frame
zero!(layer)
end
if (output_type == :video)
close_video(video_out)
end
end
@info("Created Function: smear_example(num_particles, num_iterations,
total_frames; ArrayType = Array,
output_type = :video)\n"*
"output_type can be {:video, :image}")
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1895 | using Fable, Images
# num_particles is the number of points being tracked by the chaos game
# num_iterations is the number of times each point moves in space
# ArrayType dictates what hardware you run this code on:
# CuArray for NVIDIA GPUs
# ROCArray for AMD GPUs
# Array for parallel CPU
function square_example(num_particles, num_iterations;
ArrayType = Array,
dark = true,
transform_type = :standard,
filename = "out.png")
# Physical space location.
world_size = (9*0.15, 16*0.15)
# Pixels per unit space
# The aspect ratio is 16x9, so if we want 1920x1080, we can say we want...
ppu = 1920/world_size[2]
colors = [[1.0, 0.25, 0.25,1],
[0.25, 1.0, 0.25, 1],
[0.25, 0.25, 1.0, 1],
[1.0, 0.25, 1.0, 1]]
H = define_square(; position = [0.0, 0.0], rotation = pi/4, color = colors)
swirl_operator = fo(Flames.swirl)
H2 = nothing
if transform_type == :outer_swirl
H2 = Hutchinson(swirl_operator)
elseif transform_type == :inner_swirl
H = fee(Hutchinson, [H, Hutchinson(swirl_operator)])
end
layer = FractalLayer(; ArrayType = ArrayType, logscale = false,
world_size = world_size, ppu = ppu,
H1 = H, H2 = H2,
num_particles = num_particles,
num_iterations = num_iterations)
run!(layer)
write_image(layer; filename = filename)
end
@info("Created Function: square_example(num_particles, num_iterations;
ArrayType = Array,
transform_type = :standard,
filename = 'out.png')\n"*
"transform_type can be {:standard, :inner_swirl, :outer_swirl}")
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1568 | module Fable
using KernelAbstractions
using KernelAbstractions: @atomic
using MacroTools
using Unitful
using Images
using VideoIO
# Constants
global OUTPUT = true
set_output(tf) = (global OUTPUT = tf)
# Interfaces
include("structs/time.jl")
include("structs/point.jl")
# Utilities
include("utils/extras.jl")
# Geometries
include("utils/geometries.jl")
# KA kernels
include("utils/histogram.jl")
# Fractal flame structures
include("structs/fractal_input.jl")
include("structs/fractal_user_methods.jl")
include("fums/shaders.jl")
include("structs/fractal_operators.jl")
include("structs/fractal_executable/fractal_executable.jl")
include("structs/fractal_executable/hutchinson.jl")
include("structs/fractal_executable/shader.jl")
# Operations
include("utils/simple_rng.jl")
include("fums/flames.jl")
include("fums/smears.jl")
# Shapes
include("objects/rectangle.jl")
include("objects/circle.jl")
include("objects/triangle.jl")
include("objects/barnsley.jl")
# IO
include("structs/layers/layers.jl")
include("io/postprocess/postprocess.jl")
include("structs/layers/fractal_layer.jl")
include("structs/layers/color_layer.jl")
include("structs/layers/image_layer.jl")
include("structs/layers/shader_layer.jl")
include("structs/video_params.jl")
include("io/io_tools.jl")
# PostProcessing
include("io/postprocess/clip.jl")
include("io/postprocess/filter.jl")
include("io/postprocess/sobel.jl")
include("io/postprocess/outline.jl")
# Main file
include("run/run.jl")
include("run/fractal_flame.jl")
include("run/shader.jl")
include("run/color.jl")
end # module
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 3018 | export Flames
module Flames
import Fable.@fum
import Fable.point
identity = @fum function identity(y, x)
return point(y, x)
end
scale = @fum function scale(y, x; scale = (1,1))
x = scale[2]*x
y = scale[1]*y
return point(y,x)
end
scale_and_translate = @fum function scale_and_translate(y, x;
translation = (0,0),
scale = (1, 1))
x = scale[2]*x + translation[2]
y = scale[1]*y + translation[1]
return point(y,x)
end
perspective = @fum function perspective(y, x; theta = 0.5*pi, dist = 1)
C = dist/(dist - y*sin(theta))
x *= C
y *= C*cos(theta)
return point(y,x)
end
cloud = @fum function cloud(x, y)
x *= 2
y = -(y+exp(-abs(y+2)^2/2))
return point(y,x)
end
waves = @fum function waves(y, x; c = 1, f = 1, b = 1, e = 1)
x_temp = x
x += b * sin(y/c^2)
y += e * sin(x_temp/f^2)
return point(y,x)
end
fae_cross = @fum function fae_cross(y, x)
val = sqrt(1/(x^2 + y^2)^2)
x *= val
y *= val
return point(y,x)
end
fan = @fum function fan(y, x; c = 1, f = 1)
t = pi*c^2
theta = atan(y,x)
r = sqrt(x^2+y^2)
if (theta + f) % t > 0.5*t
x = r*cos(theta - 0.5*t)
y = r*sin(theta - 0.5*t)
elseif (theta + f) % t <= 0.5*t
x = r*cos(theta + 0.5*t)
y = r*sin(theta + 0.5*t)
end
return point(y,x)
end
popcorn = @fum function popcorn(y, x; c = 1, f = 1)
x_temp = x
x += c*sin(tan(3*y))
y += f*sin(tan(3*x_temp))
return point(y,x)
end
shift = @fum function shift(y, x; loc = (0,0))
x += loc[2]
y += loc[1]
return point(y,x)
end
antibubble = @fum function antibubble(y, x)
r2 = (x*x + y*y)
c = r2/4
x = c*x
y = c*y
return point(y,x)
end
bubble = @fum function bubble(y, x)
r2 = (x*x + y*y)
c = 4/(4+r2)
x = c*x
y = c*y
return point(y,x)
end
halfway = @fum function halfway(y, x; loc=(0,0))
x = 0.5*(loc[2] + x)
y = 0.5*(loc[1] + y)
return point(y,x)
end
sinusoidal = @fum function sinusoidal(y, x)
x = sin(x)
y = sin(y)
return point(y,x)
end
polar = @fum function polar(y, x)
r = sqrt(sum(x*x + y*y))
theta = atan(y, x)
y = r-1
x = theta/pi
return point(y,x)
end
horseshoe = @fum function horseshoe(y, x)
r = sqrt(x*x + y*y)
if r < 0.001
r = 0.001
end
v1 = (x-y)*(x+y)/r
v2 = 2*x*y/r
x = v1
y = v2
return point(y,x)
end
heart = @fum function heart(y, x)
r = sqrt(x*x + y*y)
theta = atan(y, x)
y = -r*cos(theta*r)
x = r*sin(theta*r)
return point(y,x)
end
rotate = @fum function rotate(y, x; theta = 0.5*pi)
x = x*cos(theta) - y*sin(theta)
y = x*sin(theta) + y*cos(theta)
return point(y,x)
end
swirl = @fum function swirl(y, x)
r = sqrt(y*y + x*x)
v1 = x*cos(r*r) + y*sin(r*r)
v2 = x*sin(r*r) - y*cos(r*r)
y = v1
x = v2
return point(y,x)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1994 | export Shaders, create_color
module Shaders
import Fable.@fum
import Images.RGBA
custom = @fum color custom(; r = 0, g = 0, b = 0, a = 0) = RGBA{Float32}(r, g, b, a)
previous = @fum color previous() = color
red = @fum color red() = RGBA{Float32}(1, 0, 0, 1)
green = @fum color green() = RGBA{Float32}(0,1,0,1)
blue = @fum color blue() = RGBA{Float32}(0,0,1,1)
magenta = @fum color magenta() = RGBA{Float32}(1,0,1,1)
white = @fum color white() = RGBA{Float32}(1,1,1,1)
black = @fum color black() = RGBA{Float32}(0,0,0,1)
gray = @fum color gray() = RGBA{Float32}(0.5, 0.5, 0.5, 1)
grey = gray
end
create_color(a::FractalUserMethod) = a
function create_color(a::Union{Array, Tuple})
if length(a) == 3
return Shaders.custom(r = a[1], g = a[2], b = a[3], a = 1)
elseif length(a) == 4
return Shaders.custom(r = a[1], g = a[2], b = a[3], a = a[4])
else
error("Colors must have either 3 or 4 elements!")
end
end
function create_color(a::RGB)
return Shaders.custom(r = a.r, g = a.g, b = a.b, a = 1)
end
function create_color(a::RGBA)
return Shaders.custom(r = a.r, g = a.g, b = a.b, a = a.alpha)
end
function define_color_operators(color::Union{RGBA, RGB, FractalUserMethod};
fnum = 4)
color = create_color(color)
return [color for i = 1:fnum]
end
function define_color_operators(t_color::Union{Tuple, Vector}; fnum = 4)
if eltype(t_color) <: FractalUserMethod
return [t_color for i = 1:fnum]
end
if length(t_color) == 1
color = create_color(t_color[1])
return [color for i = 1:fnum]
elseif eltype(t_color) <: Number
color = create_color(t_color)
return [color for i = 1:fnum]
elseif length(t_color) == fnum
return [create_color(t_color[i]) for i = 1:fnum]
else length(t_color) != fnum
error("Expected color tuple of length "*string(fnum)*" or 1!\n"*
"Got "*string(length(t_color))*" instead!")
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1033 | export Smears
module Smears
import Fable.@fum
import Fable.point
stretch_and_rotate = @fum function stretch_and_rotate(
y,x;
object_position = (0,0),
scale = (1,1),
theta = 0)
y = (y - object_position[1])*scale[1]
x = (x - object_position[2])*scale[2]
temp_x = x*cos(theta) - y*sin(theta)
temp_y = x*sin(theta) + y*cos(theta)
x = temp_x + object_position[2]
y = temp_y + object_position[1]
return point(y,x)
end
simple_smear = @fum function simple_smear(y,x;
object_position = (0,0),
previous_position = (0.0),
previous_velocity = (0.0),
factor = 10)
temp = abs.(object_position .- previous_position)
temp = ((temp .- previous_velocity) ./ factor) .+ 1
x = (x-object_position[2])*temp[2] + object_position[2]
y = (y-object_position[1])*temp[1] + object_position[1]
return point(y,x)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 7128 | export write_image, write_video!, zero!, reset!, create_canvas, mix_layers!
function mix_layers!(layer_1::AL1, layer_2::AL2;
mode = :simple) where {AL1 <: AbstractLayer,
AL2 <: AbstractLayer}
if AL1 <: FractalLayer
to_canvas!(layer_1)
end
if AL2 <: FractalLayer
to_canvas!(layer_2)
end
overlap = find_overlap(layer_1, layer_2)
mix_layers!(layer_1, layer_2, overlap)
end
function mix_layers!(layer_1::AL1, layer_2::AL2, overlap::Overlap; op = +,
mode = :simple) where {AL1 <: AbstractLayer,
AL2 <: AbstractLayer}
if mode == :simple
if layer_1.ppu != layer_2.ppu
@warn("Pixels per unit between layer 1 and 2 are not the same!
Rescaling second layer...")
f = simple_rescale_kernel!
else
f = simple_layer_kernel!
end
else
error("Mixing mode ", string(mode), " not found!")
end
backend = get_backend(layer_1.canvas)
kernel! = f(backend, layer_1.params.numthreads)
if layer_1.ppu == layer_2.ppu
kernel!(layer_1.canvas, layer_2.canvas,
overlap.start_index_1, overlap.start_index_2, op,
ndrange = overlap.range)
else
bounds_2 = find_bounds(layer_2)
kernel!(layer_1.canvas, layer_2.canvas, overlap.bounds, bounds_2,
layer_2.ppu, overlap.start_index_1, overlap.start_index_2, op,
ndrange = overlap.range)
end
end
@kernel function simple_layer_kernel!(canvas_1, canvas_2,
start_index_1, start_index_2, op)
tid = @index(Global, Cartesian)
idx_1 = CartesianIndex(Tuple(tid) .+ Tuple(start_index_1) .- (1,1))
idx_2 = CartesianIndex(Tuple(tid) .+ Tuple(start_index_2) .- (1,1))
if canvas_2[idx_2].alpha > 0
@inbounds r = op(canvas_1[idx_1].r*(1-canvas_2[idx_2].alpha),
canvas_2[idx_2].r*canvas_2[idx_2].alpha)
@inbounds g = op(canvas_1[idx_1].g*(1-canvas_2[idx_2].alpha),
canvas_2[idx_2].g*canvas_2[idx_2].alpha)
@inbounds b = op(canvas_1[idx_1].b*(1-canvas_2[idx_2].alpha),
canvas_2[idx_2].b*canvas_2[idx_2].alpha)
@inbounds a = max(canvas_1[idx_1].alpha, canvas_2[idx_2].alpha)
@inbounds canvas_1[idx_1] = RGBA(r,g,b,a)
end
end
@kernel function simple_rescale_kernel!(canvas_1, canvas_2,
bounds, bounds_2, ppu_2,
start_index_1, start_index_2, op)
tid = @index(Global, Cartesian)
idx_1 = CartesianIndex(Tuple(tid) .+ Tuple(start_index_1) .- (1,1))
res = @ndrange()
@inbounds y = bounds.ymin + (tid[1]/res[1])*(bounds.ymax - bounds.ymin)
@inbounds x = bounds.xmin + (tid[2]/res[2])*(bounds.xmax - bounds.xmin)
idx_2 = find_bin(canvas_2, x, y, bounds_2, (1/ppu_2, 1/ppu_2))
if canvas_2[idx_2].alpha > 0
@inbounds r = op(canvas_1[idx_1].r*(1-canvas_2[idx_2].alpha),
canvas_2[idx_2].r*canvas_2[idx_2].alpha)
@inbounds g = op(canvas_1[idx_1].g*(1-canvas_2[idx_2].alpha),
canvas_2[idx_2].g*canvas_2[idx_2].alpha)
@inbounds b = op(canvas_1[idx_1].b*(1-canvas_2[idx_2].alpha),
canvas_2[idx_2].b*canvas_2[idx_2].alpha)
@inbounds a = max(canvas_1[idx_1].alpha, canvas_2[idx_2].alpha)
@inbounds canvas_1[idx_1] = RGBA(r,g,b,a)
end
end
function create_canvas(s; ArrayType = Array)
return ArrayType(fill(RGBA(0,0,0,0), s))
end
function zero!(a::AT) where AT <: AbstractArray{T} where T <: Union{RGB, RGBA}
a[:] .= RGBA(0.0, 0.0, 0.0, 0.0)
end
function zero!(layer::AL) where AL <: AbstractLayer
layer.canvas[:] .= RGBA(0.0, 0.0, 0.0, 0.0)
end
function zero!(layer::FractalLayer)
backend = get_backend(layer.canvas)
kernel! = zero_kernel!(backend, layer.params.numthreads)
kernel!(layer.values, layer.reds, layer.greens, layer.blues,
ndrange = size(layer.values))
end
@kernel function zero_kernel!(layer_values, layer_reds, layer_greens, layer_blues)
tid = @index(Global, Cartesian)
layer_values[tid] = 0
layer_reds[tid] = 0
layer_greens[tid] = 0
layer_blues[tid] = 0
end
function reset!(layers::Vector{AL}) where AL <: AbstractLayer
for i = 1:length(layers)
reset!(layers[i])
end
end
function reset!(a::Array{T};
numthreads = 256, numcores = 4) where T <: Union{RGB, RGB{N0f8}}
zero!(a; numthreads = numthreads, numcores = numcores)
end
function reset!(layer::AL) where AL <: AbstractLayer
zero!(layer)
end
function reset!(layer::ColorLayer)
layer.canvas .= layer.color
end
function write_image(layer;
filename::Union{Nothing, String} = nothing,
reset = true,
img = fill(RGBA{Float32}(0,0,0),
size(layer.canvas)))
postprocess!(layer)
img .= Array(layer.canvas)
if reset
reset!(layer)
end
if isnothing(filename) || !OUTPUT
return img
else
save(filename, img)
println(filename)
end
end
function write_image(layers::Vector{AL};
filename::Union{Nothing, String} = nothing,
reset = true,
img = fill(RGBA{Float32}(0,0,0,0),
size(layers[1].canvas))) where AL<:AbstractLayer
postprocess!(layers[1])
for i = 2:length(layers)
postprocess!(layers[i])
mix_layers!(layers[1], layers[i]; mode = :simple)
end
img .= Array(layers[1].canvas)
if reset
reset!(layers)
end
if isnothing(filename) || !OUTPUT
return img
else
save(filename, img)
println(filename)
end
end
function write_video!(v::VideoParams,
layers::Vector{AL};
reset = true) where AL <: AbstractLayer
postprocess!(layers[1])
for i = 2:length(layers)
postprocess!(layers[i])
mix_layers!(layers[1], layers[i]; mode = :simple)
end
v.frame .= Array(layers[1].canvas)
if OUTPUT
write(v.writer, v.frame)
end
zero!(v.frame)
if reset
reset!(layers)
end
println(v.frame_count)
v.frame_count += 1
end
# in the case OUTPUT = false
function write_video!(n::Nothing, layers::Vector{AL};
reset = true) where AL <: AbstractLayer
postprocess!(layers[1])
for i = 2:length(layers)
postprocess!(layers[i])
mix_layers!(layers[1], layers[i]; mode = :simple)
end
if reset
reset!(layers)
end
end
function write_image(img::Array{CT};
filename::Union{Nothing, String} = nothing
) where CT <: Union{RGB, RGBA}
if isnothing(filename) || !OUTPUT
return img
else
save(filename, img)
println(filename)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 4257 | # TODO: make kernel, use max(0, filter_corner) for bounds and summing
# TODO: Probably shouldn't print anything anymore...
#TODO: figure out how to select the best deviation factor
function create_gaussian_kernel(kernel_size; deviation_factor = 1)
if !isodd(kernel_size)
println("Even kernel sizes are not allowed. New kernel size is: ",
kernel_size-1)
kernel_size -= 1
end
kernel = zeros(kernel_size, kernel_size)
center = floor(Int, kernel_size / 2) + 1
for i = 1:kernel_size
for j = 1:kernel_size
kernel[i,j] = exp(-((i-center)^2 + (j-center)^2)/
(kernel_size/deviation_factor))
end
end
return normalize(kernel)
end
function bounds_check(signal, index, filter_width, dir)
if index < 1
filter_width - (1-index)
elseif index > size(signal)[dir]
return filter_width - (index - size(signal)[dir])
else
return filter_width
end
end
# TODO: the normalization of the colors seems off, creating a spotty output
function filter_color(filter, signal)
if (size(signal) != size(filter))
error("filter and image views are not consistent!")
end
rsum = RGB(0)
for i = 1:length(signal)
rsum += filter[i]*signal[i].c
end
return rsum / sum(filter)
end
# TODO: this is computationally complex. Kinda sucks for that reason.
function find_filter_width(signal, threshold, index::CartesianIndex;
max_width = 15)
num_points = signal[index].val
filter_width = 1
while (num_points < threshold) && (filter_width < max_width)
filter_width += 2
num_points = layer_sum(signal, filter_width, index)
end
return filter_width
end
# TODO: too many layer sum functions
function layer_sum(signal::Array{Pixel,2}, filter_width::Int,
index::CartesianIndex)
center = filter_width + 1
j,i = index[1], index[2]
# This can create a signal view that is not the size of the filter
left_bound = bounds_check(signal, i-filter_width, filter_width, 2)
right_bound = bounds_check(signal, i+filter_width, filter_width, 2)
top_bound = bounds_check(signal, j+filter_width, filter_width, 1)
bottom_bound = bounds_check(signal, j-filter_width, filter_width, 1)
# TODO: zero-pad view or slize filter
#println(filter[1])
rsum = layer_sum(signal[j-bottom_bound:j+top_bound,
i-left_bound:i+right_bound])
return rsum
end
function layer_sum(signal::Array{Pixel,2}, filter::Array{Float64,2},
index::CartesianIndex)
filter_width = floor(Int, size(filter)[1]/2)
center = filter_width + 1
j,i = index[1], index[2]
# This can create a signal view that is not the size of the filter
left_bound = bounds_check(signal, i-filter_width, filter_width, 2)
right_bound = bounds_check(signal, i+filter_width, filter_width, 2)
top_bound = bounds_check(signal, j+filter_width, filter_width, 1)
bottom_bound = bounds_check(signal, j-filter_width, filter_width, 1)
# TODO: zero-pad view or slize filter
#println(filter[1])
rsum = Pixel(signal[i,j].val,
filter_color(filter[center-bottom_bound:center+top_bound,
center-left_bound:center+right_bound],
signal[j-bottom_bound:j+top_bound,
i-left_bound:i+right_bound]))
return rsum
end
#TODO: figure out what how to make a variable sized filter
# We need to read in the point data to figure out filter size
#TODO: I believe this is actually a correlation, not convolution ^^
function fractal_conv(signal::Array{Pixel,2}; threshold = 1)
n = size(signal)
out = Array{Pixel,2}(undef,n)
# time domain
for j = 1:n[1]
for i = 1:n[2]
filter_width = find_filter_width(signal, threshold,
CartesianIndex(j,i))
filter = create_gaussian_kernel(filter_width)
rsum = layer_sum(signal, filter, CartesianIndex(j,i))
out[j, i] = rsum
rsum = RGB(0)
end
end
return out
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1304 | export Clip
struct Clip <: AbstractPostProcess
op::Function
clip_op::Function
intensity_function::Function
threshold::Number
color::CT where CT <: Union{RGB, RGBA}
initialized::Bool
end
function Clip(op, clip_op, intensity_function, threshold, color)
return Clip(op, clip_op, intensity_function, threshold, color, true)
end
function Clip(; threshold = 0.5, color = RGBA(0,0,0,1),
intensity_function = simple_intensity, clip_op = >)
return Clip(clip!, clip_op, intensity_function, threshold, color, true)
end
function clip!(layer::AL, clip_params::Clip) where AL <: AbstractLayer
clip!(layer.canvas, layer, clip_params)
end
function clip!(output, layer::AL, clip_params::Clip) where AL <: AbstractLayer
backend = get_backend(layer.canvas)
kernel! = clip_kernel!(backend, layer.params.numthreads)
kernel!(output, layer.canvas, clip_params.clip_op,
clip_params.intensity_function,
clip_params.threshold, clip_params.color;
ndrange = size(layer.canvas))
return nothing
end
@kernel function clip_kernel!(output, canvas, clip_op, intensity_function, threshold, c)
tid = @index(Global, Linear)
if clip_op(intensity_function(canvas[tid]), threshold)
output[tid] = c
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 4168 | export Filter, Blur, Gaussian, Identity
mutable struct Filter <: AbstractPostProcess
op::Function
filter::AT where AT <: AbstractArray
canvas::AT where AT <: AbstractArray
initialized::Bool
end
function Filter(filter; ArrayType = Array)
return Filter(filter!, ArrayType(filter), nothing, false)
end
function initialize!(filter::Filter, layer::AL) where AL <: AbstractLayer
ArrayType = layer.params.ArrayType
if !(typeof(filter.filter) <: layer.params.ArrayType)
@info("filter array type not the same as canvas!\nConverting filter to canvas type...")
filter.filter = ArrayType(filter.filter)
end
filter.canvas = ArrayType(zeros(eltype(layer.canvas), size(layer.canvas)))
end
function Identity(; filter_size = 3, ArrayType = Array)
if iseven(filter_size)
filter_size = filter_size - 1
@warn("filter sizes must be odd! New filter size is " *
string(filter_size)*"!")
end
filter = zeros(filter_size, filter_size)
idx = ceil(Int, filter_size*0.5)
filter[idx, idx] = 1
return Filter(filter!, ArrayType(filter), nothing, false)
end
function gaussian(x,y, sigma)
return (1/(2*pi*sigma*sigma))*exp(-((x*x + y*y)/(2*sigma*sigma)))
end
function Blur(; filter_size = 3, ArrayType = Array, sigma = 1.0)
return Gaussian(; filter_size = filter_size, ArrayType = ArrayType,
sigma = sigma)
end
function Gaussian(; filter_size = 3, ArrayType = Array, sigma = 1.0)
if iseven(filter_size)
filter_size = filter_size - 1
@warn("filter sizes must be odd! New filter size is " *
string(filter_size)*"!")
end
if filter_size > 1
filter = zeros(filter_size, filter_size)
for i = 1:filter_size
y = -1 + 2*(i-1)/(filter_size-1)
for j = 1:filter_size
x = -1 + 2*(j-1)/(filter_size-1)
filter[i,j] = gaussian(x, y, sigma)
end
end
else
filter = [1.0]
end
filter ./= sum(filter)
return Filter(filter!, ArrayType(filter), nothing, false)
end
function filter!(layer::AL, filter_params::Filter) where AL <: AbstractLayer
filter!(layer.canvas, layer, filter_params)
end
function filter!(output, layer::AL,
filter_params::Filter) where AL <: AbstractLayer
backend = get_backend(layer.canvas)
kernel! = filter_kernel!(backend, layer.params.numthreads)
kernel!(filter_params.canvas, layer.canvas, filter_params.filter;
ndrange = size(layer.canvas))
output .= filter_params.canvas
return nothing
end
@kernel function filter_kernel!(canvas_out, canvas, filter)
tid = @index(Global, Cartesian)
(range, start_index_1, start_index_2) = find_overlap(tid,
size(canvas),
size(filter))
red = 0.0
green = 0.0
blue = 0.0
alpha = 0.0
for i = 1:range[1]
for j = 1:range[2]
@inbounds red += canvas[start_index_1[1] + i - 1,
start_index_1[2] + j - 1].r *
filter[start_index_2[1] + i - 1,
start_index_2[2] + j - 1]
@inbounds green += canvas[start_index_1[1] + i - 1,
start_index_1[2] + j - 1].g *
filter[start_index_2[1] + i - 1,
start_index_2[2] + j - 1]
@inbounds blue += canvas[start_index_1[1] + i - 1,
start_index_1[2] + j - 1].b *
filter[start_index_2[1] + i - 1,
start_index_2[2] + j - 1]
@inbounds alpha += canvas[start_index_1[1] + i - 1,
start_index_1[2] + j - 1].alpha *
filter[start_index_2[1] + i - 1,
start_index_2[2] + j - 1]
end
end
@inbounds canvas_out[tid] = RGBA{Float32}(red, green, blue, alpha)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 3031 | export Outline
mutable struct Outline <: AbstractPostProcess
op::Function
gauss_filter::FT where FT <: Union{Filter, Nothing}
sobel::Sobel
intensity_function::Function
threshold::Number
color::CT where CT <: Union{RGB, RGBA}
canvas::AT where AT <: AbstractArray
object_outline::Bool
initialized::Bool
end
function Outline(; linewidth = 1,
color = RGBA(1.0, 1.0, 1.0, 1.0),
intensity_function = simple_intensity,
object_outline = false,
threshold = 1/(linewidth*linewidth+1),
sigma = 1)
sobel = Sobel()
if linewidth > 1
filter_size = floor(Int, 3*linewidth)
if iseven(filter_size)
filter_size += 1
end
gauss_filter = Blur(; filter_size = filter_size, sigma = sigma)
else
gauss_filter = nothing
end
return Outline(outline!, gauss_filter, sobel, intensity_function,
threshold, color, nothing, object_outline, false)
end
function initialize!(o::Outline, layer::AL) where AL <: AbstractLayer
if !isnothing(o.gauss_filter)
initialize!(o.gauss_filter, layer)
end
initialize!(o.sobel, layer)
o.canvas = copy(layer.canvas)
if o.object_outline
# Note, needs improvement:
# if we just want to output the object outlines, we just create a layer
# where all values are RGBA(1,1,1,1) if there is any color at all
clip_params = Clip(threshold = 0.0, color = RGBA(1,1,1,1))
clip!(o.canvas, layer, clip_params)
end
o.initialized = true
end
function outline!(layer::AL, outline_params::Outline) where AL <: AbstractLayer
backend = get_backend(layer.canvas)
kernel! = ridge_kernel!(backend, layer.params.numthreads)
superimpose! = superimpose_kernel!(backend, layer.params.numthreads)
if !isnothing(outline_params.gauss_filter)
filter!(outline_params.canvas, layer, outline_params.gauss_filter)
end
sobel!(outline_params.canvas, layer, outline_params.sobel)
kernel!(outline_params.canvas, outline_params.intensity_function,
outline_params.threshold, outline_params.color;
ndrange = size(layer.canvas))
superimpose!(layer.canvas, outline_params.canvas;
ndrange = size(layer.canvas))
end
@kernel function ridge_kernel!(canvas, intensity_function, threshold, c)
tid = @index(Global, Linear)
if intensity_function(canvas[tid]) > threshold
canvas[tid] = RGBA(c.r, c.g, c.b, c.alpha)
else
canvas[tid] = RGBA(0,0,0,0)
end
end
@kernel function superimpose_kernel!(canvas, layer)
tid = @index(Global, Linear)
r = layer[tid].alpha*layer[tid].r + (1-layer[tid].alpha)*canvas[tid].r
g = layer[tid].alpha*layer[tid].g + (1-layer[tid].alpha)*canvas[tid].g
b = layer[tid].alpha*layer[tid].b + (1-layer[tid].alpha)*canvas[tid].b
alpha = max(layer[tid].alpha, canvas[tid].alpha)
canvas[tid] = RGBA(r, g, b, alpha)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1638 | export postprocess!, intensity, perceptive_intensity, simple_intensity
function postprocess!(layer::AL) where AL <: AbstractLayer
for i = 1:length(layer.postprocessing_steps)
if !layer.postprocessing_steps[i].initialized
@info("initializing " *
string(typeof(layer.postprocessing_steps[i])) * "!")
initialize!(layer.postprocessing_steps[i], layer)
end
layer.postprocessing_steps[i].op(layer, layer.postprocessing_steps[i])
end
end
@inline function clip(c::CT, val::Number) where CT <: RGB
return CT(min(c.r, val), min(c.g, val), min(c.b, val))
end
@inline function clip(c::CT, val::Number) where CT <: RGBA
return CT(min(c.r, val), min(c.g, val), min(c.b, val), min(c.alpha, val))
end
@inline function clip(c::Number, val::Number)
return min(c, val)
end
@inline function intensity(c::CT;
i_func = simple_intensity
) where CT <: Union{RGB, RGBA}
return i_func(c)
end
@inline function perceptive_intensity(c::Number)
return c
end
@inline function perceptive_intensity(c::CT) where CT <: Union{RGB}
return (0.21 * c.r) + (0.72 * c.g) + (0.07 * c.b)
end
@inline function perceptive_intensity(c::CT) where CT <: Union{RGBA}
return c.alpha * ((0.21 * c.r) + (0.72 * c.g) + (0.07 * c.b))
end
@inline function simple_intensity(c::Number)
return c
end
@inline function simple_intensity(c::CT) where CT <: Union{RGB}
return (c.r/3) + (c.g/3) + (c.b/3)
end
@inline function simple_intensity(c::CT) where CT <: Union{RGBA}
return c.alpha * ((c.r/3) + (c.g/3) + (c.b/3))
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2267 | export Sobel
mutable struct Sobel <: AbstractPostProcess
op::Function
filter_x::AT where AT <: AbstractArray
filter_y::AT where AT <: AbstractArray
canvas_x::AT where AT <: AbstractArray
canvas_y::AT where AT <: AbstractArray
initialized::Bool
end
Sobel() = Sobel(sobel!, nothing, nothing, nothing, nothing, false)
function initialize!(s::Sobel, layer::AL) where AL <: AbstractLayer
ArrayType = layer.params.ArrayType
canvas_size = size(layer.canvas)
s.filter_x = ArrayType([1.0 0.0 -1.0;
2.0 0.0 -2.0;
1.0 0.0 -1.0])
s.filter_y = ArrayType([ 1.0 2.0 1.0;
0.0 0.0 0.0;
-1.0 -2.0 -1.0])
s.canvas_x = copy(layer.canvas)
s.canvas_y = copy(layer.canvas)
s.initialized = true
end
@kernel function quad_add!(output, canvas_y, canvas_x)
tid = @index(Global, Linear)
r = sqrt(canvas_y[tid].r*canvas_y[tid].r + canvas_x[tid].r*canvas_x[tid].r)
g = sqrt(canvas_y[tid].g*canvas_y[tid].g + canvas_x[tid].g*canvas_x[tid].g)
b = sqrt(canvas_y[tid].b*canvas_y[tid].b + canvas_x[tid].b*canvas_x[tid].b)
if eltype(output) <: RGBA
alpha = sqrt(canvas_y[tid].alpha*canvas_y[tid].alpha +
canvas_x[tid].alpha*canvas_x[tid].alpha)
output[tid] = clip(RGBA(r, g, b, alpha), 1)
else
output[tid] = clip(RGB(r, g, b), 1)
end
end
function sobel!(layer::AL, sobel_params::Sobel) where AL <: AbstractLayer
sobel!(layer.canvas, layer, sobel_params)
end
function sobel!(output, layer::AL,
sobel_params::Sobel) where AL <: AbstractLayer
backend = get_backend(layer.canvas)
kernel! = filter_kernel!(backend, layer.params.numthreads)
add_kernel! = quad_add!(backend, layer.params.numthreads)
@sync begin
@async kernel!(sobel_params.canvas_x, output,
sobel_params.filter_x, ndrange = size(layer.canvas))
@async kernel!(sobel_params.canvas_y, output,
sobel_params.filter_y, ndrange = size(layer.canvas))
end
add_kernel!(output, sobel_params.canvas_y,
sobel_params.canvas_x; ndrange = size(layer.canvas))
return nothing
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1086 | export define_barnsley
function define_barnsley(; color = Shaders.grey, tilt = 0)
fums = define_barnsley_operators(tilt = tilt)
color_set = define_color_operators(color; fnum = 4)
prob_set = (0.01, 0.85, 0.07, 0.07)
fos = Tuple(FractalOperator(fums[i], color_set[i], prob_set[i]) for i = 1:4)
return Hutchinson((fos,))
end
# This specifically returns the fums for a barnsley fern
function define_barnsley_operators(; tilt::Union{Number, FractalInput} = 0)
s_1 = @fum function s_1()
return point(0.16*y, 0.0)
end
s_2 = @fum function s_2(;tilt = 0)
x_temp = x
x = 0.85*x_temp + (0.04+tilt)*y
y = -0.04*x_temp + 0.85*y + 1.6
return point(y,x)
end
s_3 = @fum function s_3()
x_temp = x
x = 0.2*x_temp - 0.26*y
y = 0.23*x_temp + 0.22*y + 1.6
return point(y,x)
end
s_4 = @fum function s_4()
x_temp = x
x = -0.15*x_temp + 0.28*y
y = 0.26*x_temp + 0.24*y + 0.44
return point(y,x)
end
return [s_1, s_2(tilt = tilt), s_3, s_4]
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2661 | export define_circle
# Code examples modified from: https://www.math.uwaterloo.ca/~wgilbert/FractalGallery/IFS/IFS.html
naive_disk = @fum function naive_disk(x, y; radius = 1, position = (0,0),
function_index = 0)
x_temp = (x-position[2])/radius
y_temp = (y-position[1])/radius
r = sqrt(x_temp*x_temp + y_temp*y_temp)
theta = pi
if !isapprox(r, 0)
theta = atan(y_temp,x_temp)
if y_temp < 0
theta += 2*pi
end
end
theta2 = (r+function_index)*pi
r2 = theta/(2*pi)
x = radius*r2*cos(theta2)+position[2]
y = radius*r2*sin(theta2)+position[1]
return point(y,x)
end
constant_disk = @fum function constant_disk(x, y; radius = 1,
position = (0,0),
function_index = 0)
x_temp = (x-position[2])/radius
y_temp = (y-position[1])/radius
r = x_temp*x_temp + y_temp*y_temp
theta = pi
if !isapprox(r, 0)
theta = atan(y_temp,x_temp)
if y_temp < 0
theta += 2*pi
end
end
theta2 = (r+function_index)*pi
r2 = sqrt(theta/(2*pi))
x = radius*r2*cos(theta2)+position[2]
y = radius*r2*sin(theta2)+position[1]
return point(y,x)
end
# Returns back H, colors, and probs for a circle
function define_circle(; position::Union{Tuple, Vector, FractalInput} = (0, 0),
radius::Union{Number, FractalInput} = 1.0,
color = Shaders.gray,
chosen_fx = :constant_disk)
fums = define_circle_operators(position, radius; chosen_fx = chosen_fx)
color_set = define_color_operators(color; fnum = 2)
fos = Tuple((FractalOperator(fums[i], color_set[i], 0.5) for i = 1:2))
return Hutchinson((fos,))
end
# This specifically returns the fums for a circle
function define_circle_operators(position::Union{Vector, Tuple, FractalInput},
radius::Union{Number, FractalInput};
chosen_fx = :constant_disk)
f_0 = fi("f_0", 0)
f_1 = fi("f_1", 1)
if chosen_fx == :naive_disk
d_0 = naive_disk(function_index = f_0, position = position, radius = radius)
d_1 = naive_disk(function_index = f_1, position = position, radius = radius)
elseif chosen_fx == :constant_disk
d_0 = constant_disk(function_index = f_0, position = position, radius = radius)
d_1 = constant_disk(function_index = f_1, position = position, radius = radius)
else
error("function not found for circle IFS!")
end
return [d_0, d_1]
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 3518 | export define_rectangle, define_square
# Returns back H, colors, and probs for a square
rectangle_object = @fum function rectangle_onject(y,x;
vertex = 1,
rotation = 0,
position = (0,0),
scale_x = 1,
scale_y = 1)
scale_x *= 0.5
scale_y *= 0.5
if vertex == 1
p_x = scale_x*cos(rotation) - scale_y*sin(rotation) + position[2]
p_y = scale_x*sin(rotation) + scale_y*cos(rotation) + position[1]
elseif vertex == 2
p_x = scale_x*cos(rotation) + scale_y*sin(rotation) + position[2]
p_y = scale_x*sin(rotation) - scale_y*cos(rotation) + position[1]
elseif vertex == 3
p_x = - scale_x*cos(rotation) + scale_y*sin(rotation) + position[2]
p_y = - scale_x*sin(rotation) - scale_y*cos(rotation) + position[1]
elseif vertex == 4
p_x = - scale_x*cos(rotation) - scale_y*sin(rotation) + position[2]
p_y = - scale_x*sin(rotation) + scale_y*cos(rotation) + position[1]
else
p_x = 0.0
p_y = 0.0
end
return point(0.5*(p_y + y), 0.5*(p_x + x))
end
function define_rectangle(; position::Union{Vector, Tuple, FractalInput}=(0,0),
rotation::Union{Number, FractalInput} = 0.0,
scale_x::Union{Number, FractalInput} = 1.0,
scale_y::Union{Number, FractalInput} = 1.0,
color = Shaders.grey)
fums = define_rectangle_operators(position, rotation, scale_x, scale_y)
color_set = define_color_operators(color; fnum = 4)
fos = Tuple(FractalOperator(fums[i], color_set[i], 0.25) for i = 1:4)
return Hutchinson((fos,))
end
# Returns back H, colors, and probs for a square
function define_square(; position::Union{Vector, Tuple, FractalInput}=(0,0),
rotation::Union{Number, FractalInput} = 0.0,
scale::Union{Number, FractalInput} = 1.0,
color = Shaders.grey)
return define_rectangle(; position = position, rotation = rotation,
scale_x = scale, scale_y = scale, color = color)
end
# This specifically returns the fums for a square
function define_rectangle_operators(position::Union{Vector,Tuple,FractalInput},
rotation::Union{Number, FractalInput},
scale_x::Union{Number, FractalInput},
scale_y::Union{Number, FractalInput})
square_1 = rectangle_object(position = position, rotation = rotation,
scale_x = scale_x, scale_y = scale_y,
vertex = 1)
square_2 = rectangle_object(position = position, rotation = rotation,
scale_x = scale_x, scale_y = scale_y,
vertex = 2)
square_3 = rectangle_object(position = position, rotation = rotation,
scale_x = scale_x, scale_y = scale_y,
vertex = 3)
square_4 = rectangle_object(position = position, rotation = rotation,
scale_x = scale_x, scale_y = scale_y,
vertex = 4)
return (square_1, square_2, square_3, square_4)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1857 | export define_triangle
triangle_fill = @fum function triangle_fill(x,y;
A = (0,0),
B = (0,0),
C = (0,0))
midpoint_y = (A[1] + B[1] + C[1]) ./ 3
midpoint_x = (A[2] + B[2] + C[2]) ./ 3
y = midpoint_y - (y - midpoint_y) * 0.5
x = midpoint_x - (x - midpoint_x) * 0.5
return point(y,x)
end
function define_triangle(; A::Union{Vector,Tuple,FractalInput}=(sqrt(3)/4,-0.5),
B::Union{Vector,Tuple,FractalInput}=(-sqrt(3)/4,0),
C::Union{Vector,Tuple,FractalInput}=(sqrt(3)/4,0.5),
color = Shaders.gray,
chosen_fx = :fill)
fums = define_triangle_operators(A, B, C; chosen_fx = chosen_fx)
fnum = 3
if chosen_fx == :fill
fnum = 4
end
color_set = define_color_operators(color; fnum = fnum)
fos = Tuple(FractalOperator(fums[i], color_set[i], 1/fnum) for i = 1:fnum)
return Hutchinson((fos,))
end
# This specifically returns the fums for a triangle triangle
function define_triangle_operators(A::Union{Vector, Tuple, FractalInput},
B::Union{Vector, Tuple, FractalInput},
C::Union{Vector, Tuple, FractalInput};
chosen_fx = :fill)
if chosen_fx != :sierpinski && chosen_fx != :fill
error("Cannot create triangle with ", string(chosen_fx), " function!")
end
s_1 = Flames.halfway(loc = A)
s_2 = Flames.halfway(loc = B)
s_3 = Flames.halfway(loc = C)
if chosen_fx == :fill
s_4 = triangle_fill(A = A, B = B, C = C)
return [s_1, s_2, s_3, s_4]
elseif chosen_fx == :sierpinski
return [s_1, s_2, s_3]
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 355 | export run!
function run!(layer::ColorLayer; frame = 0)
backend = get_backend(layer.canvas)
kernel! = color_kernel!(backend, layer.params.numthreads)
kernel!(layer.color, layer.canvas, ndrange = size(layer.canvas))
end
@kernel function color_kernel!(color, canvas)
tid = @index(Global, Linear)
@inbounds canvas[tid] = color
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 13511 | #-------------fractal_flame.jl-------------------------------------------------#
# Before reading this file and judging me, please take a look at the errors on
# PR #64 (https://github.com/leios/Fable.jl/pull/64)
#
# Long story short, I cannot access any Tuples of varying types with iteration:
# i = 5
# fxs[i](args...;kwargs...)
# This means that anything that cannot be represented as an NTuple{Type,...},
# will break. Functions have an inherent type, so they cannot be represented as
# an NTuple and must instead be represented as a Tuple{f1, f2, f3...}.
#
# To call the functions, I need to call them with a statically known number.
# So instead of using `idx = 1`, `fxs[idx](...)`, I needed to create an
# `@generated` function that unrolls the loop for me. In the case of colors,
# where multiple colors could be used on for the same IFS function, I needed
# an additional helper function to call the Tuple one by one.
#
# It will unfortunately only get more complicated from here until Julia is fixed
#------------------------------------------------------------------------------#
export run!
@generated function call_pt_fx(fxs, pt, frame, kwargs, idx)
exs = Expr[]
ex = quote
if idx == 1
pt = fxs[1](pt.y, pt.x, frame; kwargs[1]...)
end
end
push!(exs, ex)
for i = 2:length(fxs.parameters)
ex = quote
if idx == $i
pt = fxs[$i](pt.y, pt.x, frame; kwargs[$i]...)
end
end
push!(exs, ex)
end
push!(exs, :(return pt))
return Expr(:block, exs...)
end
# These functions essentially unroll the loops in the kernel because of a
# known julia bug preventing us from using for i = 1:10...
@generated function pt_loop(fxs, fid, pt, frame, fnums, kwargs)
exs = Expr[]
push!(exs, :(bit_offset = 0))
push!(exs, :(fx_offset = 0))
for i = 1:length(fnums.parameters)
ex = quote
idx = decode_fid(fid, bit_offset, fnums[$i]) + fx_offset
pt = call_pt_fx(fxs, pt, frame, kwargs, idx)
bit_offset += ceil(UInt,log2(fnums[$i]))
fx_offset += fnums[$i]
end
push!(exs, ex)
end
push!(exs, :(return pt))
# to return 3 separate colors to mix separately
# return :(Expr(:tuple, $exs...))
return Expr(:block, exs...)
end
@generated function call_clr_fx(fxs, pt, clr, frame, kwargs, idx)
exs = Expr[]
ex = quote
if idx == 1
clr = call_clr_fx(fxs[1], pt, clr, frame, kwargs[1])
end
end
push!(exs, ex)
for i = 2:length(fxs.parameters)
ex = quote
if idx == $i
clr = call_clr_fx(fxs[$i], pt, clr, frame, kwargs[$i])
end
end
push!(exs, ex)
end
push!(exs, :(return clr))
return Expr(:block, exs...)
end
@inline function call_clr_fx(fx, pt, clr, frame, kwargs)
return fx(pt.y, pt.x, clr, frame; kwargs...)
end
@generated function call_clr_fx(fx::Tuple, pt::Point2D, clr, frame, kwargs::Tuple)
exs = Expr[]
for i = 1:length(fx.parameters)
ex = :(clr = fx[$i](pt.y, pt.x, clr, frame; kwargs[$i]...))
push!(exs, ex)
end
push!(exs, :(return clr))
return Expr(:block, exs...)
end
@generated function clr_loop(fxs, fid, pt, clr, frame, fnums, kwargs)
exs = Expr[]
push!(exs, :(bit_offset = 0))
push!(exs, :(fx_offset = 0))
for i = 1:length(fnums.parameters)
ex = quote
idx = decode_fid(fid, bit_offset, fnums[$i]) + fx_offset
clr = call_clr_fx(fxs, pt, clr, frame, kwargs, idx)
bit_offset += ceil(UInt,log2(fnums[$i]))
fx_offset += fnums[$i]
end
push!(exs, ex)
end
push!(exs, :(return clr))
# to return 3 separate colors to mix separately
# return :(Expr(:tuple, $exs...))
return Expr(:block, exs...)
end
@generated function semi_random_loop!(layer_values, layer_reds, layer_greens,
layer_blues, layer_alphas, fxs, clr_fxs,
pt, clr, frame, fnums, kwargs, clr_kwargs,
bounds, dims, bin_widths,
iteration, num_ignore)
exs = Expr[]
for i = 1:length(fxs.parameters)
ex = quote
pt = fxs[$i](pt.y, pt.x, frame; kwargs[$i]...)
clr = clr_fxs[$i](pt.y, pt.x, clr, frame; clr_kwargs[$i]...)
histogram_output!(layer_values, layer_reds, layer_greens,
layer_blues, layer_alphas, pt, clr,
bounds, dims, bin_widths,
iteration, num_ignore)
end
push!(exs, ex)
end
# to return 3 separate colors to mix separately
# return :(Expr(:tuple, $exs...))
return Expr(:block, exs...)
end
@inline function histogram_output!(layer_values, layer_reds, layer_greens,
layer_blues, layer_alphas, pt, clr,
bounds, dims, bin_widths, i, num_ignore)
on_img_flag = on_image(pt.y,pt.x, bounds, dims)
if i > num_ignore && on_img_flag
@inbounds bin = find_bin(layer_values, pt.y, pt.x, bounds, bin_widths)
if bin > 0 && bin <= length(layer_values)
@inbounds @atomic layer_values[bin] += 1
@inbounds @atomic layer_reds[bin] += clr.r
@inbounds @atomic layer_greens[bin] += clr.g
@inbounds @atomic layer_blues[bin] += clr.b
@inbounds @atomic layer_alphas[bin] += clr.alpha
end
end
end
# couldn't figure out how to get an n-dim version working for GPU
@inline function on_image(p_y, p_x, bounds, dims)
flag = true
if p_y <= bounds.ymin || p_y > bounds.ymax ||
p_y == NaN || p_y == Inf
flag = false
end
if p_x <= bounds.xmin || p_x > bounds.xmax ||
p_x == NaN || p_x == Inf
flag = false
end
return flag
end
function iterate!(layer::FractalLayer, H1::Hutchinson, n,
bounds, bin_widths, H2::Union{Nothing, Hutchinson};
frame = 0)
if isnothing(H2)
fx = naive_chaos_kernel!
elseif layer.params.solver_type == :semi_random
fx = semi_random_chaos_kernel!
elseif layer.params.solver_type == :random
fx = naive_chaos_kernel!
else
@warn(string(layer.params.solver_type)*" is not a valid solver type!\n"*
"Defaulting to random...")
fx = naive_chaos_kernel!
end
max_range = maximum(values(bounds))*10
backend = get_backend(layer.canvas)
kernel! = fx(backend, layer.params.numthreads)
if isnothing(H2)
kernel!(layer.particles, n, H1.fxs, combine(H1.kwargs, H1.fis),
H1.color_fxs, combine(H1.color_kwargs, H1.color_fis),
H1.prob_set, H1.fnums, layer.values,
layer.reds, layer.greens, layer.blues, layer.alphas,
frame, bounds, Tuple(bin_widths),
layer.params.num_ignore, max_range,
ndrange=size(layer.particles)[1])
else
kernel!(layer.particles, n, H1.fxs, combine(H1.kwargs, H1.fis),
H1.color_fxs, combine(H1.color_kwargs, H1.color_fis),
H1.prob_set, H1.fnums,
H2.fxs, combine(H2.kwargs, H2.fis),
H2.color_fxs, combine(H2.color_kwargs, H2.color_fis),
H2.prob_set, H2.fnums, layer.values,
layer.reds, layer.greens, layer.blues, layer.alphas,
frame, bounds, Tuple(bin_widths),
layer.params.num_ignore, max_range,
ndrange=size(layer.particles)[1])
end
end
@kernel function naive_chaos_kernel!(points, n, H_fxs, H_kwargs,
H_clrs, H_clr_kwargs,
H_probs, H_fnums,
layer_values, layer_reds, layer_greens,
layer_blues, layer_alphas, frame, bounds,
bin_widths, num_ignore, max_range)
tid = @index(Global,Linear)
pt = points[tid]
dims = Fable.dims(pt)
clr = RGBA{Float32}(0,0,0,0)
seed = quick_seed(tid)
fid = create_fid(H_probs, H_fnums, seed)
for i = 1:n
# quick way to tell if in range to be calculated or not
sketchy_sum = absum(pt)
if sketchy_sum < max_range
if length(H_fnums) > 1 || H_fnums[1] > 1
seed = simple_rand(seed)
fid = create_fid(H_probs, H_fnums, seed)
else
fid = UInt(1)
end
pt = pt_loop(H_fxs, fid, pt, frame, H_fnums, H_kwargs)
clr = clr_loop(H_clrs, fid, pt, clr, frame, H_fnums, H_clr_kwargs)
histogram_output!(layer_values, layer_reds, layer_greens,
layer_blues, layer_alphas, pt, clr,
bounds, dims, bin_widths, i, num_ignore)
end
end
@inbounds points[tid] = pt
end
@kernel function semi_random_chaos_kernel!(points, n, H1_fxs, H1_kwargs,
H1_clrs, H1_clr_kwargs,
H1_probs, H1_fnums,
H2_fxs, H2_kwargs,
H2_clrs, H2_clr_kwargs,
H2_probs, H2_fnums,
layer_values, layer_reds,
layer_greens, layer_blues,
layer_alphas, frame, bounds,
bin_widths, num_ignore, max_range)
tid = @index(Global,Linear)
pt = points[tid]
clr = RGBA{Float32}(0,0,0,0)
dims = Fable.dims(pt)
seed = quick_seed(tid)
fid = create_fid(H1_probs, H1_fnums, seed)
for i = 1:n
# quick way to tell if in range to be calculated or not
sketchy_sum = absum(pt)
if sketchy_sum < max_range
if length(H1_fnums) > 1 || H1_fnums[1] > 1
seed = simple_rand(seed)
fid = create_fid(H1_probs, H1_fnums, seed)
else
fid = UInt(1)
end
pt = pt_loop(H1_fxs, fid, pt, frame, H1_fnums, H1_kwargs)
clr = clr_loop(H1_clrs, fid, pt, clr,
frame, H1_fnums, H1_clr_kwargs)
semi_random_loop!(layer_values, layer_reds, layer_greens,
layer_blues, layer_alphas, H2_fxs, H2_clrs,
pt, clr, frame, H2_fnums, H2_kwargs,
H2_clr_kwargs, bounds, dims, bin_widths, i,
num_ignore )
end
end
@inbounds points[tid] = pt
end
@kernel function naive_chaos_kernel!(points, n, H1_fxs, H1_kwargs,
H1_clrs, H1_clr_kwargs,
H1_probs, H1_fnums,
H2_fxs, H2_kwargs,
H2_clrs, H2_clr_kwargs,
H2_probs, H2_fnums,
layer_values, layer_reds, layer_greens,
layer_blues, layer_alphas, frame, bounds,
bin_widths, num_ignore, max_range)
tid = @index(Global,Linear)
pt = points[tid]
output_pt = points[tid]
dims = Fable.dims(pt)
clr = RGBA{Float32}(0,0,0,0)
output_clr = RGBA{Float32}(0,0,0,0)
seed = quick_seed(tid)
fid = create_fid(H1_probs, H1_fnums, seed)
fid_2 = create_fid(H2_probs, H2_fnums, seed)
for i = 1:n
# quick way to tell if in range to be calculated or not
sketchy_sum = absum(pt)
if sketchy_sum < max_range
if length(H1_fnums) > 1 || H1_fnums[1] > 1
seed = simple_rand(seed)
fid = create_fid(H1_probs, H1_fnums, seed)
else
fid = UInt(1)
end
if length(H2_fnums) > 1 || H2_fnums[1] > 1
seed = simple_rand(seed)
fid_2 = create_fid(H2_probs, H2_fnums, seed)
else
fid_2 = UInt(1)
end
pt = pt_loop(H1_fxs, fid, pt, frame, H1_fnums, H1_kwargs)
clr = clr_loop(H1_clrs, fid, pt, clr,
frame, H1_fnums, H1_clr_kwargs)
output_pt = pt_loop(H2_fxs, fid, pt, frame, H2_fnums, H2_kwargs)
output_clr = clr_loop(H2_clrs, fid_2, pt, clr,
frame, H2_fnums, H2_clr_kwargs)
histogram_output!(layer_values, layer_reds, layer_greens,
layer_blues, layer_alphas, output_pt, output_clr,
bounds, dims, bin_widths, i, num_ignore)
end
end
@inbounds points[tid] = pt
end
function run!(layer::FractalLayer; frame = 0)
res = size(layer.canvas)
bounds = find_bounds(layer)
bin_widths = zeros(div(length(values(bounds)),2))
for i = 1:length(bin_widths)
bin_widths[i] = (bounds[i*2]-bounds[i*2-1])/res[i]
end
bounds = find_bounds(layer)
iterate!(layer, layer.H1, layer.params.num_iterations,
bounds, bin_widths, layer.H2; frame = frame)
return layer
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 523 | export run!
function run!(layer::AbstractLayer, time::TimeInterface)
run!(layer; frame = frame(time))
end
function run!(layers::Vector{AbstractLayer}, time::TimeInterface)
run!(layers; frame = frame(time))
end
function run!(layers::Vector{AbstractLayer}; frame = 0)
for i = 1:length(layers)
run!(layers[i]; frame = frame)
end
end
# dummy function that should be defined for each layer
function run!(layer::AbstractLayer; frame = 0)
@error("run!("*string(typeof(layer))*") not defined!")
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1149 | export run!
@generated function shader_loop(fxs, y, x, color, frame, kwargs)
exs = Expr[]
for i = 1:length(fxs.parameters)
ex = :(color = fxs[$i](y, x, color, frame; kwargs[$i]...))
push!(exs, ex)
end
# to return 3 separate colors to mix separately
# return :(Expr(:tuple, $exs...))
return Expr(:block, exs...)
end
function run!(layer::ShaderLayer; frame = 0)
backend = get_backend(layer.canvas)
kernel! = shader_kernel!(backend, layer.params.numthreads)
bounds = find_bounds(layer)
kernel!(layer.canvas, bounds,
layer.shader.fxs,
combine(layer.shader.kwargs, layer.shader.fis),
frame,
ndrange = size(layer.canvas))
end
@kernel function shader_kernel!(canvas, bounds, fxs, kwargs, frame)
i, j = @index(Global, NTuple)
res = @ndrange()
@inbounds y = bounds.ymin + (i/res[1])*(bounds.ymax - bounds.ymin)
@inbounds x = bounds.xmin + (j/res[2])*(bounds.xmax - bounds.xmin)
color = RGBA{Float32}(0,0,0,0)
color = shader_loop(fxs, y, x, color, frame, kwargs)
@inbounds canvas[i,j] = RGBA{Float32}(color)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1390 | export FractalInput, fi, @fi, set!, combine, to_args, find_fi_index, value
struct FractalInput
s::Union{Symbol, String}
x::Ref{Union{Number, Tuple, Vector}}
end
fi(args...) = FractalInput(args...)
function set!(fi::FractalInput, val)
fi.x.x = val
end
function combine(nt::Tuple, fis::Tuple)
return Tuple(combine(nt[i], fis[i]) for i = 1:length(fis))
end
combine(fis::Vector{FractalInput}, nt::NamedTuple) = combine(nt, fis)
function combine(nt::NamedTuple, fis::Vector{FractalInput})
if length(fis) == 0
return nt
end
fi_vals = (remove_vectors(fis[i].x.x) for i = 1:length(fis))
fi_keys = (Symbol(fis[i].s) for i = 1:length(fis))
return NamedTuple{(keys(nt)..., fi_keys...)}((values(nt)..., fi_vals...))
end
function to_args(nt::Tuple, fis::Tuple)
return Tuple(combine(fis[i], nt[i]) for i = 1:length(fis))
end
function to_args(nt::NamedTuple, fis::Vector{FractalInput})
if length(fis) == 0
return values(nt)
end
fi_vals = (remove_vectors(fis[i].x.x) for i = 1:length(fis))
return (values(nt)..., fi_vals...)
end
function find_fi_index(s, fis::FT) where FT <: Union{Vector{FractalInput},
Tuple}
for i = 1:length(fis)
if Symbol(fis[i].s) == Symbol(s)
return i
end
end
end
value(fi::FractalInput) = fi.x.x
value(a) = a
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 592 | export FractalOperator, fo
struct FractalOperator
op::FractalUserMethod
color::Union{FractalUserMethod, Tuple}
prob::Number
end
Base.length(fo::FractalOperator) = 1
fo(args...; kwargs...) = FractalOperator(args...; kwargs...)
function FractalOperator(f::FractalUserMethod, c::FractalUserMethod)
return FractalOperator(f, c, 1.0)
end
FractalOperator(f::FractalUserMethod) = FractalOperator(f,
Shaders.previous,
1.0)
FractalUserMethod(f::FractalOperator) = f.op
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 4550 | export FractalUserMethod, @fum
struct FractalUserMethod{NT <: NamedTuple,
V <: Vector{FractalInput},
F <: Function}
kwargs::NT
fis::V
fx::F
end
args(a,n) = a.args[n]
function __set_args(args, config)
if config == :fractal
correct_args = [:y, :x, :frame]
elseif config == :shader
correct_args = [:y, :x, :color, :frame]
end
if !issubset(args, correct_args)
error("Function arguments must be one of the following:\n"*
string(correct_args)*"\n"*
"Please use key-word arguments for any additional arguments!")
end
return correct_args
end
# this function can create a NamedTuple from kwargs in a macro, ie:
# kwargs = __to_NamedTuple(def[:kwargs])
# It is not currently used, but took a while to find out, so I'm leaving it
# here for debugging purposes
#function __to_NamedTuple(kwargs)
# NamedTuple{Tuple(args.(kwargs[:],1))}(Tuple(args.(kwargs[:],2)))
#end
function __define_fum_stuff(expr, config, mod)
def = MacroTools.splitdef(expr)
def[:name] = name = Symbol(def[:name], :_fum)
used_args = def[:args]
args = __set_args(used_args, config)
def[:args] = args
kwargs = NamedTuple()
fum_fx = combinedef(def)
return kwargs, Core.eval(mod, fum_fx)
end
# Note: this operator currently works like this:
# f = @fum function config f(x) x+1 end
# There should be a way to define f in this macro, so we don't need to
# say `f = @fum function ...`, but instead just `@fum function ...`
macro fum(ex...)
config = :fractal
if length(ex) == 1
elseif length(ex) == 2
if ex[1] == :color || ex[1] == :shader ||
ex[1] == :(:shader) || ex[1] == :(:color)
config = :shader
end
else
error("Improperly formatted function definition!\n"*
"Too many arguments provided!")
end
expr = ex[end]
kwargs = nothing
if isa(expr, Symbol)
error("Cannot convert Symbol to Fractal User Method!")
elseif expr.head == :(=)
# inline function definitions
if isa(expr.args[1], Expr)
kwargs, fum_fx = __define_fum_stuff(expr, config, __module__)
else
error("Cannot create FractalUserMethod.\n"*
"Input is not a valid function definition!")
end
elseif expr.head == :function
kwargs, fum_fx = __define_fum_stuff(expr, config, __module__)
else
error("Cannot convert expr to Fractal User Method!")
end
return FractalUserMethod(kwargs, FractalInput[], fum_fx)
end
function (a::FractalUserMethod)(args...; kwargs...)
# we do not reason about standard args right now, although this could
# be considered in the future if we ensure users always configure their
# fums beforehand. We could then save the args and such in each fum and
# assign them to a value that is passed in to the compute kernels.
if length(args) > 0
@warn("function arguments cannot be set at"*
" this time and will be ignored!\n"*
"Please use appropriate key-word arguments instead!")
end
# checking to make sure the symbols are assignable in the first place
error_flag = false
# Note: grabs all keywords from the a.fx. If multiple definitions exist,
# it takes the first one. It might mistakenly grab the wrong function.
# If this happens, we need to reason about how to pick the right function
# when two exist with the same name, but different kwargs...
known_kwargs = Base.kwarg_decl.(methods(a.fx))[1]
final_kwarg_idxs = Int[]
final_fi_idxs = Int[]
ks = keys(kwargs)
vals = values(NamedTuple(kwargs))
for i = 1:length(ks)
if !in(ks[i], known_kwargs)
@warn(string(key)*" not found in set of fum key-word args!")
error_flag = true
end
if isa(vals[i], FractalInput)
push!(final_fi_idxs, i)
else
push!(final_kwarg_idxs, i)
end
end
if error_flag
error("one or more keys not found in set of fum key-word args!\n"*
"Maybe consider creating a new fum function with the right "*
"key-word arguments?")
end
fis = [FractalInput(ks[i], vals[i].x) for i in final_fi_idxs]
ks = Tuple(ks[final_kwarg_idxs])
vals = Tuple(remove_vectors.(vals[final_kwarg_idxs]))
final_kwargs = NamedTuple{ks}(vals)
return FractalUserMethod(final_kwargs, fis, a.fx)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1360 | export point, generate_points, generate_points, absum, dims
# Might need the following interface for GPU compatability:
# Can otherwise use NamedTuples:
# point(x) = (x=x,)
# point(x, y) = (x=x, y=y)
# point(x, y, z) = (x=x, y=y, z=z)
# point(x, y, z, w) = (x=x, y=y, z=z, w=w)
abstract type AbstractPoint end
struct Point1D{N} <: AbstractPoint
y::N
end
struct Point2D{N} <: AbstractPoint
y::N
x::N
end
struct Point3D{N} <: AbstractPoint
y::N
x::N
z::N
end
struct Point4D{N} <: AbstractPoint
y::N
x::N
z::N
w::N
end
point(x) = Point1D(x)
point(x, y) = Point2D(x, y)
point(x, y, z) = Point3D(x, y, z)
point(x, y, z, w) = Point4D(x, y, z, w)
absum(pt::Point1D) = abs(pt.y)
absum(pt::Point2D) = abs(pt.y) + abs(pt.x)
absum(pt::Point3D) = abs(pt.y) + abs(pt.x) + abs(pt.z)
absum(pt::Point4D) = abs(pt.y) + abs(pt.x) + abs(pt.z) + abs(pt.w)
dims(pt::Point1D) = 1
dims(pt::Point2D) = 2
dims(pt::Point3D) = 3
dims(pt::Point4D) = 4
function generate_point(; dims=2, bounds = find_bounds((0,0), (2,2)))
return point([rand() * (bounds[i*2] - bounds[i*2-1]) +
bounds[i*2-1] for i=1:dims]...)
end
function generate_points(N::Int; ArrayType=Array, dims=2,
bounds=find_bounds((0,0), (2,2)))
return ArrayType([generate_point(dims = dims, bounds = bounds) for i = 1:N])
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 691 | export frame, current_time, set_fps!
global FPS = 30.0
TimeInterface = Union{Int, AbstractFloat, Quantity}
function frame(f::Int)
return f
end
function frame(t::AbstractFloat)
return floor(Int, t*FPS)
end
function frame(q::Quantity)
if !isa(q, Unitful.Time)
error(string(q) * " does not have units of time!")
end
return floor(Int, (uconvert(u"s", q)*FPS).val)
end
function current_time(f::Int)
return f/FPS
end
function current_time(t::AbstractFloat)
return t
end
function current_time(q::Quantity)
if !isa(q, Unitful.Time)
error(string(q) * " does not have units of time!")
end
return q
end
set_fps!(fps) = (global FPS = fps)
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1015 | export VideoParams, open_video, close_video
# frame is an intermediate frame before being written to the writer
mutable struct VideoParams
writer::VideoIO.VideoWriter
frame::Array{RGB{N0f8}}
frame_count::Int
end
function VideoParams(res; framerate = 30, filename = "out.mp4",
encoder_options = (crf=23,
preset="medium",
pixel_format = "yuv420p"))
return VideoParams(VideoIO.VideoWriter(filename, RGB{N0f8}, res;
framerate = framerate,
encoder_options = encoder_options),
zeros(RGB{N0f8}, res), 0)
end
function open_video(args...; kwargs...)
if OUTPUT
return VideoParams(args...; kwargs...)
else
return nothing
end
end
function close_video(v::VideoParams)
close_video_out!(v.writer)
end
# In the case OUTPUT = false
function close_video(n::Nothing)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 640 | export FractalExecutable, fee, update!
abstract type FractalExecutable end;
function fee(T::Type{FE}, args...; kwargs...) where FE <: FractalExecutable
return FE(args...; kwargs...)
end
function update!(H::FractalExecutable; kwargs...)
possible_kwargs = [H.fis[i].s for i = 1:length(H.fis[i])]
for i = 1:length(kwargs)
if in(kwargs[i][1], possible_kwargs)
set!(H.fis[i], kwargs[i][2])
else
@error("Key word argument "*string(kwarg[1])*
" is not a FractalInput!\n"*
"Please use one of the following...\n", possible_kwargs)
end
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 3055 | export Hutchinson
mutable struct Hutchinson <: FractalExecutable
fxs::Tuple
kwargs::Tuple
fis::Tuple
color_fxs::Tuple
color_kwargs::Tuple
color_fis::Tuple
prob_set::Tuple
fnums::Tuple
end
Hutchinson() = Hutchinson((),(),(),(),(),(),(),())
Hutchinson(H::Hutchinson; depth = 0) = H
function Hutchinson(fum::FractalUserMethod, color_fum::FractalUserMethod,
prob::Number)
return Hutchinson((fum.fx,), (fum.kwargs,), (fum.fis,),
(color_fum.fx,), (color_fum.kwargs,), (color_fum.fis,),
(prob,), (1,))
end
function color_splat(fo_color::FractalUserMethod)
return ((fo_color.fx,), (fo_color.kwargs,), (fo_color.fis,))
end
function color_splat(fo_color::Tuple)
fxs = [fo_color[i].fx for i = 1:length(fo_color)]
kwargs = [fo_color[i].kwargs for i = 1:length(fo_color)]
fis = [fo_color[i].fis for i = 1:length(fo_color)]
return ((Tuple(fxs),), (Tuple(kwargs),), (Tuple(fis),))
end
function Hutchinson(fo::FractalOperator; depth = 0)
if depth <= 1 && fo.prob != 1
@warn("Setting probability to 1 for standalone FractalOperator...")
prob = 1
else
prob = fo.prob
end
return Hutchinson((fo.op.fx,), (fo.op.kwargs,), (fo.op.fis,),
color_splat(fo.color)...,
(prob,), (1,))
end
function Hutchinson(H1::Hutchinson, H2::Hutchinson)
return Hutchinson((H1.fxs..., H2.fxs...),
(H1.kwargs..., H2.kwargs...),
(H1.fis..., H2.fis...),
(H1.color_fxs..., H2.color_fxs...),
(H1.color_kwargs..., H2.color_kwargs...),
(H1.color_fis..., H2.color_fis...),
(H1.prob_set..., H2.prob_set...),
(H1.fnums..., H2.fnums...))
end
function Hutchinson(fos::Union{Tuple, Vector}; depth = 0)
if depth > 1
error("Cannot create Hutchinson operators of depth > 2! (#65)")
end
if length(fos) == 0
error("No FractalOperator provided!")
elseif length(fos) == 1
H = Hutchinson(fos[1]; depth = 1)
H.fnums = (length(fos[1]),)
return H
else
H = Hutchinson()
multilayer_flag = false
prob = 0.0
for i = 1:length(fos)
if isa(fos[i], Union{Tuple, Vector})
multilayer_flag = true
elseif depth > 0
prob += fos[i].prob
end
H = Hutchinson(H, Hutchinson(fos[i]; depth = depth+1))
end
if multilayer_flag
H.fnums = length.(fos)
else
if !(eltype(fos) <: Hutchinson)
H.fnums = Tuple(1 for i = 1:length(fos))
end
if prob > 1.0
@warn("Probabilities do not add up to 1!\n"*
"Setting all operators to be equally likely...")
H.prob_set = Tuple([1/length(fos) for i = 1:length(fos)])
end
end
return H
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 929 | export Shader
mutable struct Shader <: FractalExecutable
fxs::Tuple
kwargs::Tuple
fis::Tuple
end
Shader() = Shader((),(),())
function Shader(fum::FractalUserMethod)
return Shader((fum.fx,), (fum.kwargs,), (fum.fis,))
end
function Shader(fums::Tuple)
if length(fums) == 0
error("No FractalUserMethod provided!")
elseif length(fums) == 1
return Shader(fums[1])
else
# recursive
shader = Shader()
for i = 1:length(fums)
shader = Shader(shader, Shader(fums[i]))
end
return shader
end
end
function Shader(a::Shader, b::Shader)
return Shader((a.fxs..., b.fxs...),
(a.kwargs..., b.kwargs...),
(a.fis..., b.fis...))
end
function Shader(shaders::Vector{Shader})
shader = shaders[1]
for i = 2:length(shaders)
shader = Shader(shader, shaders[i])
end
return shader
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1216 | export ColorLayer
mutable struct ColorLayer <: AbstractLayer
color::Union{RGB, RGBA}
canvas::AT where AT <: AbstractArray
position::Tuple
world_size::Tuple
ppu::Number
params::NamedTuple
postprocessing_steps::Vector{APP} where APP <: AbstractPostProcess
end
function ColorLayer(c::CT;
postprocessing_steps = Vector{AbstractPostProcess}([]),
world_size = (0.9, 1.6),
position = (0.0, 0.0),
ppu = 1200,
ArrayType = Array,
FloatType = Float32,
numthreads = 256) where CT <: Union{RGB, RGBA}
res = (ceil(Int,world_size[1]*ppu), ceil(Int,world_size[2]*ppu))
if isa(c, RGB)
c = RGBA(c)
end
c = RGBA{FloatType}(c)
return ColorLayer(c,
ArrayType(fill(c, res)),
position,
world_size,
ppu,
params(ColorLayer;
ArrayType = ArrayType,
FloatType = FloatType,
numthreads = numthreads),
postprocessing_steps)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 9042 | export FractalLayer, default_params, params, CopyToCanvas, to_canvas!
# Note: the rgb components needed to be spread into separate arrays for indexing
# reasons in the KA kernels
mutable struct FractalLayer <: AbstractLayer
H1::Union{Nothing, Hutchinson}
H2::Union{Nothing, Hutchinson}
particles::APT where APT <: AbstractArray{AP} where AP <: AbstractPoint
values::AIT where AIT <: AbstractArray{Int}
reds::AFT where AFT <: AbstractArray{FT} where FT <: AbstractFloat
greens::AFT where AFT <: AbstractArray{FT} where FT <: AbstractFloat
blues::AFT where AFT <: AbstractArray{FT} where FT <: AbstractFloat
alphas::AFT where AFT <: AbstractArray{FT} where FT <: AbstractFloat
canvas::ACT where ACT <: AbstractArray{CT} where CT <: RGBA
position::Tuple
world_size::Tuple
ppu::Number
params::NamedTuple
postprocessing_steps::Vector{APP} where APP <: AbstractPostProcess
end
function default_params(a::Type{FractalLayer}; config = :standard,
ArrayType = Array, FloatType = Float32,
num_particles = 1000, num_iterations = 1000,
dims = 2)
if config == :standard
return (numthreads = 256, gamma = 2.2, logscale = false,
calc_max_value = false, max_value = 1, ArrayType = ArrayType,
FloatType = FloatType, num_ignore = 20, dims = dims,
solver_type = :semi_random, num_particles = num_particles,
num_iterations = num_iterations)
elseif config == :fractal_flame
return (numthreads = 256, gamma = 2.2, logscale = true,
calc_max_value = true, max_value = 1, ArrayType = ArrayType,
FloatType = FloatType, num_ignore = 20, dims = dims,
solver_type = :semi_random, num_particles = num_particles,
num_iterations = num_iterations)
end
end
function params(a::Type{FractalLayer}; numthreads = 256,
ArrayType = Array, FloatType = Float32,
logscale = false, gamma = 2.2, calc_max_value = false,
max_value = 1, num_ignore = 20, num_particles = 1000,
num_iterations = 1000, dims = 2, solver_type = :semi_random)
return (numthreads = numthreads,
ArrayType = ArrayType,
FloatType = FloatType,
logscale = logscale,
gamma = gamma,
max_value = max_value,
calc_max_value = calc_max_value,
num_ignore = num_ignore,
num_particles = num_particles,
num_iterations = num_iterations,
dims = dims,
solver_type = solver_type)
end
# Creating a default call
function FractalLayer(p, v, r, g, b, a, c, position, world_size, ppu;
postprocessing_steps = AbstractPostProcess[],
config = standard,
H1 = Hutchinson(), H2 = nothing)
postprocessing_steps = vcat([CopyToCanvas()], postprocessing_steps)
return FractalLayer(H1, H2, p, v, r, g, b, a, c, position, world_size, ppu,
default_params(FractalLayer,
config = config,
ArrayType = typeof(v),
FloatType = eltype(v)),
postprocessing_steps)
end
# Create a blank, black image of size s
function FractalLayer(; config = :meh, ArrayType=Array, FloatType = Float32,
postprocessing_steps = AbstractPostProcess[],
world_size = (0.9, 1.6), position = (0.0, 0.0),
ppu = 1200, gamma = 2.2, logscale = false,
calc_max_value = false, max_value = 1,
numthreads = 256,
num_particles = 1000, num_iterations = 1000, dims = 2,
H1 = Hutchinson(), H2 = nothing,
solver_type = :semi_random)
postprocessing_steps = vcat([CopyToCanvas()], postprocessing_steps)
res = (ceil(Int, world_size[1]*ppu), ceil(Int, world_size[2]*ppu))
p = generate_points(num_particles; dims = dims, ArrayType = ArrayType)
v = ArrayType(zeros(Int,res))
r = ArrayType(zeros(FloatType,res))
g = ArrayType(zeros(FloatType,res))
b = ArrayType(zeros(FloatType,res))
a = ArrayType(zeros(FloatType,res))
c = ArrayType(fill(RGBA(FloatType(0),0,0,0), res))
if config == :standard || config == :fractal_flame
return FractalLayer(H1, H2, p, v, r, g, b, a, c,
position, world_size, ppu,
default_params(FractalLayer;
ArrayType = ArrayType,
FloatType = FloatType,
config = config,
num_particles = num_particles,
num_iterations = num_iterations,
dims = dims),
postprocessing_steps)
else
return FractalLayer(H1, H2, p, v, r, g, b, a, c,
position, world_size, ppu,
params(FractalLayer;
ArrayType=ArrayType,
FloatType = FloatType,
gamma = gamma,
logscale = logscale,
calc_max_value = calc_max_value,
max_value = max_value,
numthreads = numthreads,
num_particles = num_particles,
num_iterations = num_iterations,
dims = dims,
solver_type = solver_type),
postprocessing_steps)
end
end
#------------------------------------------------------------------------------#
# CopyToCanvas for FractalLayer
#------------------------------------------------------------------------------#
struct CopyToCanvas <: AbstractPostProcess
op::Function
initialized::Bool
end
CopyToCanvas() = CopyToCanvas(to_canvas!, true)
function norm_layer!(layer::FractalLayer)
layer.reds .= norm_component.(layer.reds, layer.values)
layer.greens .= norm_component.(layer.greens, layer.values)
layer.blues .= norm_component.(layer.blues, layer.values)
layer.alphas .= norm_component.(layer.alphas, layer.values)
end
function norm_component(color, value)
if value == 0 || isnan(value)
return color
else
return color / value
end
end
function to_canvas!(layer::FractalLayer, canvas_params::CopyToCanvas)
to_canvas!(layer)
end
function to_canvas!(layer::FractalLayer)
f = FL_canvas_kernel!
if layer.params.logscale
norm_layer!(layer)
f = FL_logscale_kernel!
end
if layer.params.calc_max_value != 0
update_params!(layer; max_value = maximum(layer.values))
end
backend = get_backend(layer.canvas)
kernel! = f(backend, layer.params.numthreads)
if layer.params.logscale
kernel!(layer.canvas, layer.reds, layer.greens, layer.blues,
layer.alphas, layer.values, layer.params.gamma,
layer.params.max_value, ndrange = length(layer.canvas))
else
kernel!(layer.canvas, layer.reds, layer.greens, layer.blues,
layer.alphas, layer.values,
ndrange = length(layer.canvas))
end
return nothing
end
@kernel function FL_canvas_kernel!(canvas, layer_reds, layer_greens,
layer_blues, layer_alphas, layer_values)
tid = @index(Global, Linear)
FT = eltype(layer_reds)
val = layer_values[tid]
# warp divergence, WOOOoooOOO
if val > 0
@inbounds r = min(layer_reds[tid]/val,1)
@inbounds g = min(layer_greens[tid]/val,1)
@inbounds b = min(layer_blues[tid]/val,1)
@inbounds a = min(layer_alphas[tid]/val,1)
@inbounds canvas[tid] = RGBA(r,g,b,a)
else
@inbounds canvas[tid] = RGBA(FT(0), 0, 0, 0)
end
end
@kernel function FL_logscale_kernel!(canvas, layer_reds, layer_greens,
layer_blues, layer_alphas, layer_values,
layer_gamma, layer_max_value)
tid = @index(Global, Linear)
FT = eltype(layer_reds)
if layer_max_value != 0
@inbounds alpha = log10((9*layer_values[tid]/layer_max_value)+1)
@inbounds r = layer_reds[tid]^(1/layer_gamma)
@inbounds g = layer_greens[tid]^(1/layer_gamma)
@inbounds b = layer_blues[tid]^(1/layer_gamma)
@inbounds a = layer_alphas[tid]^(1/layer_gamma) * alpha^(1/layer_gamma)
@inbounds canvas[tid] = RGBA(r,g,b,a)
else
@inbounds canvas[tid] = RGBA(FT(0), 0, 0, 0)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1599 | export ImageLayer
mutable struct ImageLayer <: AbstractLayer
canvas::AT where AT <: AbstractArray
position::Tuple
world_size::Tuple
ppu::Number
params::NamedTuple
postprocessing_steps::Vector{APP} where APP <: AbstractPostProcess
end
# dynamically sets ppu based on world_size
function ImageLayer(img;
postprocessing_steps = Vector{AbstractPostProcess}([]),
position = (0.0, 0.0),
ppu = 1200,
ArrayType = Array,
FloatType = Float32,
numthreads = 256)
world_size = (size(img)[1]/ppu, size(img)[2]/ppu)
return ImageLayer(img, position, world_size, ppu,
params(ImageLayer;
ArrayType = ArrayType,
FloatType = FloatType,
numthreads = numthreads),
postprocessing_steps)
end
function ImageLayer(filename::String;
postprocessing_steps = Vector{AbstractPostProcess}([]),
position = (0.0, 0.0),
ppu = 1,
ArrayType = Array,
FloatType = Float32,
numthreads = 256)
img = load(filename)
return ImageLayer(img;
position = position,
ppu = ppu,
ArrayType = ArrayType,
FloatType = FloatType,
numthreads = numthreads,
postprocessing_steps = postprocessing_steps)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 4231 | export AbstractLayer, default_params, params, update_params!, find_overlap,
find_bounds, AbstractPostProcess
abstract type AbstractLayer end;
abstract type AbstractPostProcess end;
struct Overlap
range::Tuple
start_index_1::Tuple
start_index_2::Tuple
bounds::NamedTuple
end
# TODO: higher dimensions...
function find_bounds(position, world_size)
return (ymin = position[1] - 0.5 * world_size[1],
ymax = position[1] + 0.5 * world_size[1],
xmin = position[2] - 0.5 * world_size[2],
xmax = position[2] + 0.5 * world_size[2])
end
function find_bounds(layer)
return find_bounds(layer.position, layer.world_size)
end
# does not return Overlap because it is used inside KA kernels
@inline function find_overlap(index, world_size_1, world_size_2)
filter_ymin = floor(Int, index[1] - 0.5*world_size_2[1])+1
filter_ymax = floor(Int, index[1] + 0.5*world_size_2[1])
filter_xmin = floor(Int, index[2] - 0.5*world_size_2[2])+1
filter_xmax = floor(Int, index[2] + 0.5*world_size_2[2])
ymin = max(filter_ymin, 1)
xmin = max(filter_xmin, 1)
ymax = min(filter_ymax, world_size_1[1])
xmax = min(filter_xmax, world_size_1[2])
if filter_ymin < 1
# note: the 2 is because it is 1 + (1 - filter_ymin)
filter_ymin = 2 - filter_ymin
else
filter_ymin = 1
end
if filter_xmin < 1
filter_xmin = 2 - filter_xmin
else
filter_xmin = 1
end
# range, start_index_1, start_index_2
return ((ymax - ymin + 1, xmax - xmin + 1), (ymin, xmin),
(filter_ymin, filter_xmin))
end
function find_overlap(layer_1::AL1, layer_2::AL2) where {AL1 <: AbstractLayer,
AL2 <: AbstractLayer}
# Returning early if size and position is the same
if layer_1.world_size == layer_2.world_size &&
layer_1.position == layer_2.position
return Overlap(size(layer_1.canvas), (1,1), (1,1), find_bounds(layer_1))
end
# finding boundaries of each canvas
bounds_1 = find_bounds(layer_1)
bounds_2 = find_bounds(layer_2)
# finding overlap region and starting indices
ymin = max(bounds_1.ymin, bounds_2.ymin)
xmin = max(bounds_1.xmin, bounds_2.xmin)
ymax = min(bounds_1.ymax, bounds_2.ymax)
xmax = min(bounds_1.xmax, bounds_2.xmax)
if xmax < xmin || ymax < ymin
@warn("No overlap between layers...")
return nothing
end
start_index_1 = [1, 1]
start_index_2 = [1, 1]
if ymin > bounds_1.ymin
start_index_1[1] = floor(Int, layer_1.ppu * (ymin - bounds_1.ymin)) + 1
end
if xmin > bounds_1.xmin
start_index_1[2] = floor(Int, layer_1.ppu * (xmin - bounds_1.xmin)) + 1
end
if ymin > bounds_2.ymin
start_index_2[1] = floor(Int, layer_2.ppu * (ymin - bounds_2.ymin)) + 1
end
if xmin > bounds_2.xmin
start_index_2[2] = floor(Int, layer_2.ppu * (xmin - bounds_2.xmin)) + 1
end
return Overlap((floor(Int, (ymax - ymin)*layer_1.ppu),
floor(Int, (xmax - xmin)*layer_1.ppu)),
Tuple(start_index_1),
Tuple(start_index_2),
(ymin = ymin, ymax = ymax, xmin = xmin, xmax = xmax))
end
function default_params(a::Type{AL}) where AL <: AbstractLayer
return (numthreads = 256, numcores = 4,
ArrayType = Array, FloatType = Float32)
end
function params(a::Type{AL}; numthreads = 256, numcores = 4, ArrayType = Array,
FloatType = Float32) where AL <: AbstractLayer
return (numthreads = numthreads,
numcores = numcores,
ArrayType = ArrayType,
FloatType = FloatType)
end
function update_params!(layer::AL; kwargs...) where AL <: AbstractLayer
some_keys = [keys(layer.params)...]
some_values = [values(layer.params)...]
new_keys = [keys(kwargs)...]
new_values = [values(kwargs)...]
for i = 1:length(some_keys)
for j = 1:length(new_keys)
if some_keys[i] == new_keys[j]
some_values[i] = new_values[j]
end
end
end
layer.params = NamedTuple{Tuple(some_keys)}(some_values)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2075 | export ShaderLayer
mutable struct ShaderLayer <: AbstractLayer
shader::Shader
canvas::AT where AT <: AbstractArray
position::Tuple
world_size::Tuple
ppu::Number
params::NamedTuple
postprocessing_steps::Vector{APP} where APP <: AbstractPostProcess
end
function ShaderLayer(shader::Shader;
postprocessing_steps = Vector{AbstractPostProcess}([]),
world_size = (0.9, 1.6),
position = (0.0, 0.0),
ppu = 1200,
ArrayType = Array,
FloatType = Float32,
numthreads = 256)
res = (ceil(Int, world_size[1]*ppu), ceil(Int, world_size[2]*ppu))
return ShaderLayer(shader,
ArrayType(fill(RGBA(FloatType(0),0,0,0), res)),
position,
world_size,
ppu,
params(ColorLayer;
ArrayType = ArrayType,
FloatType = FloatType,
numthreads = numthreads),
postprocessing_steps)
end
function ShaderLayer(fums::Union{FractalUserMethod, Tuple};
postprocessing_steps = Vector{AbstractPostProcess}([]),
world_size = (0.9, 1.6),
position = (0.0, 0.0),
ppu = 1200,
ArrayType = Array,
FloatType = Float32,
numthreads = 256)
res = (ceil(Int, world_size[1]*ppu), ceil(Int, world_size[2]*ppu))
return ShaderLayer(Shader(fums),
ArrayType(fill(RGBA(FloatType(0),0,0,0), res)),
position,
world_size,
ppu,
params(ColorLayer;
ArrayType = ArrayType,
FloatType = FloatType,
numthreads = numthreads),
postprocessing_steps)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 105 | function remove_vectors(a)
return a
end
function remove_vectors(a::Vector)
return Tuple(a)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 635 | export in_ellipse, in_rectangle
@inline function in_ellipse(x, y, position, rotation, r1, r2)
r = sqrt(x*x + y*y)
theta = atan(y,x)
x2 = r*cos(theta-rotation)
y2 = r*sin(theta-rotation)
if (x2-position[2])^2/r2^2 + (y2-position[1])^2/r1^2 <= 1
return true
end
return false
end
@inline function in_rectangle(x, y, position, rotation, scale_x, scale_y)
r = sqrt(x*x + y*y)
theta = atan(y,x)
x2 = r*cos(theta-rotation)
y2 = r*sin(theta-rotation)
if abs(x2-position[2]) <= scale_x*0.5 &&
abs(y2-position[1]) <= scale_y*0.5
return true
end
return false
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 3358 | @inline function find_bin(histogram_output, input_y, input_x,
bounds, bin_widths)
bin = ceil(Int, (input_y - bounds[1]) / bin_widths[1])
slab = size(histogram_output)[1]
bin += Int(ceil(((input_x - bounds[3]) / bin_widths[2])-1)*slab)
return bin
end
@inline function find_bin(histogram_output, input,
tid, dims, bounds, bin_widths)
b_index = 1
bin = ceil(Int, (input[tid, 1] - bounds[1]) / bin_widths[1])
slab = 1
for i = 2:dims
slab *= size(histogram_output)[i-1]
b_index += 2
bin += Int(ceil(Int,(((input[tid, i]) - bounds[b_index]) /
bin_widths[i])-1)*slab)
end
return bin
end
# This is a naive histogramming method that is preferred for CPU calculations
@kernel function naive_histogram_kernel!(histogram_output, input,
bounds, bin_widths, dims)
tid = @index(Global, Linear)
# I want to turn this in to an @uniform, but that fails on CPU (#274)
bin = find_bin(histogram_output, input, tid, dims, bounds, bin_widths)
@inbounds @atomic histogram_output[bin] += 1
end
# This a 1D histogram kernel where the histogramming happens on shmem
@kernel function histogram_kernel!(histogram_output, input,
bounds, bin_widths, dims)
tid = @index(Global, Linear)
lid = @index(Local, Linear)
@uniform warpsize = Int(32)
@uniform gs = @groupsize()[1]
@uniform N = length(histogram_output)
shared_histogram = @localmem Int (gs)
# This will go through all input elements and assign them to a location in
# shmem. Note that if there is not enough shem, we create different shmem
# blocks to write to. For example, if shmem is of size 256, but it's
# possible to get a value of 312, then we will have 2 separate shmem blocks,
# one from 1->256, and another from 256->512
@uniform max_element = 1
@uniform min_element = 1
while max_element <= N
# Setting shared_histogram to 0
@inbounds shared_histogram[lid] = 0
@synchronize()
# I want to turn this in to an @uniform, but that fails on CPU (#274)
bin = find_bin(histogram_output, input, tid, dims, bounds, bin_widths)
max_element = min_element + gs
if max_element > N + 1
max_element = N+1
end
# Defining bin on shared memory and writing to it if possible
if bin >= min_element && bin < max_element
bin -= min_element-1
@inbounds @atomic shared_histogram[bin] += 1
max_element = N
end
@synchronize()
if ((lid+min_element-1) <= N)
@inbounds @atomic histogram_output[lid+min_element-1] += shared_histogram[lid]
end
min_element += gs
end
end
function histogram!(histogram_output, input; dims = ndims(histogram_output),
bounds = zeros(dims,2),
bin_widths = [1 for i = 1:dims],
numcores = 4, numthreads = 256, ArrayType = Array)
backend = get_backend(histogram_output)
kernel! = naive_histogram_kernel!(backend, numthreads)
kernel!(histogram_output, input, ArrayType(bounds), ArrayType(bin_widths),
dims, ndrange=size(input)[1])
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 3861 | # Numbers come from...
#@article{l1999tables,
# title={Tables of linear congruential generators of different sizes and good lattice structure},
# author={L’ecuyer, Pierre},
# journal={Mathematics of Computation},
# volume={68},
# number={225},
# pages={249--260},
# year={1999},
# url={https://www.ams.org/mcom/1999-68-225/S0025-5718-99-00996-5/S0025-5718-99-00996-5.pdf}
#}
# This is a quick and dirty method to generate a seed
@inline function quick_seed(id)
return UInt(id*1099087573)
end
# This is a linear congruential generator (LCG)
# This uses a default modulo 64 for UInt
@inline function LCG_step(x::UInt, a::UInt, c::UInt)
return UInt(a*x+c) #%m, where m = 64
end
# This is a combination of both
@inline function simple_rand(x::Union{Int, UInt})
return LCG_step(UInt(x), UInt(2862933555777941757), UInt(1))
end
@inline function find_choice(prob_set, start, fnum, seed)
rnd = seed/typemax(UInt)
p = 0.0
for i = start:start + fnum - 1
p += prob_set[i]
if rnd <= p
return i - start + 1
end
end
return 0
end
# The fid (Function ID) is used to select which operation in a
# function system to select for each iteration.
# The fid could have multiple function systems in it. Quick example:
# 2 function systems (fs) with 3 and 5 functions respectively.
# The fid might be 011 01, read from right to left
# The first 2 digits, 01, represent a selection between 1 and 3 from fs 1
# The second 3 digits, 011, represent a selection between 1 and 5 from fs 2
# As a UInt, the value is saved as 25
# encoding an fid involves generating a random UInt and going through the
# bitstring to ensure that each set of possible values is a possible option
@inline function create_fid(fnums, rng::UI) where UI <: Unsigned
val = UI(0)
offset = UI(0)
for i = 1:length(fnums)
# needed bits to hold the fnum
bitsize = ceil(UI, log2(fnums[i]))
# set of 1's to mask only those bits in the rng string
bitmask = UI(2^(bitsize + offset) - 1 - (2^offset - 1))
# shifting the bits from rng over to read them as an int
a = UI(((rng & bitmask) >> offset))
# checking if that option is actually valid,
# if not, using the rng string to create an adhoc new choice
if a+1 > fnums[i]
a = UI(rng % fnums[i])
end
# Shifting back to appropriate location
b = a << offset
# adding to final bitstring
val += b
# creating offset bit number for next iteration
offset += bitsize
end
return val
end
@inline function create_fid(probs, fnums, seed)
fid = UInt(0)
bit_offset = 0
fx_offset = 1
for i = 1:length(fnums)
if probs[fx_offset] < 1
seed = simple_rand(UInt(seed))
choice = find_choice(probs, fx_offset, fnums[i], seed)
fid += ((choice-1) << bit_offset)
bit_offset += ceil(UInt, log2(fnums[i]))
end
fx_offset += fnums[i]
end
return fid
end
# Decoding takes an offset, which is the number of digits on the fid bitstring
# to ignore from the right hand side.
# Should probably add an error, but was afraid of the conditional
@inline function decode_fid(fid::UI, offset, fnum) where UI <: Unsigned
bitsize = ceil(UI, log2(fnum))
bitmask = UI(2^(bitsize + offset) - 1 - (2^offset - 1))
value = UI((fid & bitmask) >> offset) + 1
return value
end
@inline function find_random_fxs(fid::UI, fnums, probs) where UI <: Unsigned
bit_offset = 0
fx_offset = 0
t_out = ()
for i = 1:length(fnums)
idx = decode_fid(fid, bit_offset, fnums[i]) + fx_offset
t_out = (t_out...,idx)
bit_offset += ceil(UInt,log2(fnums[i]))
fx_offset += fnums[i]
end
return t_out
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2053 | #------------------------------------------------------------------------------#
# Helper Functions
#------------------------------------------------------------------------------#
# Consider also testing RGB
function color_lt(a::CT1, b::CT2) where {CT1 <: RGBA, CT2 <: RGBA}
return (a.r <= b.r) &
(a.g <= b.g) &
(a.b <= b.b) &
(a.alpha <= b.alpha)
end
function color_gt(a::CT1, b::CT2) where {CT1 <: RGBA, CT2 <: RGBA}
return color_lt(b, a)
end
#------------------------------------------------------------------------------#
# Tests
#------------------------------------------------------------------------------#
function chaos_tests(ArrayType::Type{AT}) where AT <: AbstractArray
H = Fable.define_circle(; position = [0.0,0.0], radius = 2.0,
color = [1.0, 1.0, 1.0, 1.0],
chosen_fx = :naive_disk)
fl = FractalLayer(; ArrayType = ArrayType, config = :fractal_flame,
world_size = (4,4), ppu = 11/4, H1 = H)
run!(fl)
img = write_image(fl)
@test color_gt(img[5,5], img[1,1])
@test isapprox(img[5,5].r, img[4,4].r)
@test isapprox(img[5,5].g, img[4,4].g)
@test isapprox(img[5,5].b, img[4,4].b)
GC.gc()
H2 = Fable.define_circle(; position = [0.0,0.0], radius = 2.0,
color = [1.0, 1.0, 1.0, 1.0],
chosen_fx = :constant_disk)
fl = FractalLayer(; ArrayType = ArrayType, config = :simple, H1 = H2,
world_size = (4,4), ppu = 11/4)
run!(fl)
img = write_image(fl)
@test isapprox(img[5,5], img[4,4])
@test !isapprox(img[5,5], img[1,1])
end
#------------------------------------------------------------------------------#
# Testsuite
#------------------------------------------------------------------------------#
function chaos_testsuite(ArrayType::Type{AT}) where AT <: AbstractArray
@testset "Chaos game tests for $(string(ArrayType))s" begin
chaos_tests(ArrayType)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 1332 | #------------------------------------------------------------------------------#
# Test Definitions
#------------------------------------------------------------------------------#
function example_tests(ArrayType::Type{AT}) where AT <: AbstractArray
include("../examples/barnsley.jl")
barnsley_example(1000, 1000; ArrayType = ArrayType)
@test true
main = nothing
include("../examples/layering.jl")
layering_example(1000, 1000; ArrayType = ArrayType)
@test true
main = nothing
include("../examples/shader.jl")
shader_example(radial; ArrayType = ArrayType)
@test true
main = nothing
include("../examples/sierpinski.jl")
sierpinski_example(1000, 1000, 10; ArrayType = ArrayType)
@test true
main = nothing
include("../examples/smear.jl")
smear_example(1000, 1000, 10; ArrayType = ArrayType)
@test true
main = nothing
end
#------------------------------------------------------------------------------#
# Testsuite Definition
#------------------------------------------------------------------------------#
function example_testsuite(ArrayType::Type{AT}) where AT <: AbstractArray
Fable.set_output(false)
@testset "running all examples on $(string(ArrayType))s" begin
example_tests(ArrayType)
end
Fable.set_output(true)
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 5248 | #------------------------------------------------------------------------------#
# Helper Functions
#------------------------------------------------------------------------------#
function find_dims(a)
if ndims(a) == 1
return 1
else
return(size(a))[2]
end
end
# Function to use as a baseline for CPU metrics
function create_histogram!(histogram_output, input;
dims = find_dims(input),
bounds = zeros(dims, 2),
bin_widths = ones(dims))
for i = 1:size(input)[1]
bin = Fable.find_bin(histogram_output, input, i,
dims, bounds, bin_widths)
histogram_output[bin] += 1
end
end
#------------------------------------------------------------------------------#
# Test Definitions
#------------------------------------------------------------------------------#
function find_bin_tests()
# Integer test
# defining a to be 1's everywhere
a = zeros(100,2)
for i = 1:10
a[(i-1)*10+1:i*10,1] .= i
a[(i-1)*10+1:i*10,2] = 1:10
end
dims = 2
bin_widths = [1,1]
bounds = [0 0; 0 0]
histogram_output = zeros(10,10)
create_histogram!(histogram_output, a;
dims = dims, bounds = bounds, bin_widths = bin_widths)
@test histogram_output == ones(10,10)
# Floating point test
# Subtracting 0.5 from A so it rounds up to the correct bins
a[:] .-= 0.5
histogram_output[:] .= 0
create_histogram!(histogram_output, a;
dims = dims, bounds = bounds, bin_widths = bin_widths)
@test histogram_output == ones(10,10)
end
function histogram_kernel_tests(ArrayType::Type{AT}) where AT <: AbstractArray
rand_input = rand(Float32, 128)*128
linear_input = [i for i = 1:1024]
linear_input_2d = zeros(10000,2)
for i = 1:100
linear_input_2d[(i-1)*100+1:i*100,1] .= i
linear_input_2d[(i-1)*100+1:i*100,2] = 1:100
end
offset_input_2d = zeros(10000,2)
offset_input_2d[:] .= linear_input_2d[:] .- 0.5
all_2 = [2 for i = 1:512]
rand_input_2d = rand(Float32, 128, 2)*128
rand_input_3d = rand(Float32, 32, 3)*32
histogram_rand_baseline = zeros(Int, 128)
histogram_linear_baseline = zeros(Int, 1024)
histogram_linear_2d_baseline = zeros(Int, 100, 100)
histogram_offset_2d_baseline = zeros(Int, 100, 100)
histogram_2_baseline = zeros(Int, 2)
histogram_rand_baseline_2d = zeros(Int, 128, 128)
histogram_rand_baseline_3d = zeros(Int, 32, 32, 32)
create_histogram!(histogram_rand_baseline, rand_input)
create_histogram!(histogram_linear_baseline, linear_input)
create_histogram!(histogram_linear_2d_baseline, linear_input_2d)
create_histogram!(histogram_offset_2d_baseline, offset_input_2d)
create_histogram!(histogram_2_baseline, all_2)
create_histogram!(histogram_rand_baseline_2d, rand_input_2d)
create_histogram!(histogram_rand_baseline_3d, rand_input_3d)
rand_histogram = ArrayType(zeros(Int, 128))
linear_histogram = ArrayType(zeros(Int, 1024))
linear_2d_histogram = ArrayType(zeros(Int, 100, 100))
offset_2d_histogram = ArrayType(zeros(Int, 100, 100))
histogram_2s = ArrayType(zeros(Int, 2))
rand_histogram_2d = ArrayType(zeros(Int, 128, 128))
rand_histogram_3d = ArrayType(zeros(Int, 32, 32, 32))
@time Fable.histogram!(rand_histogram, ArrayType(rand_input);
ArrayType = ArrayType)
@time Fable.histogram!(linear_histogram, ArrayType(linear_input);
ArrayType = ArrayType)
@time Fable.histogram!(linear_2d_histogram, ArrayType(linear_input_2d);
ArrayType = ArrayType)
@time Fable.histogram!(offset_2d_histogram, ArrayType(linear_input_2d);
ArrayType = ArrayType)
@time Fable.histogram!(histogram_2s, ArrayType(all_2);
ArrayType = ArrayType)
@time Fable.histogram!(rand_histogram_2d, ArrayType(rand_input_2d);
ArrayType = ArrayType)
@time Fable.histogram!(rand_histogram_3d, ArrayType(rand_input_3d);
ArrayType = ArrayType)
@test isapprox(Array(rand_histogram), histogram_rand_baseline)
@test isapprox(Array(linear_histogram), histogram_linear_baseline)
@test isapprox(Array(linear_2d_histogram), histogram_linear_2d_baseline)
@test isapprox(Array(offset_2d_histogram), histogram_offset_2d_baseline)
@test isapprox(Array(histogram_2s), histogram_2_baseline)
@test isapprox(Array(rand_histogram_2d), histogram_rand_baseline_2d)
@test isapprox(Array(rand_histogram_3d), histogram_rand_baseline_3d)
end
#------------------------------------------------------------------------------#
# Testsuit Definition
#------------------------------------------------------------------------------#
function histogram_testsuite(ArrayType::Type{AT}) where AT <: AbstractArray
if ArrayType <: Array
@testset "find bin tests" begin
find_bin_tests()
end
end
@testset "Histogram kernel tests for $(string(ArrayType))s" begin
histogram_kernel_tests(ArrayType)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 9839 | # TODO: Layering at different positions (need to fix io functions first)
#------------------------------------------------------------------------------#
# Helper Functions
#------------------------------------------------------------------------------#
# shader that is white above 0, and black below 0
test_fum = @fum color function test_fum(x,y)
if y > 0
return RGBA{Float32}(1,1,1,1)
else
return RGBA{Float32}(0,0,0,0)
end
end
#------------------------------------------------------------------------------#
# Tests
#------------------------------------------------------------------------------#
function layering_tests(ArrayType::Type{AT}) where AT <: AbstractArray
cl = ColorLayer(RGBA(1, 0, 1, 1); world_size = (4, 4), ppu = 11/4,
ArrayType = ArrayType)
sl = ShaderLayer(test_fum; world_size = (4, 4), ppu = 11/4,
ArrayType = ArrayType)
circle = Fable.define_circle(; position = [0.0,0.0], radius = 2.0,
color = [0.0, 0.0, 1.0, 1.0])
fl = FractalLayer(; world_size = (4,4), ppu = 11/4, H1 = circle,
ArrayType = ArrayType)
layers = [cl, sl, fl]
run!(layers)
img = write_image(layers)
@test isapprox(img[1,1], RGBA(1.0, 0.0, 1.0, 1.0))
@test isapprox(img[11,1], RGBA(1.0, 1.0, 1.0, 1.0))
@test isapprox(img[5,5], RGBA(0.0, 0.0, 1.0, 1.0))
black = RGBA(0,0,0,1)
white = RGBA(1,1,1,1)
position_offsets = ((5, 5), (5, -5), (-5, -5), (-5, 5),
(0, 5), (0, -5), (5, 0), (-5, 0))
# colors at edges of color layer
expected_colors = ((white, white, white, black),
(white, black, white, white),
(black, white, white, white),
(white, white, black, white),
(white, white, black, black),
(black, black, white, white),
(white, black, white, black),
(black, white, black, white))
default_position = (0,0)
default_ppu = 1
default_size = (10,10)
# Offset grid with centered 1 and 2 at LR, LL, UL, UR, D, U, L, R
cl1 = ColorLayer(white;
ppu = default_ppu,
position = default_position,
world_size = default_size)
for i = 1:length(position_offsets)
new_position = (position_offsets[i][1], position_offsets[i][2])
cl2 = ColorLayer(black;
ppu = default_ppu,
position = new_position,
world_size = default_size)
img = write_image([cl1, cl2])
@test img[1,1] == expected_colors[i][1]
@test img[end,1] == expected_colors[i][2]
@test img[1,end] == expected_colors[i][3]
@test img[end,end] == expected_colors[i][4]
end
# Testing image layers
il = ImageLayer(cl.canvas)
write_image(il; filename = "check.png", reset = false)
il2 = ImageLayer("check.png")
@test Array(il.canvas) == Array(il2.canvas)
end
function layer_mixing_tests(ArrayType::Type{AT}) where AT <: AbstractArray
clayer = ColorLayer(RGB(0.5, 0.5, 0.5); world_size = (1, 2), ppu = 1)
clayer_2 = ColorLayer(RGB(0, 0, 0); world_size = (1, 1), ppu = 1,
position = (0, -0.5))
clayer_3 = ColorLayer(RGB(1, 1, 1); world_size = (1, 1), ppu = 1,
position = (0, 0.5))
mix_layers!(clayer, clayer_2)
mix_layers!(clayer, clayer_3)
img = write_image(clayer)
@test img[1] == RGBA(0,0,0,1)
@test img[2] == RGBA(1,1,1,1)
clayer = ColorLayer(RGB(0.5, 0.5, 0.5); world_size = (1, 2), ppu = 1)
square_1 = define_square(; color = Shaders.black,
position = (0, -0.5), scale = 1)
square_2 = define_square(; color = Shaders.white,
position = (0, 0.5), scale = 1)
flayer_1 = FractalLayer(; H1 = square_1, world_size = (1, 2), ppu = 1,
num_particles = 10, num_iterations = 1000)
flayer_2 = FractalLayer(; H1 = square_2, world_size = (1, 2), ppu = 1,
num_particles = 10, num_iterations = 1000)
run!(flayer_1)
run!(flayer_2)
mix_layers!(clayer, flayer_1)
mix_layers!(clayer, flayer_2)
img = write_image(clayer)
@test img[1] == RGBA(0,0,0,1)
@test img[2] == RGBA(1,1,1,1)
end
# TODO: Figure out appropriate indices for this test
function overlap_tests()
# Perfectly aligned
cl1 = ColorLayer(RGB(0,0,0); ppu = 1)
cl2 = ColorLayer(RGB(0,0,0); ppu = 1)
overlap = find_overlap(cl1, cl2)
@test overlap.range == size(cl1.canvas)
@test overlap.start_index_1 == (1,1)
@test overlap.start_index_2 == (1,1)
# inbedded test
cl1 = ColorLayer(RGB(0,0,0); ppu = 1, world_size = (15, 15))
cl2 = ColorLayer(RGB(0,0,0); ppu = 1, world_size = (10, 10))
overlap = find_overlap(cl1, cl2)
@test overlap.range == size(cl2.canvas)
@test overlap.start_index_1 == (3, 3)
@test overlap.start_index_2 == (1, 1)
# different ppus
cl1 = ColorLayer(RGB(0,0,0); ppu = 2, world_size = (10, 10))
cl2 = ColorLayer(RGB(0,0,0); ppu = 3, world_size = (15, 15))
overlap = find_overlap(cl1, cl2)
@test overlap.range == size(cl1.canvas)
@test overlap.start_index_1 == (1, 1)
@test overlap.start_index_2 == (8, 8)
# bounding tests
# TODO: Implement tests for small shifts (such as 0.5)
# I have not quite decided the best way to deal with offset grids
shifts = (0)
default_size = (10, 10)
default_position = (0,0)
default_ppu = 1
position_offsets = ((5, 5), (5, -5), (-5, -5), (-5, 5),
(0, 5), (0, -5), (5, 0), (-5, 0))
expected_ranges = ((5, 5), (5, 5), (5, 5), (5, 5),
(10, 5), (10, 5), (5, 10), (5, 10))
expected_start_indices_1 = ((6, 6), (6, 1), (1, 1), (1, 6),
(1, 6), (1, 1), (6, 1), (1, 1))
expected_start_indices_2 = ((1, 1), (1, 6), (6, 6), (6, 1),
(1, 1), (1, 6), (1, 1), (6, 1))
# Offset grid with centered 1 and 2 at LR, LL, UL, UR, D, U, L, R
cl1 = ColorLayer(RGB(0,0,0);
ppu = default_ppu,
position = default_position,
world_size = default_size)
for shift in shifts
for i = 1:length(position_offsets)
new_position = (position_offsets[i][1] + shift,
position_offsets[i][2] + shift)
cl2 = ColorLayer(RGB(0,0,0);
ppu = default_ppu,
position = new_position,
world_size = default_size)
overlap = find_overlap(cl1, cl2)
@test overlap.range == expected_ranges[i]
@test overlap.start_index_1 == expected_start_indices_1[i]
@test overlap.start_index_2 == expected_start_indices_2[i]
# testing opposite
overlap = find_overlap(cl2, cl1)
@test overlap.range == expected_ranges[i]
@test overlap.start_index_1 == expected_start_indices_2[i]
@test overlap.start_index_2 == expected_start_indices_1[i]
end
end
end
function bounds_tests()
# default tests
cl = ColorLayer(RGB(0,0,0))
bounds = find_bounds(cl)
@test Bool(floor(sum(values(bounds) .== (-0.45, 0.45, -0.8, 0.8))/4))
# random tests
for i = 1:10
position = Tuple(rand(2) * 10 .- 5)
world_size = Tuple(rand(2)*100)
cl = ColorLayer(RGB(0,0,0); position = position,
world_size = world_size, ppu = 1)
bounds = find_bounds(cl)
expected_bounds = (position[1] - world_size[1]*0.5,
position[1] + world_size[1]*0.5,
position[2] - world_size[2]*0.5,
position[2] + world_size[2]*0.5)
@test Bool(floor(sum(values(bounds) .== expected_bounds)/4))
end
end
function rescaling_tests(ArrayType::Type{AT}) where AT <: AbstractArray
black = RGBA(0,0,0,1)
white = RGBA(1,1,1,1)
cl = ColorLayer(black; ppu = 1, world_size = (10,10), ArrayType = ArrayType)
cl2 = ColorLayer(white; ppu = 2, world_size = (10,10),
position = (5,5), ArrayType = ArrayType)
img_1 = write_image([cl, cl2])
@test img_1[1, 1] == black
@test img_1[end, 1] == black
@test img_1[1, end] == black
@test img_1[end, end] == white
cl2 = ColorLayer(white, ppu = 0.2, world_size = (5,5),
position = (0,0), ArrayType = ArrayType)
img_2 = write_image([cl, cl2])
@test img_2[1, 1] == black
@test img_2[end, 1] == black
@test img_2[1, end] == black
@test img_2[end, end] == black
@test img_2[5,5] == white
cl2 = ColorLayer(white, ppu = 0.5, world_size = (10,10),
position = (5,5), ArrayType = ArrayType)
img_3 = write_image([cl, cl2])
@test img_1 == img_3
end
#------------------------------------------------------------------------------#
# Testsuite
#------------------------------------------------------------------------------#
function layering_testsuite(ArrayType::Type{AT}) where AT <: AbstractArray
if ArrayType <: Array
@testset "overlap / bounding tests" begin
overlap_tests()
bounds_tests()
end
end
@testset "Layering tests for $(string(ArrayType))s" begin
layering_tests(ArrayType)
layer_mixing_tests(ArrayType)
end
@testset "Rescaling tests for $(string(ArrayType))s" begin
rescaling_tests(ArrayType)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2078 | #------------------------------------------------------------------------------#
# Tests
# Note: circle tested in layering test, but maybe should also be tested here?
#------------------------------------------------------------------------------#
function square_tests(ArrayType::Type{AT}) where AT <: AbstractArray
color_array = [[1.0, 0, 0, 1],
[0.0, 1, 0, 1],
[0.0, 0, 1, 1],
[1.0, 0, 1, 1]]
square = Fable.define_square(; position = [0.0,0.0], scale = 4.0,
color = color_array)
fl = FractalLayer(; H1 = square, ArrayType = ArrayType,
world_size = (4,4), ppu = 2.5)
run!(fl)
img = write_image(fl)
@test isapprox(img[3,3], RGBA(0.0, 0.0, 1.0, 1.0))
@test isapprox(img[8,3], RGBA(1.0, 0.0, 1.0, 1.0))
@test isapprox(img[3,8], RGBA(0.0, 1.0, 0.0, 1.0))
@test isapprox(img[8,8], RGBA(1.0, 0.0, 0.0, 1.0))
end
function triangle_tests(ArrayType::Type{AT}) where AT <: AbstractArray
color_array = [[1.0, 0, 0, 1],
[0.0, 1, 0, 1],
[0.0, 0, 1, 1],
[1.0, 0, 1, 1]]
triangle = Fable.define_triangle(; color = color_array)
fl = FractalLayer(; H1 = triangle, ArrayType = ArrayType,
world_size = (1,1), ppu = 11)
run!(fl)
img = write_image(fl)
@test isapprox(img[3,6], RGBA(0.0, 1.0, 0.0, 1.0))
@test isapprox(img[7,7], RGBA(1.0, 0.0, 1.0, 1.0))
@test isapprox(img[8,3], RGBA(1.0, 0.0, 0.0, 1.0))
@test isapprox(img[9,9], RGBA(0.0, 0.0, 1.0, 1.0))
end
#------------------------------------------------------------------------------#
# Testsuite
#------------------------------------------------------------------------------#
function object_testsuite(ArrayType::Type{AT}) where AT <: AbstractArray
@testset "square tests for $(string(ArrayType))s" begin
square_tests(ArrayType)
end
@testset "triangle tests for $(string(ArrayType))s" begin
triangle_tests(ArrayType)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2110 | # Note: Not sure how to test the filters (Sobel, Gauss, Outline), so I have
# examples instead
#------------------------------------------------------------------------------#
# Tests
#------------------------------------------------------------------------------#
# This will clip all values above a certain threshold value to be at a
# designated color
function clip_tests(ArrayType::Type{AT}) where AT <: AbstractArray
clip = Clip(; threshold = 0.25, color = RGB(1.0, 0, 1))
cl = ColorLayer(RGB(0.5, 0.5, 0.5); world_size = (1, 1), ppu = 1,
postprocessing_steps = [clip])
img = write_image(cl)
@test img[1,1] == RGBA(1.0, 0.0, 1.0, 1.0)
cl = ColorLayer(RGB(0.2, 0.2, 0.2); world_size = (1, 1), ppu = 1,
postprocessing_steps = [clip])
img = write_image(cl)
@test img[1,1] == RGBA{Float32}(0.2, 0.2, 0.2, 1.0)
clip = Clip(; threshold = 0.25, color = RGB(1.0, 0, 1), clip_op = <)
cl = ColorLayer(RGB(0.5, 0.5, 0.5); world_size = (1, 1), ppu = 1,
postprocessing_steps = [clip])
img = write_image(cl)
@test img[1,1] == RGBA{Float32}(0.5, 0.5, 0.5, 1.0)
cl = ColorLayer(RGB(0.2, 0.2, 0.2); world_size = (1, 1), ppu = 1,
postprocessing_steps = [clip])
img = write_image(cl)
@test img[1,1] == RGBA(1.0, 0.0, 1.0, 1.0)
end
function filter_tests(ArrayType::Type{AT}) where AT <: AbstractArray
identity = Identity()
cl = ColorLayer(RGB(0.2, 0.2, 0.2); world_size = (4, 4), ppu = 1,
postprocessing_steps = [identity])
img = write_image(cl)
for i = 1:length(img)
@test img[i] == RGBA{Float32}(0.2, 0.2, 0.2, 1.0)
end
end
#------------------------------------------------------------------------------#
# Testsuite
#------------------------------------------------------------------------------#
function postprocess_testsuite(ArrayType::Type{AT}) where AT <: AbstractArray
@testset "Postprocess tests for $(string(ArrayType))s" begin
clip_tests(ArrayType)
filter_tests(ArrayType)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 2112 | #------------------------------------------------------------------------------#
# Test Definitions
#------------------------------------------------------------------------------#
@kernel function random_test_kernel!(a)
tid = @index(Global, Linear)
a[tid] = Fable.simple_rand(tid)
end
function random_test!(a; numthreads = 256)
backend = get_backend(a)
kernel! = random_test_kernel!(backend, numthreads)
kernel!(a, ndrange = length(a))
end
function LCG_tests(ArrayType::Type{AT}) where AT <: AbstractArray
a = ArrayType(zeros(1024,1024))
threshold = 0.00001
random_test!(a)
a ./= typemax(UInt)
avg = sum(a)/length(a)
@test abs(avg-0.5) < threshold
end
function fid_tests()
fnums = Tuple([UInt16(i) for i = 1:7])
rng = typemax(UInt16)
fid = Fable.create_fid(fnums, rng)
@test bitstring(UInt16(fid)) == "0000101100011001"
probs = (1,
1/2, 1/2,
1/3, 1/3, 1/3,
1/4, 1/4, 1/4, 1/4,
1/5, 1/5, 1/5, 1/5, 1/5,
1/6, 1/6, 1/6, 1/6, 1/6, 1/6,
1/7, 1/7, 1/7, 1/7, 1/7, 1/7, 1/7)
fid_2 = Fable.create_fid(probs, fnums, rng)
offset = 0
for i = 1:length(fnums)
choice = Fable.decode_fid(fid, offset, fnums[i])
if i in (1,2,4)
@test choice == i
else
@test choice != i
end
choice_2 = Fable.decode_fid(rng, offset, fnums[i])
@test choice_2 == 2^(ceil(log2(fnums[i])))
choice_3 = Fable.decode_fid(fid_2, offset, fnums[i])
@test choice_3 <= i
offset += ceil(Int, log2(fnums[i]))
end
end
#------------------------------------------------------------------------------#
# Testsuite Definition
#------------------------------------------------------------------------------#
function random_testsuite(ArrayType::Type{AT}) where AT <: AbstractArray
if ArrayType <: Array
@testset "fid tests" begin
fid_tests()
end
end
@testset "LCG tests for $(string(ArrayType))s" begin
LCG_tests(ArrayType)
end
end
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | code | 887 | using Test
using KernelAbstractions
using Fable
using Images
ArrayTypes = [Array]
using CUDA
if has_cuda_gpu()
CUDA.allowscalar(false)
push!(ArrayTypes, CuArray)
end
using AMDGPU
if has_rocm_gpu()
AMDGPU.allowscalar(false)
push!(ArrayTypes, ROCArray)
end
include("histogram_tests.jl")
include("random_tests.jl")
include("chaos_tests.jl")
include("layering_tests.jl")
include("object_tests.jl")
# Example testsuite is flaky, but can be run locally.
#include("example_tests.jl")
function run_tests(ArrayTypes)
for ArrayType in ArrayTypes
histogram_testsuite(ArrayType)
random_testsuite(ArrayType)
layering_testsuite(ArrayType)
chaos_testsuite(ArrayType)
object_testsuite(ArrayType)
# Note: Passes locally, but not when running Pkg.test (#5)
#example_testsuite(ArrayType)
end
end
run_tests(ArrayTypes)
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | docs | 2108 | # Fae.jl
[![Developer Documentation][docs-latest-img]][docs-url]
[docs-url]: https://www.leioslabs.com/Fae.jl/dev/
[docs-latest-img]: https://img.shields.io/badge/docs-dev-blue.svg
The Fractal Animation Engine, Fae.jl, is an open research project with the goal of creating a new, general purpose rendering engine based on [Iterated Function Systems](https://www.algorithm-archive.org/contents/IFS/IFS.html) (IFS).
The principle is simple: an IFS can draw any object with the right set of equations, so if we can find that set of equations, we can render dynamic scenes.
This package uses KernelAbstractions.jl and is built with parallelism and performance in mind.
Here is a quick list of various research directions for the project:
1. **Performance**: Right now, Fae is using a naive chaos game kernel for all visualizations. It would be interesting to explore higher-performance methods for this. In addition, object rendering is currently done layer-by-layer and it would be interesting to be able to render multiple objects with the same IFS. [Relevant issue](https://github.com/leios/Fae.jl/issues/2).
2. **Generalizations**: Right now, all fractals are made by first starting with a set of equations and then drawing those equations, but it would be interesting to explore the other direction. If the kernels are performant enough, we can do multiple IFS iterations and use some form of optimal control to dynamically learn equations from an input image. This would mean we could essentially turn any image into a fractal, similar to fractal compression. [Relevant Issue](https://github.com/leios/Fae.jl/issues/4).
3. **Synergy with other rendering methods**: There are still advantages to using raytracing, raymarching, or rasterization, but performing clear analyses between the methods and using them together to create a general-purpose rendering library would be an interesting direction.
As it stands, the documentation will be a bit sparse until we hit v0.0.1, which should be in a few months, but if you have any questions, comments, or concerns, please create an issue or pull request!
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | docs | 2920 | # The Fractal Animation Engine
Fable is a fractal animation engine that attempts to create a general-purpose rendering engine via Iterated Function Systems (IFSs) and fractals.
The current Fable.jl API is still in active development, but for those wanting to learn about how to use it, there are several [examples available to learn from](https://github.com/leios/Fable.jl/tree/main/examples).
Though Fable.jl focuses on creating general-purpose animations with *fractals*, other rendering modes are either supported or planned to be implemented in the future.
For now, the only available rendering modes are:
* **Hutchinson operators:** These are used to describe Iterated Function Systems and are the primary focus of Fable.jl
* **Colors:** This mode is somewhat trivial and will just create a layer of a specified color
* **Shaders:** This mode leverages the framework used to describe IFSs to color an image with some user-provided equation.
We would like to support rendering via raytracing, raymarching, and rasterization in the future for those who wish to use such features.
If you would like to learn how to use any of the existing rendering modes, please look at [the layering section of our documentation](layering.md).
## What are Iterated Function Systems?
We plan to put more information in the docs, but there is a great article already describing them in the [Algorithm Archive](https://www.algorithm-archive.org/contents/IFS/IFS.html).
For now, please go there for more information.
## General Fable.jl workflow
Fable.jl is generally structured around building a Fractal Executable (`fee`).
In the case you want to use the fractal rendering mode, this `fee` will be a function system, so for a Sierpinski Triangle, it would look like this:
```math
\begin{aligned}
f_1(P,A) &= \frac{P+A}{2} \\
f_2(P,B) &= \frac{P+B}{2} \\
f_3(P,C) &= \frac{P+C}{2}.
\end{aligned}
```
Here, $P$ is some point location and $A$, $B$, and $C$ are all vertices of the triangle.
For Fable.jl, each function is called a Fractal User Method (`fum` or `FractalUserMethod`).
If the user wants to change the variables dynamically, they might create a Fractal Input (`fi` or `FractalInput`).
Finally, each function should have some sort of color (or shader) associated with it.
Combining two `fum`s for both the position and color functions creates a Fractal Operator (`fo` or `FractalOperator`)
So, how do you use Fable.jl?
Well...
* `fee`, the Fractal Executable is the thing you are building
* `fi`, the Fractal Input(s) are the variables needed for your executable
* `fo`, the Fractal Operator is the function you are using in your executable, complete with probability and color or shader information
* `fum`, the Fractal User Method is how users actually create colors and Fractal Operators.
I am intending to write more docs here, but check out the examples for more information on specifically how to use these.
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | docs | 5805 | # Layering
Fable.jl has multiple layer types that can be composed together to create a final image (or frame in a video).
These layers indicate how the user would like to create an object or field.
Right now, the following layers are available:
* `ColorLayer`: This layer is essentially a single color spread across some number of pixels in a rectangle.
* `ShaderLayer`: This layer is a "shader" that uses a `FractalUserMethod` to color every pixel in a rectangle.
* `ImageLayer`: This layer is used to import images generated outside of Fable.jl. Note that remedial resizing functions are available, but these need to be cleaned up in the future.
* `FractalLayer`: This layer is for using Iterated Function Systems and generating objects via fractals.
These layers eventually write to their respective `canvas` objects, which are composed into a final image or frame via:
```
write_image(layer; filename = "check.png")
write_image([layers]; filename = "check.png")
write_video!(video_out, layers)
write_video!(video_out, [layers])
```
As an important note, even though the `canvas` for each layer is essentially an Array (or `CuArray` / `ROCArray`) of `RGBA` values (pixels), the layers, themselves are created with the following arguments:
1. `world_size`: The "world size" is the size of the world the layer covers. For example, if you want to render a unit circle, you might want to make sure the world size is roughly $$2\times 2$$ in size, otherwise, you might clip part of the object!
2. `ppu`: the PPU unit stands for "pixels per unit" and is similar to DPI (Dots Per Inch) used in printing. The idea here is that each unit of your world must have a certain number of pixels in it. Importantly, this allows you to dynamically scale your visualization without changing object position.
3. `position`: This is the position (in the physical units of your world) of the *center* of your layer. This helps with compositing layers at different locations.
To get a better understanding of how these work, here are some quick examples:
## Color Layers
The `ColorLayer` is likely the simplest layer provided by Fable.jl.
To generate a layer that is only a single color, you just need to create the layer and then run the `write_image(...)` function, like so:
```
function layering_example(; ArrayType = Array)
world_size = (9*0.15, 16*0.15)
ppu = 1920/world_size[2]
clayer = ColorLayer(RGB(0.5, 0.5, 0.5); world_size = world_size, ppu = ppu,
ArrayType = ArrayType)
write_image(clayer; filename = "out.png")
end
```
Running this, will provide the following image:

## Shader Layers
Shader Layers are a bit more complicated than Color Layers, but are ultimately user-specified functions spread across an image.
So, let's say the user specified the following `FractalUserMethod`:
```
radial = @fum function radial(y, x; origin = (0,0))
r = sqrt((x-origin[2])*(x-origin[2]) + (y-origin[1])*(y-origin[1]))
red = 1
green = min(1, 1/r)
blue = 1
alpha = min(1, 1/r)
return RGBA{Float32}(red, green, blue, alpha)
end
```
This should essentially create a white circle that fades out and also turns pink as it goes further from the center of the image.
To run this, you can generate a `ShaderLayer` like so:
```
function shader_example(fum; res = (1080,1920), ArrayType = Array,
filename = "out.png")
layer = ShaderLayer(fum; ArrayType = ArrayType, world_size = (9/4, 4),
ppu = 1920/4)
run!(layer)
write_image(layer; filename = filename)
end
shader_example(radial)
```
Which will create the following image (with a black background):

## Image Layers
As mentioned above, image layers are a work-in-progress.
In particular, resizing is a bit finicky and need a little rework.
For now, it works like so:
```
ilayer = ImageLayer(img)
ilayer = ImageLayer(filename)
write_image(ilayer, filename_2)
```
It can also take all the same arguments as other layers (`position`, `ppu`, and `world_size`), but the resizing is done in a very naive way, so if the image looks odd through Fable.jl, it might be best to figure out the exact pixel size you need and to make the image fit those dimensions with another program.
## Fractal Layers and combing layers together
Because Fractal Layers are a bit tricky, there are additional examples in the documentation to describe how they work.
For now, I will show an example of how you might composite two layers together by modifying the example shown for the Color Layer above:
```
function layering_example(num_particles, num_iterations; ArrayType = Array)
world_size = (9*0.15, 16*0.15)
ppu = 1920/world_size[2]
square = define_rectangle(position = [0.0,0.0],
rotation = pi/4,
color = RGBA(1,0,1))
flayer = FractalLayer(; ArrayType = ArrayType, H1 = square,
world_size = world_size, ppu = ppu,
num_particles = num_particles,
num_iterations = num_iterations)
clayer = ColorLayer(RGB(0.5, 0.5, 0.5); world_size = world_size, ppu = ppu,
ArrayType = ArrayType)
layers = [clayer, flayer]
run!(layers)
write_image(layers; filename = "out.png")
end
```
This will provide the following image:

Note that the `clayer` (Color Layer) is written *before* the `flayer` (Fractal Layer).
In general, the first layer acts as the base layer for rendering and acts as your "camera" for viewing all other layers.
This might need a better abstraction in the future, but works for now.
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | docs | 13157 | # Post processing
Once you have generated an image via any of the provided Fractal Executables (such as Colors, Shaders, or Hutchinson operators), you may want to do additional operations before writing to file.
Right now, we support the following operations:
* **Clipping**: This is the process of turning any pixel above a given threshold intensity into another desired color.
* **Filtering**: This is essentially a convolution with a provided filter, for effects like a Gaussian blur.
* **Sobel**: This is a Sobel filter (without directional information). It is useful for edge detection or simple outlines.
* **Outlines**: This takes the Sobel information and turns it into a more distinct outline.
In this discussion, I will also describe how you may write your own post processing option, if you want.
All the examples can be found in `examples/postprocessing.md`.
## General Notes
The `postprocess!(...)` function is called when using `write_image(...)` or `write_video(...)`.
This means that the post processing step happens after the all FractalExecutables have been `run(...)`.
Importantly, all post processing steps act exclusively on the `canvas` for each `AbstractLayer` type.
Each `canvas` is essentially an `Array` (`CuArray` or `ROCArray`) of `RGBA` values that are initialized before post processing occurs.
Each post processing step is performed in the order they are added to the `postprocessing_steps` `Vector` in each `AbstractLayer`.
There is no default post process for `Shader` and `Color` layers, which essentially means that no post process will be performed unless specified by the user.
For `FractalLayer`s, there is always a `CopyToCanvas(...)` post process, which essentially takes the `RGBA` information from the `run(...)` function and turns it into a `canvas` for later post processing steps.
In practice, this is a small discrepancy that users should not need to worry about.
For the following examples, we will be performing post processing on a simple circle created via a FractalExecutable:
```
function quick_circle(num_particles, num_iterations; ArrayType = Array,
filename = "out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType)
run!(fl)
write_image(fl; filename = filename)
end
```
This will create a pink circle that looks like this:

## Clipping
By default, the `Clip` post process will turn any `RGBA` value above a pre-defined `threshold` to another designated color; however, you can change the `clip_op`(clip operator) to use any function instead of `>`.
You may also change how the intensity is calculated by passing in an `intensity_function` argument.
Fable.jl currently supports the following intensity functions:
```
@inline function simple_intensity(c::CT) where CT <: Union{RGB}
return (c.r/3) + (c.g/3) + (c.b/3)
end
```
and
```
@inline function perceptive_intensity(c::CT) where CT <: Union{RGBA}
return c.alpha * ((0.21 * c.r) + (0.72 * c.g) + (0.07 * c.b))
end
```
The latter is meant to more realistically portray to how humans perceive light.
The `Clip` post process can be created like so:
```
clip = Clip(; threshold = 0.5, color = RGBA(0,0,0,1),
intensity_function = simple_intensity, clip_op = >)
```
Note that the key word arguments above are also the defaults for the `Clip` post process.
Here is a quick example:
```
function clip_example(num_particles, num_iterations; ArrayType = Array,
filename = "clip_out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
clip = Clip(; threshold = 0.5, color = RGBA(1, 1, 0, 1))
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [clip])
run!(fl)
write_image(fl; filename = filename)
end
```
This will turn our pink ball yellow:

## Filtering
The `Filter` post process essentially performs a convolution with a provided filter.
Convolutions are somewhat complicated to understand, but if you want to learn more, please check out the chapter(s) available on the [Algorithm Archive](https://www.algorithm-archive.org/contents/convolutions/convolutions.html).
All the necessary information for understanding how this post process works can be found there, along with an example using the `Sobel` operator.
By default, Fable.jl provides the following filters:
**Identity**: This is a test filter and just returns the exact image back
```
function Identity(; filter_size = 3, ArrayType = Array)
if iseven(filter_size)
filter_size = filter_size - 1
@warn("filter sizes must be odd! New filter size is " *
string(filter_size)*"!")
end
filter = zeros(filter_size, filter_size)
idx = ceil(Int, filter_size*0.5)
filter[idx, idx] = 1
return Filter(filter!, ArrayType(filter), nothing, false)
end
```
**Gaussian** / **Blur**: these perform a Gaussian blur of the image.
```
function gaussian(x,y, sigma)
return (1/(2*pi*sigma*sigma))*exp(-((x*x + y*y)/(2*sigma*sigma)))
end
function Blur(; filter_size = 3, ArrayType = Array, sigma = 1.0)
return Gaussian(; filter_size = filter_size, ArrayType = ArrayType,
sigma = sigma)
end
function Gaussian(; filter_size = 3, ArrayType = Array, sigma = 1.0)
if iseven(filter_size)
filter_size = filter_size - 1
@warn("filter sizes must be odd! New filter size is " *
string(filter_size)*"!")
end
if filter_size > 1
filter = zeros(filter_size, filter_size)
for i = 1:filter_size
y = -1 + 2*(i-1)/(filter_size-1)
for j = 1:filter_size
x = -1 + 2*(j-1)/(filter_size-1)
filter[i,j] = gaussian(x, y, sigma)
end
end
else
filter = [1.0]
end
filter ./= sum(filter)
return Filter(filter!, ArrayType(filter), nothing, false)
end
```
The `Sobel` post process also uses a `Filter`, but it will be discussed separately in the next section.
The only important note here is that because users are creating kernels themselves, it is possible to accidentally create a kernel of a different `ArrayType` than the layer's `canvas`.
In this case, the kernel will change the array type of the filter and provide the following warning:
```
Info: filter array type not the same as canvas!
Converting filter to canvas type...
```
Finally, here is a quick example using the Gaussian `Blur` post process (note you can also use the same post process by calling `Gaussian` instead in the same way):
```
function blur_example(num_particles, num_iterations; ArrayType = Array,
filter_size = 3, filename = "blur_out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
blur = Blur(; filter_size = filter_size)
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [blur])
run!(fl)
write_image(fl; filename = filename)
end
```
This will produce the following image when using a $$100\times 100$$ filter:

## Sobel operator
The Sobel operator is often called an "image derivative."
More information can be found on the [Algorithm Archive](https://www.algorithm-archive.org/contents/convolutions/2d/2d.html).
In general, this operation can be split into 3 steps:
1. A gradient in the $$x$$ direction ($$G_x$$)
2. A gradient in the $$y$$ direction ($$G_y$$)
3. A sum of both gradients: $$\sqrt{G_x^2 + G_y^2}$$
As an important note, many implementations of the Sobel operator also return gradient direction information.
This part of the operation is not performed in Fable.jl by default.
Here is a quick example using the Sobel operator:
```
function sobel_example(num_particles, num_iterations; ArrayType = Array,
filename = "sobel_out.png")
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
sobel = Sobel()
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [sobel])
run!(fl)
write_image(fl; filename = filename)
end
```
This will produce the following image:

## Outlines
Outlines are surprisingly tricky to get right.
I will not argue that the `Outline` implementation in Fable.jl is perfect, but it works well enough for now.
The current implementation was inspired by Canny edge detection and does the following:
1. Blurs the given image by some factor related to the user-provided `linewidth` variable.
2. Performs a Sobel operation on the image to get the image derivative.
3. Performs naive ridge detection, which sets any value in the Sobel-operated canvas above a certain threshold to be the provided outline `color`. This is essentially a `Clip` post process from above.
There are a bunch of key word arguments you can use for `Outline`:
```
outline = Outline(; linewidth = 1,
color = RGBA(1.0, 1.0, 1.0, 1.0),
intensity_function = simple_intensity,
object_outline = false,
threshold = 1/(linewidth*linewidth+1),
sigma = 1)
```
Here, `linewidth` is the desired line width of the outline, `color` is the desired color, `intensity_function` is the intensity function as described in the `Clip` subsection above, `threshold` is used for ridge detection, and `sigma` defines the width of the Gaussian for the blur kernel.
The only tricky argument is `object_outline`, which is specifically for FractalLayers.
It indicates that the user wants to outline the fractal object, itself, not any inner components from potentially using a `FractalUserMethod` for coloring the fractal object.
Here is a quick example using the Outline post process:
```
function outline_example(num_particles, num_iterations; ArrayType = Array,
filename = "outline_out.png", linewidth = 1,
object_outline = false)
circle = define_circle(; radius = 0.1, color = [1, 0, 1, 1])
outline = Outline(; linewidth = linewidth, object_outline = object_outline)
fl = FractalLayer(; H1 = circle, ArrayType = ArrayType,
postprocessing_steps = [outline])
run!(fl)
write_image(fl; filename = filename)
end
```
This will produce the following image:

## Building your own
Finally, we will touch on what is necessary to build a post process from scratch.
Right now, this can be done by creating a new `AbstractPostProcess` struct, similar to those used in the above examples.
Here is the `Clip` post processing struct for reference:
```
struct Clip <: AbstractPostProcess
op::Function
clip_op::Function
intensity_function::Function
threshold::Number
color::CT where CT <: Union{RGB, RGBA}
initialized::Bool
end
```
To be honest, this part of the code is a little sticky right now, so feel free to try to clean it up in a PR, but the minimal `AbstractPostProcess` struct would look like this:
```
struct Minimal <: AbstractPostProcess
op::Function
initialized::Bool
end
```
Here, `op` is the provided function the `AbstractPostProcess` should use, while `initialized` is a boolean value indicating whether the post process needs initialization.
This is useful for post processes that require additional `canvas` parameters, like the `Filter` post process:
```
mutable struct Filter <: AbstractPostProcess
op::Function
filter::AT where AT <: Union{Array, CuArray, ROCArray}
canvas::AT where AT <: Union{Array, CuArray, ROCArray, Nothing}
initialized::Bool
end
```
If `initialized` is set to `false`, the `initialize!(...)` function will be called when using the post process for the first time.
Here is the `initialize!(...)` function for `Filter`:
```
function initialize!(filter::Filter, layer::AL) where AL <: AbstractLayer
ArrayType = layer.params.ArrayType
if !(typeof(filter.filter) <: layer.params.ArrayType)
@info("filter array type not the same as canvas!\nConverting filter to canvas type...")
filter.filter = ArrayType(filter.filter)
end
filter.canvas = ArrayType(zeros(eltype(layer.canvas), size(layer.canvas)))
end
```
Note that all `initialize!` functions should have the args `(filter::Filter, layer::AL)`.
In practice, these functions are usually used to make sure that the post process canvas has the same `ArrayType` and size as the layer.
As a final note: when designing an `op` function to be used for each post process, remember that the `ArrayType` could be a `CuArray` or `ROCArray`, so try to make the functions GPU friendly.
This is why many of the post processes are written in KernelAbstractions.
Again, this part of the code is sticky, so if you need to add another post process, feel free to create an issue and we can talk about whether it makes sense to add directly to Fable.jl!
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | docs | 1597 | # Research Directions
Fable.jl is an open research project with the goal of creating a new, general purpose rendering engine based on [Iterated Function Systems](https://www.algorithm-archive.org/contents/IFS/IFS.html) (IFS).
Here is a quick list of various research directions for the project:
## Performance
Right now, Fable is using a naive chaos game kernel for all visualizations.
It would be interesting to explore higher-performance methods for this.
In addition, object rendering is currently done layer-by-layer and it would be interesting to be able to render multiple objects with the same IFS.
[Relevant issue](https://github.com/leios/Fable.jl/issues/2).
## Generalizations
Right now, all fractals are made by first starting with a set of equations and then drawing those equations, but it would be interesting to explore the other direction.
If the kernels are performant enough, we can do multiple IFS iterations and use some form of optimal control to dynamically learn equations from an input image.
This would mean we could essentially turn any image into a fractal, similar to fractal compression.
[Relevant Issue](https://github.com/leios/Fable.jl/issues/4).
## Synergy with other rendering methods
There are still advantages to using raytracing, raymarching, or rasterization, but performing clear analyses between the methods and using them together to create a general-purpose rendering library would be an interesting direction.
If you are at all interested in helping with this project, please start discussions on the relevant issues or otherwise create a new one!
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | docs | 1113 | # Time Interaface
To be honest, the time interface for Fable.jl is under construction and not *quite* ready for general use; however, as an *animation* engine, it does allow users to use some form of "time" component for each `FractalUserMethod`.
The most important thing to note is that **Fable.jl fundamentally animates per frame, not based on real time!** This simply means that the variable sent to each `FractalUserMethod` is not `time`, but the current `frame`.
## How to use the Fable.jl time interface
Right now, simply create a `FractalUserMethod` that uses the `frame` variable, and then pass some time argument along to your `run!(...)` function as a keyword argument:
```
run!(layer; time = t)
```
Here `t` could be a `Float` that represents the number of seconds, an `Int` that represents the current frame, or a Unitful quantity (like `1u"s") which represents some other unit of time.
I'll be adding more to these docs as the time interface becomes more stable, but for now, please feel free to let me know what you think on the [relevant issue](https://github.com/leios/Fable.jl/issues/53)!
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | docs | 9569 | # A Simple Smear
Animations are made by stitching together a series of images to give the illusion of motion.
When creating an animation, we can choose the number of images we show to our viewers every second.
Cinematic movies are typically shown at 24 frames per second (fps).
Video games do not usually have a set fps value, but most people usually prefer 60 or higher.
Youtube videos can be set to whatever you want, but I typically prefer either 30 or 60 depending on the situation.
Now here's a weird quirk of the human brain.
Old-school animations are usually 24 fps, but seem incredibly smooth.
If you play a video game at 24 fps, it can sometimes be nauseating.
Why?
Well, there is no hard answer to this, but video game engines are tasked at showing sometimes thousands of objects to you in real time.
This is a really demanding process for your graphics card, so engines will do whatever they can to render things as quickly as possible while still being correct.
Even worse for the game engine, it does not always know it's next frame because it has to take the actions of the player into account.
This is starkly contrasting the animation industry where it might take days to draw even a single frame.
Because the entire movie has been drawn on a storyboard before-hand, the artists know what to draw and how to guide the viewer to the next important scene.
After months of hard work, all the animators come together and coalesce their art into the final video.
So let's compare and contrast the difference between these two approaches.
If a game engine is given 3 frames to move a circle from the upper left to lower right of the screen, it will render the circle at the start and end location along with the intermediary frames, like so:
| Frame 1 | Intermediate Frame | Final Frame |
| ------- | ------------------ | ----------- |
|  |  |  |
Animators will do things a little differently.
The start and end will look the same, but the intermediary frame will be squashed to show the direction of motion:
| Frame 1 | Intermediate Frame | Final Frame |
| ------- | ------------------ | ----------- |
|  |  |  |
The intermediary frame is called a smear frame and this technique is used almost everywhere in modern animation.
If you have ever seen a really smooth animation, it's probably because there were really good smears between different character positions.
Smear frames are also why characters might look a little weird when you pause an animated video at the wrong place.
Simply put: if an animation lacks smear frames, it might start to look like a low fps video game.
We want to avoid that as best as we can!
So, let's get to it!
## Example
To start, I will create a function that use the `num_particles`, and `num_iterations` for the naive chaos game kernel.
Note in this case, I am also using `ArrayType` for the Array Type (`Array` for CPU or `CuArray` for GPU), and `num_frames` for the total number of frames.
Finally, I will create an `output_type` variable that can be either `:video`, or `:image` to output to video (`out.mp4`) or images (`check*.png`):
```
using Fable, CUDA, AMDGPU
function main(num_particles, num_iterations, total_frames; ArrayType = Array,
output_type = :video)
```
Now I will define the image and video parameters:
```
# define image domain
world_size = (9, 16)
ppu = 1920 / 16
res = (1080, 1920)
layer = FractalLayer(; ArrayType = ArrayType,
world_size = world_size, ppu = ppu,
num_particles = num_particles,
num_iterations = num_iterations)
# defining video parameters
if output_type == :video
video_out = open_video(res; framerate = 30, filename = "out.mp4",
encoder_options = (crf=23, preset="medium"))
end
```
Note that the video will stitch together a series of frames, so we still need the pixels from `layer` hanging around.
Now we define the ball:
```
# define ball parameters
position = [-2.0, -2.0]
ball = define_circle(; position = position,
radius = 1.0,
color = (1,1,1))
```
And now we start getting ready for the smear frame transformation:
```
# fractal inputs to track changes in position, scale, and theta for smear
object_position = fi("object_position", position)
scale = fi("scale", (1,1))
theta = fi("theta", 0)
# first defining the fractal user method
smear = Smears.stretch_and_rotate(object_position = object_position,
scale = scale, theta = theta)
# now turning it into a fractal operator
smear_transform = fee(Hutchinson, FractalOperator(smear))
```
For this, we are creating fractal inputs (`object_position`, `scale`, and `theta`) for the `stretch_and_rotate` fractal user method. We then turn this into a fractal operator.
Note that fractal inputs are good for when you need to update the value of certain parameters on the fly.
For clarity, here is the `stretch_and_rotate` fractal user method:
```
stretch_and_rotate = @fum function stretch_and_rotate(
x,y;
object_position = (0,0),
scale = (1,1),
theta = 0)
y = (y - object_position[1])*scale[1]
x = (x - object_position[2])*scale[2]
temp_x = x*cos(theta) - y*sin(theta)
temp_y = x*sin(theta) + y*cos(theta)
x = temp_x + object_position[2]
y = temp_y + object_position[1]
return (y,x)
end
```
After this, we need to attach the newly generated operators to the `FractalLayer`:
```
# attaching each operator to the layer
layer.H1 = ball
layer.H2 = smear_transform
```
Finally, we have the animation loop:
```
for i = 1:total_frames
# changing ball position
radius = 1.0
pos = [-2.0+4*(i-1)/(total_frames-1),
-2.0+4*(i-1)/(total_frames-1)]
# creating a value that grows as it gets closer to total_frames / 2
# and shrinks as it gets closer to total_frames
scale_x = 2 - abs((i-1)*2-(total_frames-1))/(total_frames-1)
# modifying fractal inputs for smear
set!(object_position, pos)
set!(scale, (1,scale_x))
set!(theta, pi/4)
run!(layer)
if output_type == :video
write_video!(video_out, [layer])
elseif output_type == :image
filename = "check"*lpad(i,5,"0")*".png"
write_image([layer], filename)
end
# clearing frame
zero!(layer)
end
```
This does 4 things:
1. It updates the circle at every step.
2. It re`set`s the `object_position`, `scale`, and `theta` for the `smear_trasnform`.
3. It outputs to either video or image.
4. It sets the canvas values back to 0 for the next frame
Once this is done, all we need to do is close the video (if we were outputting to video at all:
```
if (output_type == :video)
close_video(video_out)
end
```
If we run `main(10000, 10000, 10, CuArray; output_tupe = :video)`, we will get the following video:

## Just the code
And here is the full code:
```
function smear_example(num_particles, num_iterations, total_frames;
ArrayType = Array, output_type = :video)
FloatType = Float32
# define image domain
world_size = (9, 16)
ppu = 1920 / 16
res = (1080, 1920)
layer = FractalLayer(; ArrayType = ArrayType, FloatType = FloatType,
world_size = world_size, ppu = ppu,
num_particles = num_particles,
num_iterations = num_iterations)
# defining video parameters
if output_type == :video
video_out = open_video(res; framerate = 30, filename = "out.mp4")
end
# define ball parameters
object_position = fi("object_position", [-2.0, -2.0])
ball = define_circle(; position = object_position,
radius = 1.0,
color = (1,1,1))
# fractal inputs to track changes in position, scale, and theta for smear
scale = fi("scale", (1,1))
theta = fi("theta", 0)
# first defining the fractal user method
smear = Smears.stretch_and_rotate(object_position = object_position,
scale = scale, theta = theta)
# now turning it into a fractal operator
smear_transform = fee(Hutchinson, fo(smear))
layer.H1 = ball
layer.H2 = smear_transform
for i = 1:total_frames
# changing ball position
radius = 1.0
pos = [-2.0+4*(i-1)/(total_frames-1),
-2.0+4*(i-1)/(total_frames-1)]
# creating a value that grows as it gets closer to total_frames / 2
# and shrinks as it gets closer to total_frames
scale_x = 2 - abs((i-1)*2-(total_frames-1))/(total_frames-1)
# modifying fractal inputs for smear
set!(object_position, pos)
set!(scale, (1,scale_x))
set!(theta, pi/4)
run!(layer)
if output_type == :video
write_video!(video_out, [layer])
elseif output_type == :image
filename = "check"*lpad(i,5,"0")*".png"
write_image([layer]; filename=filename)
end
# clearing frame
zero!(layer)
end
if (output_type == :video)
close_video(video_out)
end
end
```
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 0.0.2 | 65301af3ab06b04cf8a52cd43b06222bab5249c2 | docs | 6551 | # A Swirled Square
This is a quick example to show how to use Fable.jl
## Step 1: create a square
First, we should create a square.
To do this, we need to set up Fable with the right parameters:
```
# Physical space location.
world_size = (9*0.15, 16*0.15)
# Pixels per unit space
# The aspect ratio is 16x9, so if we want 1920x1080, we can say we want...
ppu = 1920/world_size[2]
```
Right now, this part of the API is in flux, but we need some sort of physical world to hold the objects in, so we set this to be some size (`world_size = (9*0.15, 16*0.15)`).
We also define the *Pixels Per Unit* or `ppu` value.
The resolution should be the `world_size * ppu`, so if we want a 1920x1080 image, we need to set the ppu accordingly (here we set it as `1920/world_size[2]`).
This will be replaced with a camera struct eventually.
Now we need to define a color.
This can be done by passing in an array or tuple (such as `color = [1.0, 0, 0, 1]` for red), or as an array of arrays or tuples, like:
```
colors = [[1.0, 0.25, 0.25,1],
[0.25, 1.0, 0.25, 1],
[0.25, 0.25, 1.0, 1],
[1.0, 0.25, 1.0, 1]]
```
In this case, each row of the array will define the color of a different quadrant of the square.
Now we can define our fractal executable...
```
H = define_square(; position = [0.0, 0.0], rotation = pi/4, color = colors)
```
Here, `ArrayType` can be either an `Array` or `CuArray` depending whether you would like to run the code on the CPU or (CUDA / AMD) GPU.
`num_particles` and `num_iterations` are the number of points we are solving with for the chaos game and the number of iterations for each point.
The higher these numbers are, the better resolved our final image will be.
Notationally, we are using the variable `H` to designate a Hutchinson operator, which is the mathematical name for a function set.
Finally, we need to attach this function to the layer and run everything with the `run!(...)` function and write it to an image:
```
layer = FractalLayer(; ArrayType = ArrayType, logscale = false,
world_size = world_size, ppu = ppu, H1 = H,
num_particles = num_particles,
num_iterations = num_iterations)
run!(layer)
write_image(layer; filename = "out.png")
```
Note that the `H1 = H` keyword argument is the one actually defining `H` as the first Hutchinson operator for the `FractalLayer`.
After running this, we will get the following image:

The full code can be found at the bottom of this page
## Step 2: swirl the square
Next, we will try to "swirl the square" by also adding another fractal executable to the mix, the swirl operator (defined already in Fable.jl):
```
swirl = @fum function swirl(x, y)
r = sqrt(y*y + x*x)
v1 = x*cos(r*r) + y*sin(r*r)
v2 = x*sin(r*r) - y*cos(r*r)
y = v1
x = v2
return point(y,x)
end
```
Here, we are using the `@fum` syntax to show how users might define their own operators.
The same can be done for colors.
The code here does not change significantly, except that we create a `H2` and add it to the `fractal_flame(...)` function:
```
...
H2 = Hutchinson(swirl_operator)
layer = FractalLayer(res; ArrayType = ArrayType, logscale = false,
FloatType = FloatType, H1 = H, H2 = H2,
num_particles = num_particles,
num_iterations = num_iterations)
run!(layer)
...
```
There are a few nuances to point out:
1. We are using `Shaders.previous`, which simply means that the swirl will use whatever colors were specified in `H1`.
2. Fractal operators can be called with `fee` or `Hutchinson` and require `Array` or `Tuple` inputs.
3. `final = true`, means that this is a post processing operation. In other words, `H1` creates the object primitive (square), and `H2` always operates on that square.
4. We are specifying the Floating Type, `FloatType`, as `Float32`, but that is not necessary.
Once this is run, it should provide the following image:

## Step 3: a different kind of swirl
Now some people might be scratching their heads at the previous result.
If we are solving with both `H1` and `H2`, why does it look like two separate actions instead of one combined one?
In other words, why is the swirl so clearly different than the square operation?
This is because we operate on two separate sets of points.
`H1` creates object primitives. Every step of the simulation, we will read from the points after `H1` operates on them.
`H2` works on a completely different location in memory specifically for image output.
If we want, we can make `H2` operate on the object, itself, by creating a new fractal executable:
```
final_H = fee(Hutchinson, [H, H2])
layer = FractalLayer(res; ArrayType = ArrayType, logscale = false,
FloatType = FloatType, H1 = final_H
num_particles = num_particles,
num_iterations = num_iterations)
run!(layer)
```
which will create the following image:

## The full example
```
function square_example(num_particles, num_iterations;
ArrayType = Array,
dark = true,
transform_type = :standard,
filename = "out.png")
# Physical space location.
world_size = (9*0.15, 16*0.15)
# Pixels per unit space
# The aspect ratio is 16x9, so if we want 1920x1080, we can say we want...
ppu = 1920/world_size[2]
colors = [[1.0, 0.25, 0.25,1],
[0.25, 1.0, 0.25, 1],
[0.25, 0.25, 1.0, 1],
[1.0, 0.25, 1.0, 1]]
H = define_square(; position = [0.0, 0.0], rotation = pi/4, color = colors)
swirl_operator = fo(Flames.swirl)
H2 = nothing
if transform_type == :outer_swirl
H2 = Hutchinson(swirl_operator)
elseif transform_type == :inner_swirl
H = fee(Hutchinson, [H, Hutchinson(swirl_operator)])
end
layer = FractalLayer(; ArrayType = ArrayType, logscale = false,
world_size = world_size, ppu = ppu,
H1 = H, H2 = H2,
num_particles = num_particles,
num_iterations = num_iterations)
run!(layer)
write_image(layer; filename = filename)
end
```
| Fable | https://github.com/leios/Fable.jl.git |
|
[
"MIT"
] | 1.1.0 | 3e0a96753f53eab0d15ad837ef1a3742389c928b | code | 3688 | module GeniePackageManager
using Genie
using Genie.Renderer.Json
using Genie.HTTPUtils.HTTP
using Pkg
using Base64
const PKGLISTURL = "https://raw.githubusercontent.com/JuliaRegistries/General/master/Registry.toml"
const defaultroute = "/geniepackagemanager"
const viewpath = abspath(joinpath(@__DIR__, "..", "views", "index.html"))
function register_routes(defaultroute = defaultroute)
route("$defaultroute") do
serve_file(viewpath)
end
route("$defaultroute/list", list_packages)
# REST ENDPOINTS
route("$defaultroute/:package::String/add", add, method = POST)
route("$defaultroute/:package::String/:version::String/add", add_with_version, method = POST)
route("$defaultroute/:package::String/dev", dev, method = POST)
route("$defaultroute/:package::String/remove", remove_package, method = POST)
route("$defaultroute/:package::String/update", update_package, method = POST)
route("$defaultroute/updateall", update_all_packages)
route("$defaultroute/addurl", add_with_url)
route("$defaultroute/addurldev", add_with_url_dev)
Genie.Configuration.isdev() && route("$defaultroute/exit", () -> exit(0))
nothing
end
function list_packages()
deps = Pkg.dependencies()
installs = Dict{String, Vector{Any}}()
for (uuid, dep) in deps
dep.is_direct_dep || continue
moddevdir = false
if haskey(ENV, "JULIA_PKG_DEVDIR")
moddevdir = true
end
if dep.version === nothing
installs[dep.name] = ["", ""]
elseif moddevdir && occursin(ENV["JULIA_PKG_DEVDIR"], dep.source)
installs[dep.name] = [dep.version, "dev"]
elseif !moddevdir && !isempty(findall(x -> x == "dev", splitpath(dep.source)))
installs[dep.name] = [dep.version, "dev"]
else
installs[dep.name] = [dep.version, ""]
end
end
return installs |> json
end
function add()
try
package = params(:package)
Pkg.add(package)
return Dict(:status => "ok", :message => "Package $package added") |> json
catch e
return Dict("error" => e) |> json
end
end
function dev()
try
package = params(:package)
Pkg.develop(package)
return Dict(:status => "ok", :message => "Package $package added") |> json
catch e
return Dict("error" => e) |> json
end
end
function add_with_version()
try
package = params(:package)
version = params(:version)
Pkg.add(name=package, version=version)
return Dict(:status => "ok", :message => "Package $package@$version added") |> json
catch e
return Dict("error" => e) |> json
end
end
function add_with_url()
try
giturl = String(base64decode(params(:url)))
Pkg.add(url=giturl)
return Dict(:status => "ok", :message => "Package $giturl added") |> json
catch e
return Dict("error" => e) |> json
end
end
function add_with_url_dev()
try
giturl = String(base64decode(params(:url)))
Pkg.develop(url=giturl)
return Dict(:status => "ok", :message => "Package $giturl added") |> json
catch e
return Dict("error" => e) |> json
end
end
function remove_package()
try
package = params(:package)
Pkg.rm(package)
return Dict(:status => "ok", :message => "Package $package removed") |> json
catch e
return Dict("error" => e) |> json
end
end
function update_package()
try
package = params(:package)
Pkg.update(package)
return Dict(:status => "ok", :message => "Package $package updated") |> json
catch e
return Dict("error" => e) |> json
end
end
function update_all_packages()
try
Pkg.update()
return Dict(:status => "ok", :message => "All packages updated") |> json
catch e
return Dict("error" => e) |> json
end
end
end # module GeniePackageManager
| GeniePackageManager | https://github.com/GenieFramework/GeniePackageManager.jl.git |
|
[
"MIT"
] | 1.1.0 | 3e0a96753f53eab0d15ad837ef1a3742389c928b | code | 110 | using GeniePackageManager
using Test
@testset "GeniePackageManager.jl" begin
# Write your tests here.
end | GeniePackageManager | https://github.com/GenieFramework/GeniePackageManager.jl.git |
|
[
"MIT"
] | 1.1.0 | 3e0a96753f53eab0d15ad837ef1a3742389c928b | docs | 94 | # GeniePackageManager 🧞📦 🧞♀️📦
Package Management solution for Genie.jl and GenieBuilder Apps | GeniePackageManager | https://github.com/GenieFramework/GeniePackageManager.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 743 | using Cowsay
using Documenter
DocMeta.setdocmeta!(Cowsay, :DocTestSetup, :(using Cowsay); recursive=true)
makedocs(;
modules=[Cowsay],
authors="Thomas A. Christensen II <[email protected]> and contributors",
repo="https://github.com/MillironX/cowsay.jl/blob/{commit}{path}#{line}",
sitename="cowsay.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://millironx.com/Cowsay.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
"Available Cowfiles" => "cows.md",
"Make your own Cowfile" => "cowfiles.md",
],
)
deploydocs(;
repo="github.com/MillironX/Cowsay.jl",
devbranch="master",
)
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 9190 | module Cowsay
using TextWrap
export cowsay
export cowthink
export cowsaid
export cowthunk
include("cows/blowfish.cow.jl")
include("cows/bunny.cow.jl")
include("cows/cower.cow.jl")
include("cows/default.cow.jl")
include("cows/dragon-and-cow.cow.jl")
include("cows/dragon.cow.jl")
include("cows/elephant-in-snake.cow.jl")
include("cows/elephant.cow.jl")
include("cows/eyes.cow.jl")
include("cows/flaming-sheep.cow.jl")
include("cows/fox.cow.jl")
include("cows/kitty.cow.jl")
include("cows/koala.cow.jl")
include("cows/mech-and-cow.cow.jl")
include("cows/meow.cow.jl")
include("cows/moofasa.cow.jl")
include("cows/moose.cow.jl")
include("cows/mutilated.cow.jl")
include("cows/sheep.cow.jl")
include("cows/skeleton.cow.jl")
include("cows/small.cow.jl")
include("cows/stegosaurus.cow.jl")
include("cows/supermilker.cow.jl")
include("cows/surgery.cow.jl")
include("cows/three-eyes.cow.jl")
include("cows/turkey.cow.jl")
include("cows/turtle.cow.jl")
include("cows/tux.cow.jl")
include("cows/udder.cow.jl")
include("cows/vader-koala.cow.jl")
include("cows/vader.cow.jl")
include("cows/www.cow.jl")
"""
cowsay([io,] message::AbstractString; kwargs...)
cowthink([io,] message::AbstractString; kwargs...)
Print an ASCII picture of a cow saying/thinking `message`
# Arguments
- `message::AbstractString`: Tell the cow what to say
# Keywords
- `cow=default`: Specify a particular function handle to print the ASCII art. See below for
more details on what constitutes a valid function handle.
- `eyes::AbstractString="oo"`: A two-character string to be drawn in for the eyes. Not all
cowfiles support this, though.
- `tongue::AbstractString=" "`: A two-character string to be drawn in for the tongue. Not
all cowfiles support this.
- `wrap::Int=40`: The number of characters at which to wrap `message` to a new line
- `nowrap::Bool=false`: Don't perform text wrapping on `message`
## Cow appearance Keywords
- `borg::Bool=false`: Initiates Borg mode
- `dead::Bool=false`: Causes the cow to appear dead
- `greedy::Bool=false`: Invokes greedy mode
- `paranoid::Bool=false`: Causes a state of paranoia to come over the cow
- `stoned::Bool=false`: Makes the cow appear thoroughly stoned
- `tired::Bool=false`: Yields a tired cow
- `wired::Bool=false`: Somewhat the opposite of `tired`, and initiates wired mode
- `young::Bool=false`: Brings on the cow's youthful appearance
# Example
```jldoctest
julia> cowsay("Have you mooed today?")
_______________________
< Have you mooed today? >
-----------------------
\\ ^__^
\\ (oo)\\_______
(__)\\ )\\/\\
||----w |
|| ||
julia> cowthink("Have I mooed today?")
_____________________
( Have I mooed today? )
---------------------
o ^__^
o (oo)\\_______
(__)\\ )\\/\\
||----w |
|| ||
```
"""
function cowsay(message::AbstractString; kwargs...)
cowsay(stdout, message; kwargs...)
end
function cowsay(io::IO, message::AbstractString; kwargs...)
println(io, cowsaid(message; kwargs...))
end
"""
cowthink([io,] message::AbstractString; kwargs...)
Print an ASCII picture of a cow thinking `message`
See [`cowsay`](@ref)
"""
function cowthink(message::AbstractString; kwargs...)
cowthink(stdout, message; kwargs...)
end
function cowthink(io::IO, message::AbstractString; kwargs...)
println(io, cowthunk(message; kwargs...))
end
"""
cowsaid(message::AbstractString; kwargs...)
cowthunk(message::AbstractString; kwargs...)
Constructs cow art and returns it as a string instead of printing it. See [`cowsay`](@ref)
for implementation details.
# Example
```jldoctest
julia> cowsaid("Have you mooed today?")
" _______________________\\n< Have you mooed today? >\\n -----------------------\\n \\\\ ^__^\\n \\\\ (oo)\\\\_______\\n (__)\\\\ )\\\\/\\\\\\n ||----w |\\n || ||\\n"
```
```jldoctest
julia> cowthunk("Have I mooed today?")
" _____________________\\n( Have I mooed today? )\\n ---------------------\\n o ^__^\\n o (oo)\\\\_______\\n (__)\\\\ )\\\\/\\\\\\n ||----w |\\n || ||\\n"
```
"""
function cowsaid(message::AbstractString; kwargs...)
return cowmoo(message, :say; kwargs...)
end
"""
cowthunk(message::AbstractString; kwargs...)
Construct art of a cow thinking `message`.
See [`cowsaid`](@ref) and [`cowsay`](@ref)
"""
function cowthunk(message::AbstractString; kwargs...)
return cowmoo(message, :think; kwargs...)
end
"""
cowmoo(message::AbstractString, mode, kwargs...)
Converts `message` into either saying or thinking art based on the value of `mode`. All of
the default values for `kwargs` for pretty much every other function live here. See
[`cowsay`](@ref) for their descriptions.
"""
function cowmoo(message::AbstractString, mode; kwargs...)
cow = dict_or_default(kwargs, :cow, Cowsay.default)
eyes = dict_or_default(kwargs, :eyes, "oo")
tongue = dict_or_default(kwargs, :tongue, " ")
wrap = dict_or_default(kwargs, :wrap, 40)
nowrap = dict_or_default(kwargs, :nowrap, false)
eyes, tongue = construct_face!(eyes, tongue; kwargs...)
# Default to 'say' mode
if mode == :think
balloon = thinkballoon
thoughts = "o"
else
balloon = sayballoon
thoughts = "\\"
end
wrapped_message = !nowrap ? TextWrap.wrap(message, width=wrap, replace_whitespace=false) : message
speechbubble = balloon(wrapped_message)
return string(speechbubble, cow(eyes=eyes, tongue=tongue, thoughts=thoughts))
end
function construct_face!(eyes, tongue; kwargs...)
borg = dict_or_default(kwargs, :borg, false)
dead = dict_or_default(kwargs, :dead, false)
greedy = dict_or_default(kwargs, :greedy, false)
paranoid = dict_or_default(kwargs, :paranoid, false)
stoned = dict_or_default(kwargs, :stoned, false)
tired = dict_or_default(kwargs, :tired, false)
wired = dict_or_default(kwargs, :wired, false)
young = dict_or_default(kwargs, :young, false)
if borg
eyes = "=="
end
if dead
eyes = "xx"
tongue = "U "
end
if greedy
eyes = "\$\$"
end
if paranoid
eyes = "@@"
end
if stoned
eyes = "**"
tongue = "U "
end
if tired
eyes = "--"
end
if wired
eyes = "OO"
end
if young
eyes = ".."
end
return eyes, tongue
end
"""
dict_or_default(dict, key, value)
If `key` is present in `dict`, then return `dict[key]`, otherwise return `value`
# Example
```jldoctest
julia> dict = Dict(:holstein => "lotsa milk", :jersey => "butterfat", :shorthorn => "worthless");
julia> Cowsay.dict_or_default(dict, :holstein, "fluid")
"lotsa milk"
julia> Cowsay.dict_or_default(dict, :brown_swiss, "cheese")
"cheese"
```
"""
function dict_or_default(dict, key, value)
if haskey(dict, key)
return dict[key]
else
return value
end
end
"""
function sayballoon(message::AbstractString)
Creates the balloon portion of the art for [`cowsay`](@ref)
See also [`cowsay`](@ref), [`thinkballoon`](@ref)
"""
function sayballoon(message::AbstractString)
messagelines = split(message, "\n")
nlines = length(messagelines)
linelength = max(length.(messagelines)...)
paddinglength = linelength + 2
if nlines == 1
balloon = string(
" ",
repeat("_", paddinglength),
"\n< ",
message,
" >\n ",
repeat("-", paddinglength),
"\n"
)
else
balloon = string(
" ",
repeat("_", paddinglength),
"\n/ ",
rpad(messagelines[1], linelength),
" \\\n"
)
if nlines > 2
for i = 2:nlines-1
balloon = string(
balloon,
"| ",
rpad(messagelines[i], linelength),
" |\n"
)
end
end
balloon = string(
balloon,
"\\ ",
rpad(messagelines[end], linelength),
" /\n ",
repeat("-", paddinglength),
"\n"
)
end
return balloon
end #function
"""
function thinkballoon(message::AbstractString)
Creates the balloon portion of the art for [`cowthink`](@ref)
See also [`cowthink`](@ref), [`sayballoon`](@ref)
"""
function thinkballoon(message::AbstractString)
messagelines = split(message, "\n")
nlines = length(messagelines)
linelength = max(length.(messagelines)...)
paddinglength = linelength + 2
balloon = string(
" ",
repeat("_", paddinglength),
"\n"
)
for i in 1:nlines
balloon = string(
balloon,
"( ",
rpad(messagelines[i], linelength),
" )\n"
)
end #for
balloon = string(
balloon,
" ",
repeat("-", paddinglength),
"\n"
)
return balloon
end #function
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 1444 | """
function blowfish()
A blowfish.
```jldoctest
julia> cowsay("Bloop, bloop", cow=Cowsay.blowfish)
______________
< Bloop, bloop >
--------------
\\
\\
| .
. |L /|
_ . |\\ _| \\--+._/| .
/ ||\\| Y J ) / |/| ./
J |)'( | ` F`.'/
-<| F __ .-<
| / .-'. `. /-. L___
J \\ < \\ | | O\\|.-'
_J \\ .- \\/ O | | \\ |F
'-F -<_. \\ .-' `-' L__
__J _ _. >-' )._. |-'
`-|.' /_. \\_| F
/.- . _.<
/' /.' .' `\\
/L /' |/ _.-'-\\
/'J ___.---'\\|
|\\ .--' V | `. `
|/`. `-. `._)
/ .-.\\
VK \\ ( `\\
`.\\
```
"""
function blowfish(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts
| .
. |L /|
_ . |\\ _| \\--+._/| .
/ ||\\| Y J ) / |/| ./
J |)'( | ` F`.'/
-<| F __ .-<
| / .-'. `. /-. L___
J \\ < \\ | | O\\|.-'
_J \\ .- \\/ O | | \\ |F
'-F -<_. \\ .-' `-' L__
__J _ _. >-' )._. |-'
`-|.' /_. \\_| F
/.- . _.<
/' /.' .' `\\
/L /' |/ _.-'-\\
/'J ___.---'\\|
|\\ .--' V | `. `
|/`. `-. `._)
/ .-.\\
VK \\ ( `\\
`.\\
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 547 | """
function bunny()
A cute little wabbit
# Example
```jldoctest
julia> cowsay("Look at that tortoise way off in the distance.", cow=Cowsay.bunny)
______________________________________
/ Look at that tortoise way off in the \\
\\ distance. /
--------------------------------------
\\
\\ \\
\\ /\\
( )
.( o ).
```
"""
function bunny(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts \\
\\ /\\
( )
.( o ).
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 700 | ##
## A cowering cow
##
"""
function cower()
A cowering cow
# Example
```jldoctest
julia> cowsay("Is it safe to come out yet?", cow=Cowsay.cower)
_____________________________
< Is it safe to come out yet? >
-----------------------------
\\
\\
,__, | |
(oo)\\| |___
(__)\\| | )\\_
| |_w | \\
| | || *
Cower....
```
"""
function cower(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts
,__, | |
(oo)\\| |___
(__)\\| | )\\_
| |_w | \\
| | || *
Cower....
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 519 | """
function default()
The original cowfile
# Example
```jldoctest
julia> cowsay("Moo", cow=Cowsay.default)
_____
< Moo >
-----
\\ ^__^
\\ (oo)\\_______
(__)\\ )\\/\\
||----w |
|| ||
```
"""
function default(;eyes="oo", tongue=" ", thoughts="\\")
thecow =
"""
$thoughts ^__^
$thoughts ($eyes)\\_______
(__)\\ )\\/\\
$tongue ||----w |
|| ||
"""
return thecow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 2771 | """
function dragon_and_cow()
A dragon smiting a cow, possible credit to [email protected]
# Example
```jldoctest
julia> cowsay("Roast beef: it's what's for dinner", cow=Cowsay.dragon_and_cow)
____________________________________
< Roast beef: it's what's for dinner >
------------------------------------
\\ ^ /^
\\ / \\ // \\
\\ |\\___/| / \\// .\\
\\ /O O \\__ / // | \\ \\ *----*
/ / \\/_/ // | \\ \\ \\ |
@___@` \\/_ // | \\ \\ \\/\\ \\
0/0/| \\/_ // | \\ \\ \\ \\
0/0/0/0/| \\/// | \\ \\ | |
0/0/0/0/0/_|_ / ( // | \\ _\\ | /
0/0/0/0/0/0/`/,_ _ _/ ) ; -. | _ _\\.-~ / /
,-} _ *-.|.-~-. .~ ~
\\ \\__/ `/\\ / ~-. _ .-~ /
\\____(oo) *. } { /
( (--) .----~-.\\ \\-` .~
//__\\\\ \\__ Ack! ///.----..< \\ _ -~
// \\\\ ///-._ _ _ _ _ _ _{^ - - - - ~
```
"""
function dragon_and_cow(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts ^ /^
$thoughts / \\ // \\
$thoughts |\\___/| / \\// .\\
$thoughts /O O \\__ / // | \\ \\ *----*
/ / \\/_/ // | \\ \\ \\ |
@___@` \\/_ // | \\ \\ \\/\\ \\
0/0/| \\/_ // | \\ \\ \\ \\
0/0/0/0/| \\/// | \\ \\ | |
0/0/0/0/0/_|_ / ( // | \\ _\\ | /
0/0/0/0/0/0/\`/,_ _ _/ ) ; -. | _ _\\.-~ / /
,-} _ *-.|.-~-. .~ ~
\\ \\__/ \`/\\ / ~-. _ .-~ /
\\____($eyes) *. } { /
( (--) .----~-.\\ \\-\` .~
//__\\\\ \\__ Ack! ///.----..< \\ _ -~
// \\\\ ///-._ _ _ _ _ _ _{^ - - - - ~
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 2139 | ##
## The Whitespace Dragon
##
"""
function dragon()
The Whitespace Dragon
# Example
```jldoctest
julia> cowsay("Roar!", cow=Cowsay.dragon)
_______
< Roar! >
-------
\\ / \\ //\\
\\ |\\___/| / \\// \\\\
/0 0 \\__ / // | \\ \\
/ / \\/_/ // | \\ \\
@_^_@'/ \\/_ // | \\ \\
//_^_/ \\/_ // | \\ \\
( //) | \\/// | \\ \\
( / /) _|_ / ) // | \\ _\\
( // /) '/,_ _ _/ ( ; -. | _ _\\.-~ .-~~~^-.
(( / / )) ,-{ _ `-.|.-~-. .~ `.
(( // / )) '/\\ / ~-. _ .-~ .-~^-. \\
(( /// )) `. { } / \\ \\
(( / )) .----~-.\\ \\-' .~ \\ `. \\^-.
///.----..> \\ _ -~ `. ^-` ^-_
///-._ _ _ _ _ _ _}^ - - - - ~ ~-- ,.-~
/.-~
```
"""
function dragon(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts / \\ //\\
$thoughts |\\___/| / \\// \\\\
/0 0 \\__ / // | \\ \\
/ / \\/_/ // | \\ \\
@_^_@'/ \\/_ // | \\ \\
//_^_/ \\/_ // | \\ \\
( //) | \\/// | \\ \\
( / /) _|_ / ) // | \\ _\\
( // /) '/,_ _ _/ ( ; -. | _ _\\.-~ .-~~~^-.
(( / / )) ,-{ _ `-.|.-~-. .~ `.
(( // / )) '/\\ / ~-. _ .-~ .-~^-. \\
(( /// )) `. { } / \\ \\
(( / )) .----~-.\\ \\-' .~ \\ `. \\^-.
///.----..> \\ _ -~ `. ^-` ^-_
///-._ _ _ _ _ _ _}^ - - - - ~ ~-- ,.-~
/.-~
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 694 | """
function elephant_in_snake()
Do we need to explain this?
# Example
```jldoctests
julia> cowsay("Help!", cow=Cowsay.elephant_in_snake)
_______
< Help! >
-------
\\
\\ ....
........ .
. .
. .
......... .......
..............................
Elephant inside ASCII snake
```
"""
function elephant_in_snake(;eyes="oo", tongue=" ", thoughts="\\")
the_cow = """
$thoughts
$thoughts ....
........ .
. .
. .
......... .......
..............................
Elephant inside ASCII snake
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 672 | """
function elephant()
An elephant out and about
# Example
```jldoctest
julia> cowsay("Toot!", cow=Cowsay.elephant)
_______
< Toot! >
-------
\\ /\\ ___ /\\
\\ // \\/ \\/ \\\\
(( O O ))
\\\\ / \\ //
\\/ | | \\/
| | | |
| | | |
| o |
| | | |
|m| |m|
```
"""
function elephant(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts /\\ ___ /\\
$thoughts // \\/ \\/ \\\\
(( O O ))
\\\\ / \\ //
\\/ | | \\/
| | | |
| | | |
| o |
| | | |
|m| |m|
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 1321 | """
function eyes()
Evil-looking eyes
# Example
```jldoctest
julia> cowsay("Mwah, ha, ha!", cow=Cowsay.eyes)
_______________
< Mwah, ha, ha! >
---------------
\\
\\
.::!!!!!!!:.
.!!!!!:. .:!!!!!!!!!!!!
~~~~!!!!!!. .:!!!!!!!!!UWWW\$\$\$
:\$\$NWX!!: .:!!!!!!XUWW\$\$\$\$\$\$\$\$\$P
\$\$\$\$\$##WX!: .<!!!!UW\$\$\$\$" \$\$\$\$\$\$\$\$#
\$\$\$\$\$ \$\$\$UX :!!UW\$\$\$\$\$\$\$\$\$ 4\$\$\$\$\$*
^\$\$\$B \$\$\$\$\\ \$\$\$\$\$\$\$\$\$\$\$\$ d\$\$R"
"*\$bd\$\$\$\$ '*\$\$\$\$\$\$\$\$\$\$\$o+#"
\"""\" \"""\"""\"
```
"""
function eyes(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts
.::!!!!!!!:.
.!!!!!:. .:!!!!!!!!!!!!
~~~~!!!!!!. .:!!!!!!!!!UWWW\$\$\$
:\$\$NWX!!: .:!!!!!!XUWW\$\$\$\$\$\$\$\$\$P
\$\$\$\$\$##WX!: .<!!!!UW\$\$\$\$" \$\$\$\$\$\$\$\$#
\$\$\$\$\$ \$\$\$UX :!!UW\$\$\$\$\$\$\$\$\$ 4\$\$\$\$\$*
^\$\$\$B \$\$\$\$\\ \$\$\$\$\$\$\$\$\$\$\$\$ d\$\$R"
"*\$bd\$\$\$\$ '*\$\$\$\$\$\$\$\$\$\$\$o+#"
\"""\" \"""\"""\"
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 1041 | ##
## The flaming sheep, contributed by Geordan Rosario ([email protected])
##
"""
function flaming_sheep()
The flaming sheep, contributed by Geordan Rosario ([email protected])
# Example
```jldoctest
julia> cowsay("Baaahhh!", cow=Cowsay.flaming_sheep)
__________
< Baaahhh! >
----------
\\ . . .
\\ . . . ` ,
\\ .; . : .' : : : .
\\ i..`: i` i.i.,i i .
\\ `,--.|i |i|ii|ii|i:
UooU\\.'@@@@@@`.||'
\\__/(@@@@@@@@@@)'
(@@@@@@@@)
`YY~~~~YY'
|| ||
```
"""
function flaming_sheep(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts . . .
$thoughts . . . ` ,
$thoughts .; . : .' : : : .
$thoughts i..`: i` i.i.,i i .
$thoughts `,--.|i |i|ii|ii|i:
U$(eyes)U\\.'@@@@@@`.||'
\\__/(@@@@@@@@@@)'
(@@@@@@@@)
`YY~~~~YY'
|| ||
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 1296 | """
function fox()
# Example
```jldoctest
julia> cowsay("What does the fox say?", cow=Cowsay.fox)
________________________
< What does the fox say? >
------------------------
\\ ,-. .-,
\\ |-.\\ __ /.-|
\\ \\ ` ` /
/_ _ \\
< _`q p _ >
<.._=/ \\=_. >
{`\\()/`}`\\
{ } \\
|{ } \\
\\ '--' .- \\
|- / \\
| | | | | ;
| | |.;.,..__ |
.-"";` `|
/ | /
`-../____,..---'`
```
"""
function fox(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts ,-. .-,
$thoughts |-.\\ __ /.-|
$thoughts \\ ` ` /
/_ _ \\
< _`q p _ >
<.._=/ \\=_. >
{`\\()/`}`\\
{ } \\
|{ } \\
\\ '--' .- \\
|- / \\
| | | | | ;
| | |.;.,..__ |
.-"";` `|
/ | /
`-../____,..---'`
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 697 | """
function kitty()
A kitten of sorts, I think
# Example
```jldoctest
julia> cowsay("Meow", cow=Cowsay.kitty)
______
< Meow >
------
\\
\\
("`-' '-/") .___..--' ' "`-._
` *_ * ) `-. ( ) .`-.__. `)
(_Y_.) ' ._ ) `._` ; `` -. .-'
_.. `--'_..-_/ /--' _ .' ,4
( i l ),-'' ( l i),' ( ( ! .-'
```
"""
function kitty(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts
("`-' '-/") .___..--' ' "`-._
` *_ * ) `-. ( ) .`-.__. `)
(_Y_.) ' ._ ) `._` ; `` -. .-'
_.. `--'_..-_/ /--' _ .' ,4
( i l ),-'' ( l i),' ( ( ! .-'
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 478 | """
function koala
From the canonical koala collection
# Example
```jldoctest
julia> cowsay("Welcome to Down Under", cow=Cowsay.koala)
_______________________
< Welcome to Down Under >
-----------------------
\\
\\
___
{~._.~}
( Y )
()~*~()
(_)-(_)
```
"""
function koala(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts
___
{~._.~}
( Y )
()~*~()
(_)-(_)
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 2035 | """
function mech_and_cow()
# Example
```jldoctest
julia> cowsay("Do you ever get that feeling...?", cow=Cowsay.mech_and_cow)
__________________________________
< Do you ever get that feeling...? >
----------------------------------
\\ ,-----.
/ | |
\\ ,--| |-.
/ __,----| | | |
\\ ,;:: | `_____' |
/ `._______| i^i |
\\ `----| |---'| .
/ ,-------._| |== ||//
\\ | |_|P`. /'/
/ `-------' 'Y Y/'/'
\\ .==\\ /_\\
^__^ / /'| `i
(oo)\\_______ /' / | |
(__)\\ )\\/\\ /' / | `i
||----w|| ___,;`----'.___L_,-'`\\__
|| || i_____;----\\.____i""\\____\\
```
"""
function mech_and_cow(;eyes="oo", tongue=" ", thoughts="\\")
sthguoht = thoughts;
if thoughts == "\\"
sthguoht = "/"
end #if
the_cow =
"""
$thoughts ,-----.
$sthguoht | |
$thoughts ,--| |-.
$sthguoht __,----| | | |
$thoughts ,;:: | `_____' |
$sthguoht `._______| i^i |
$thoughts `----| |---'| .
$sthguoht ,-------._| |== ||//
$thoughts | |_|P`. /'/
$sthguoht `-------' 'Y Y/'/'
$thoughts .==\\ /_\\
^__^ / /'| `i
($eyes)\\_______ /' / | |
(__)\\ )\\/\\ /' / | `i
$tongue||----w|| ___,;`----'.___L_,-'`\\__
|| || i_____;----\\.____i""\\____\\
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 1163 | """
function meow()
A meowing tiger?
# Example
```jldoctest
julia> cowsay("We're kind of stupid that way", cow=Cowsay.meow)
_______________________________
< We're kind of stupid that way >
-------------------------------
\\
\\ , _ ___.--'''`--''//-,-_--_.
\\`"' ` || \\\\ \\ \\\\/ / // / ,-\\\\`,_
/'` \\ \\ || Y | \\|/ / // / - |__ `-,
/@"\\ ` \\ `\\ | | ||/ // | \\/ \\ `-._`-,_.,
/ _.-. `.-\\,___/\\ _/|_/_\\_\\/|_/ | `-._._)
`-'``/ / | // \\__/\\__ / \\__/ \\
`-' /-\\/ | -| \\__ \\ |-' |
__/\\ / _/ \\/ __,-' ) ,' _|'
(((__/(((_.' ((___..-'((__,'
```
"""
function meow(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts , _ ___.--'''`--''//-,-_--_.
\\`"' ` || \\\\ \\ \\\\/ / // / ,-\\\\`,_
/'` \\ \\ || Y | \\|/ / // / - |__ `-,
/@"\\ ` \\ `\\ | | ||/ // | \\/ \\ `-._`-,_.,
/ _.-. `.-\\,___/\\ _/|_/_\\_\\/|_/ | `-._._)
`-'``/ / | // \\__/\\__ / \\__/ \\
`-' /-\\/ | -| \\__ \\ |-' |
__/\\ / _/ \\/ __,-' ) ,' _|'
(((__/(((_.' ((___..-'((__,'
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 716 | ##
## MOOfasa.
##
"""
function moofasa()
MOOfasa
# Example
```jldoctest
julia> cowsay("It's the circle of life", cow=Cowsay.moofasa)
_________________________
< It's the circle of life >
-------------------------
\\ ____
\\ / \\
| ^__^ |
| (oo) |______
| (__) | )\\/\\
\\____/|----w |
|| ||
Moofasa
```
"""
function moofasa(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts ____
$thoughts / \\
| ^__^ |
| ($eyes) |______
| (__) | )\\/\\
\\____/|----w |
|| ||
Moofasa
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 591 | """
function moose()
# Example
```jldoctest
julia> cowsay("Time to vamoose", cow=Cowsay.moose)
_________________
< Time to vamoose >
-----------------
\\
\\ \\_\\_ _/_/
\\ \\__/
(oo)\\_______
(__)\\ )\\/\\
||----w |
|| ||
```
"""
function moose(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts \\_\\_ _/_/
$thoughts \\__/
($eyes)\\_______
(__)\\ )\\/\\
$tongue ||----w |
|| ||
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 682 | """
function mutilated()
A mutilated cow, from [email protected]
# Example
```jldoctest
julia> cowsay("I wouldn't have been so eager to make head cheese...", cow=Cowsay.mutilated)
_______________________________________
/ I wouldn't have been so eager to make \\
\\ head cheese... /
---------------------------------------
\\ \\_______
v__v \\ \\ O )
(oo) ||----w |
(__) || || \\/\\
```
"""
function mutilated(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts \\_______
v__v $thoughts \\ O )
($eyes) ||----w |
(__) || || \\/\\
$tongue
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 551 | ##
## The non-flaming sheep.
##
"""
function sheep()
The non-flaming sheep.
# Example
```jldoctest
julia> cowsay("Baa", cow=Cowsay.sheep)
_____
< Baa >
-----
\\
\\
__
UooU\\.'@@@@@@`.
\\__/(@@@@@@@@@@)
(@@@@@@@@)
`YY~~~~YY'
|| ||
```
"""
function sheep(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts
$thoughts
__
U$(eyes)U\\.'@@@@@@`.
\\__/(@@@@@@@@@@)
(@@@@@@@@)
`YY~~~~YY'
|| ||
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 973 | ##
##
"""
function skeleton()
This 'Scowleton' brought to you by one of
{appel,kube,rowe}@csua.berkeley.edu
# Example
```jldoctest
julia> cowsay("All T-Bone, no steak", cow=Cowsay.skeleton)
______________________
< All T-Bone, no steak >
----------------------
\\ (__)
\\ /oo|
\\ (_"_)*+++++++++*
//I#\\\\\\\\\\\\\\\\I\\
I[I|I|||||I I `
I`I'///'' I I
I I I I
~ ~ ~ ~
Scowleton
```
"""
function skeleton(;eyes="oo", tongue=" ", thoughts="\\")
the_cow =
"""
$thoughts (__)
$thoughts /$eyes|
$thoughts (_"_)*+++++++++*
//I#\\\\\\\\\\\\\\\\I\\
I[I|I|||||I I `
I`I'///'' I I
I I I I
~ ~ ~ ~
Scowleton
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
|
[
"MIT"
] | 1.0.0 | 193ec7cad29c4099823e7a0d853b4173ad5d3ab1 | code | 477 | """
function small()
A small cow, artist unknown
# Example
```jldoctest
julia> cowsay("A calf", cow=Cowsay.small)
________
< A calf >
--------
\\ ,__,
\\ (..)____
(__) )\\
||--|| *
```
"""
function small(;eyes="oo", tongue=" ", thoughts="\\")
if eyes == "oo"
eyes = ".."
end
the_cow =
"""
$thoughts ,__,
$thoughts ($eyes)____
(__) )\\
$tongue||--|| *
"""
return the_cow
end
| Cowsay | https://github.com/MillironX/Cowsay.jl.git |
Subsets and Splits