text:
# Text-to-Image Search via CLIP#

This guide will showcase fine-tuning a CLIP model for text to image retrieval.

We’ll be fine-tuning CLIP on the fashion captioning dataset which contains information about fashion products.

For each product the dataset contains a title and images of multiple variants of the product. We constructed a parent Document for each picture, which contains two chunks: an image document and a text document holding the description of the product.

## Data#

Our journey starts locally. We have to prepare the data and push it to the cloud and Finetuner will be able to get the dataset by its name. For this example, we already prepared the data, and we’ll provide the names of training and evaluation data (clip-fashion-train-data and clip-fashion-eval-data) directly to Finetuner.

## Backbone model#

Currently, we only support openai/clip-vit-base-patch32 for text to image retrieval tasks. However, you can see all available models either in choose backbone section or by calling describe_models().

## Fine-tuning#

From now on, all the action happens in the cloud!

First you need to login to Jina ecosystem:

import finetuner

Now that everything’s ready, let’s create a fine-tuning run!

import finetuner

run = finetuner.fit(
model='openai/clip-vit-base-patch32',
run_name='clip-fashion',
train_data='clip-fashion-train-data',
eval_data='clip-fashion-eval-data',
epochs=5,
learning_rate= 1e-5,
loss='CLIPLoss',
cpu=False,
)

Let’s understand what this piece of code does:

finetuner.fit parameters

The only required arguments are model and train_data. We provide default values for others. Here is the full list of the parameters.

• We start with providing model, run_name, names of training and evaluation data.

• We also provide some hyper-parameters such as number of epochs and a learning_rate.

• Additionally, we use BestModelCheckpoint to save the best model after each epoch and EvaluationCallback for evaluation.

## Monitoring#

We created a run! Now let’s see its status.

print(run.status())

{'status': 'CREATED', 'details': 'Run submitted and awaits execution'}

Since some runs might take up to several hours/days, it’s important to know how to reconnect to Finetuner and retrieve your run.

import finetuner
run = finetuner.get_run('clip-fashion')

You can continue monitoring the run by checking the status - status() or the logs - logs().

## Evaluating#

Currently, we don’t have a user-friendly way to get evaluation metrics from the EvaluationCallback we initialized previously. What you can do for now is to call logs() in the end of the run and see evaluation results:

           INFO     Done ✨                                                                              __main__.py:219
INFO     Saving fine-tuned models ...                                                         __main__.py:222
INFO     Saving model 'model' in /usr/src/app/tuned-models/model ...                          __main__.py:233
INFO     Pushing saved model to Hubble ...                                                    __main__.py:240
[10:38:14] INFO     Pushed model artifact ID: '62a1af491597c219f6a330fe'                                 __main__.py:246
INFO     Finished 🚀                                                                          __main__.py:248

Evaluation of CLIP

In this example, we did not plug-in an EvaluationCallback since the callback can evaluate one model at one time. In most cases, we want to evaluate two models: i.e. use CLIPTextEncoder to encode textual Documents as query_data while use CLIPImageEncoder to encode image Documents as index_data. Then use the textual Documents to search image Documents.

We have done the evaulation for you in the table below.

Before Finetuning After Finetuning
average_precision 0.253423 0.415924
dcg_at_k 0.902417 2.14489
f1_score_at_k 0.0831918 0.241773
hit_at_k 0.611976 0.856287
ndcg_at_k 0.350172 0.539948
precision_at_k 0.0994012 0.256587
r_precision 0.231756 0.35847
recall_at_k 0.108982 0.346108
reciprocal_rank 0.288791 0.487505

## Saving#

artifact = run.save_artifact('clip-model')

## Inference#

Now you saved the artifact into your host machine, let’s use the fine-tuned model to encode a new Document:

from docarray import Document, DocumentArray

# Prepare some documents to encode
text_da = DocumentArray([Document(text='some text to encode')])
image_da = DocumentArray([Document(uri='my-image.png')])
clip_text_encoder = finetuner.get_model(artifact=artifact, select_model='clip-text')
clip_image_encoder = finetuner.get_model(artifact=artifact, select_model='clip-vision')
# Encoding will happen in-place in your DocumentArray
finetuner.encode(model=clip_text_encoder, data=text_da)
finetuner.encode(model=clip_image_encoder, data=image_da)

print(text_da.embeddings.shape)
print(image_da.embeddings.shape)

(1, 512)
(1, 512)

what is select_model?

When fine-tuning CLIP, we are fine-tuning the CLIPVisionEncoder and CLIPTextEncoder in parallel. The artifact contains two models: clip-vision and clip-text. The parameter select_model tells finetuner which model to use for inference, in the above example, we use clip-text to encode a Document with text content.

Inference with ONNX

In case you set to_onnx=True when calling finetuner.fit function, please use model = finetuner.get_model('/path/to/YOUR-MODEL.zip', is_onnx=True)

Check out clip-as-service to learn how to plug-in a finetuned CLIP model to our CLIP specific service.

That’s it! If you want to integrate the fine-tuned model into your Jina Flow, please check out integrated with the Jina ecosystem.


text:
# splitting one limit into two?

Suppose I have the limit

$\lim_{m\rightarrow \infty}\frac{\sum_{k=0}^ma_{k,m}}{\sum_{k=0}^mb_{k,m}}$.

When can I write this as

$\lim_{n\rightarrow \infty}\lim_{m\rightarrow \infty} \frac{\sum_{k=0}^ma_{k,n}}{\sum_{k=0}^mb_{k,n}}$?

To be specific, both sums converge to exponentials, which tend to zero as $n\rightarrow$. I'd like to take their ratio before letting $n$ tend to infinity.

-
As stated, I think I can cook up counterexamples, so it might be helpful to be even more specific about what you actually want to prove. –  Yemon Choi Apr 8 '13 at 4:12
Actually, I now realize that the latter expression is also an ok starting point, which is what I needed. Thanks for the help. –  user32851 Apr 8 '13 at 16:22

## 1 Answer

The first (single) limit is totally blind to terms   $a_{k\ n}\ \ b_{k\ n}$   for all   $k > n$,   while the second (double) limit depends on them. Thus the two limits are hardly related at all.

In other words, the single limit considers finite segments, and the double limit the infinite segments. To compare these two there should be perhaps a relation given between the finite and infinite sums.

Also, something should be said about denominators staying reasonably away from $0$; well--something :-)

(I am surprised that the m-th sums in the single limit case have exactly m terms--I'd expect a more flexible situation).

-

format: plain


text:
The function SAMC helps users to build a SAMC sampler easily. However, the main part of our implementation requires numerous evaluations of an energy function at each iteration, which becomes a critical bottleneck in computational aspect. SAMCPLUS exploits a generic framework for passing user-provided C++ functions to our backend. We will use two-dimensional multimodal example (Liang, Liu, and Carroll 2010) to introduce details on how to boost your computation using XPtr.

## Basic Example

The problem is to sample from a multimodal distribution $$f(x) \propto \exp\{-H(x)\}$$, where $\begin{eqnarray} H(x) = &-\{x_1 \sin(20x_2) + x_2 \sin(20x_1)\}^2 \cosh\{\sin(10x_1)x_1\} \\ &- \{x_1 \cos(10x_2) - x_2 \sin(10x_1)\}^2 \cosh\{\cos(20x_1)x_1\} \end{eqnarray}$ with domain $$(x_1,x_2) \in [-1.1,1.1]^2$$. Before we start in detail, let’s define an options list containing other parameters for our problem.

myoption = list()
myoption$partition = c(-Inf,seq(from=-8,to=0,length.out=41)) # energy partition myoption$tau       = 1.0                                     # temperature
myoption$domain = c(-1.1,1.1) # domain for sample space myoption$vecpi     = as.vector(rep(1/41,41))                 # desired sampling distribution
myoption$niter = 200000 # total number of iterations myoption$stepsize  = 0.25                                    # s.d for random-walk proposal

### Option 1 : R function

First, define a corresponding R function func_r that evaluates $$H(x)$$,

func_r = function(x){
x1 = x[1]; x2 = x[2];
val1 = (-(x1*sin(20*x2)+x2*sin(20*x1))^2)*cosh(sin(10*x1)*x1);
val2 = (-(x1*cos(10*x2)-x2*sin(10*x1))^2)*cosh(cos(20*x2)*x2);
return(val1+val2);
}

### Option 2 : C++ function

Let’s make a C++ function that does the same job,

library(RcppXPtrUtils)
cppscript = "SEXP funcH(arma::vec x){
double x1 = x(0);
double x2 = x(1);
double val1 = (-std::pow((x1*sin(20*x2)+x2*sin(20*x1)),2))*cosh(sin(10*x1)*x1);
double val2 = (-std::pow((x1*cos(10*x2)-x2*sin(10*x1)),2))*cosh(cos(20*x2)*x2);
return Rcpp::wrap(val1+val2);
}"
func_ptr = RcppXPtrUtils::cppXPtr(cppscript,depends="RcppArmadillo") # as a pointer

Conventional wrapping of a C/C++ chunk usually returns a wrapper that directly calls the compiled function from R. However, cppXPtr now returns an XPtr object, which is an R’s traditional externalptr wrapped into a XPtr class.

### Comparison : Results

First observation should be whether two operations result in nearly identical samples.

library(SAMCpack)
res1 = SAMC(2,func_r,options=myoption)       # use R function
res2 = SAMCPLUS(2,func_ptr,options=myoption) # use C++ function

Then, we can see that these two results are compatible, where first 100 runs are disregarded and 1/100 thinning is applied.

### Comparison : Time

The most critical reason to use SAMCPLUS would be execution time. We ran each 10 times.

library(microbenchmark)
execution = microbenchmark(
list = alist(
runR   = SAMC(2,func_r,options=myoption),
runCPP = SAMCPLUS(2,func_ptr,options=myoption)
), times=10
)

and the boxplot below shows a large gap between these two methods.

## How To Write a C++ Function

In the Option 2 of previous section, once a CPP script is written as an inline function, it can be wrapped as XPtr. In order to keep consistency across a variety code snippets and minimize potential error, we decided to impose some restrictions.

• Return type must be SEXP, short for S-Expression, as in SEXP function(...).
• First input argument is a arma::vec object from RcppArmadillo, representing random variable $$x$$.
• Second input argument is used when additional data needs to be inserted through data argument of SAMCPLUS. They are should be one of
• arma::vec for a vector,
• arma::mat for a matrix, or
• R’s native List
• When you use List as your data, type conversion or suitable adjustment may be required.

RcppArmadillo is a templated C++ linear algebra library. We believe it balances ease of use like other script computing platform and computational efficiency. For example, most of expressions many statisticians often use involve some degree of numerical operations and RcppArmadillo is definitely one of the optimal options if not the best. For more details about the library, please see the introductory vignette.

## User-Provided Data with XPtr

As noted before, we made three options available when the compiled C++ function needs to use external data - vector(arma::vec), matrix(arma::mat), and List(Rcpp::List).

### Case 1 : Vector/Matrix Data

We will still use the same example. First, let’s consider a case to use a vector-valued data. In our example, let’s call a vector $$data\_vec=(10,20)^\top$$. In this case, we can define a C++ function as below.

data_vec = as.vector(c(10,20)) # vector-valued data=(10,20)
cppscript_vec = "SEXP funcH_vec(arma::vec x, arma::vec data){
double x1 = x(0);
double x2 = x(1);
double par1 = data(0);  // first element  : 10
double par2 = data(1);  // second element : 20
double val1 = (-std::pow((x1*sin(par2*x2)+x2*sin(par2*x1)),2))*cosh(sin(par1*x1)*x1);
double val2 = (-std::pow((x1*cos(par1*x2)-x2*sin(par1*x1)),2))*cosh(cos(par2*x2)*x2);
return Rcpp::wrap(val1+val2);
}"

Second, let’s assume we have a matrix-valued data, $data\_mat = \begin{pmatrix} 20 & 20 & 10 \\ 10 & 10 & 20 \end{pmatrix}$ whose elements are corresponding to the numeric values in a cost function. As before,

data_mat = matrix(c(20,10,20,10,10,20),nrow=2)
cppscript_mat = "SEXP funcH_mat(arma::vec x, arma::mat data){
double x1 = x(0);
double x2 = x(1);
double val1 = (-std::pow((x1*sin(data(0,0)*x2)+x2*sin(data(0,1)*x1)),2))*cosh(sin(data(0,2)*x1)*x1);
double val2 = (-std::pow((x1*cos(data(1,0)*x2)-x2*sin(data(1,1)*x1)),2))*cosh(cos(data(1,2)*x2)*x2);
return Rcpp::wrap(val1+val2);
}"

Then, create two XPtr’s from our supplied functions,

func_ptrvec = RcppXPtrUtils::cppXPtr(cppscript_vec,depends="RcppArmadillo") # as a pointer
func_ptrmat = RcppXPtrUtils::cppXPtr(cppscript_mat,depends="RcppArmadillo") # as a pointer

and these can be run likewise.

res3 = SAMCPLUS(2,func_ptrvec,options=myoption,data=data_vec) # vector data
res4 = SAMCPLUS(2,func_ptrmat,options=myoption,data=data_mat) # matrix data

and still we can check that the results are compatible.

### Case 2 : List Data

Unlike arma::vec and arma::mat, List is a native R and Rcpp object. List may contain multiple elements and for this scenario we will use both vector and matrix data, each. Especially, in this case, we will show how you can use Rcpp native vector and matrix class as well. First, let’s prepare the data.

data_list = list()
data_list[[1]] = as.vector(c(20,10))
data_list[[2]] = matrix(c(20,10,10,20),nrow=2)

In the code below, vector and matrix are sequentially extracted using integer index for a list.

cppscript_list = "SEXP funcH_list(arma::vec x, Rcpp::List datalist){
double x1 = x(0);
double x2 = x(1);

NumericVector lefty = as<NumericVector>(datalist[0]);
NumericMatrix right = as<NumericMatrix>(datalist[1]);

double val1 = (-std::pow((x1*sin(lefty[0]*x2)+x2*sin(right(0,0)*x1)),2))*cosh(sin(right(0,1)*x1)*x1);
double val2 = (-std::pow((x1*cos(lefty[1]*x2)-x2*sin(right(1,0)*x1)),2))*cosh(cos(right(1,1)*x2)*x2);
return Rcpp::wrap(val1+val2);
}"

If we compile as before and run it, we can check the following results,

### Case 3 : Arbitrary-Type Data

As well known, types of data available in R are indeed just SEXPs, or S-expression. Therefore, for the advanced user, we made SEXP option to be taken care of at the interface level. Below should be a replicate of using vector-type data similar to Case 1, but additional care of type conversion is required.

cppscript_sexp = "SEXP funcH_sexp(arma::vec x, SEXP data){
double x1 = x(0);
double x2 = x(1);

// Wrap the input 'data' as 'datavec' (Rcpp type)
NumericVector datavec = as<NumericVector>(data);

double par1 = datavec[0];  // first element  : 10
double par2 = datavec[1];  // second element : 20
double val1 = (-std::pow((x1*sin(par2*x2)+x2*sin(par2*x1)),2))*cosh(sin(par1*x1)*x1);
double val2 = (-std::pow((x1*cos(par1*x2)-x2*sin(par1*x1)),2))*cosh(cos(par2*x2)*x2);
return Rcpp::wrap(val1+val2);
}"

Let’s see it ran well,

data_sexp = as.vector(c(10,20)) # vector-valued data=(10,20) to be passed as SEXP
res6 = SAMCPLUS(2,func_ptrsexp,options=myoption,data=data_sexp)


text:
# How can I append a number at the end of a string object?

## Recommended Posts

Googol PL3X    100
So far I've got this u32 attachedControlers = getNumberOfControls(); //vector to hold player names vector<string> names; if (attachedControlers > 1 && multiPlayer(attachedControlers)) for (int i = 0; i < attachedControlers; ++ i) { names.push_back("Player"); } else names.push_back("Player1"); But what I need is something that adds a number to the end based on what i is equal too, so if attachedControlers == 3 I will fill my vector with "Player1", "Player2" and "Player3", but I don't know how to append a number to the end without using c style strings.

##### Share on other sites
Evil Steve    2017
With std::stringstream:
// #include <sstream> at the top of your filestd::stringstream str;str << "Player" << attachedControlers;names.push_back(str.str());

##### Share on other sites
jochen    333
You can use std::ostringstream.

std::string Playername = "Player";std::ostringstream StrStream;StrStream << i;Playername.append( StrStream.str() );

also to make it a little more readable, and if you are not afraid of using boost, you could write

std::string Playername = "Player";Playername += boost::lexical_cast< std::string > ( i );

best Jochen

##### Share on other sites
Googol PL3X    100
Hey thanks guys, a few questions

Whats the boost namespace I've never heard it?

And what does lexical_cast do?

##### Share on other sites
Evil Steve    2017
Quote:
 Original post by Googol PL3XHey thanks guys, a few questionsWhats the boost namespace I've never heard it?And what does lexic_cast do?
Boost and lexical_cast.

##### Share on other sites
jochen    333
boost is a well known and imho very usefull resource for C++ developers.
You can find out about boost at www.boost.org.

boost::lexical_cast is a library that's part of boost.

Best Jochen

##### Share on other sites
Googol PL3X    100
Awsome, thanks mate :)


text:
# PHysics 11 Pulley probem

1. Nov 20, 2004

### eno

PLZ HELP!! I am puzzled with this problem, and all i could find are that the forces equal, but the ans int eh back of the textbook clearly says the solution is 0.2 m/s2

Question: This situation occurs in a pulley system. A 80.0 kg man inside a 40.0 kg dumb waiter (like an elevator) pulls down on the rope. At the end of the rope, it is attached to the dumb-waiter. At the other end, the person exerts a force. At that moment, the scale on which he is standing reads 200N. Determine the elevator's acceleration.

THX for ur time!!

2. Nov 20, 2004

### Physik

Hmm.. thats wierd. I didn't get 0.2m/s^2

Let me try to understand this better. The man is inside the dumbwaiter (which will pull up the elevator) has a mass of 80kg, the dumbwaiter is 40kg, so total mass of the dumbwaiter is 120kg. Correct?

http://img52.exs.cx/img52/1381/2035.gif

I got 8.1 m/s^2 as an answer. So I don't know if I'm wrong, or the book is.

Last edited: Nov 20, 2004
3. Nov 21, 2004

### Raza

MAYBE this is the correct answer:
$$80+40=120$$

$$(120)(9.8)=1176$$

$$F=MA$$

$$A=\frac{F}{M}$$

$$A=\frac{200}{1176}$$

$$A=0.17m/s^2$$
Probably the 0.17 is rounded off.

Last edited: Nov 21, 2004
4. Nov 21, 2004

### eno

sorry, Raza, nice try. the 1176 is the force, and not the mass, so u cannot use the force of 200N to divide that force, which results in some unknown unit number. THe answer just conincidently matches with the ans int he book, but i am sure the way u got it is wrong....again, thx for trying.

physik, here's the link to the actual question and diagram from the textbk:

http://www.enovon.com/public/physics.jpg

again, thx for trying, maybe u can understand the problem better by this clear picture :)

Last edited by a moderator: Apr 21, 2017
5. Nov 21, 2004

### gauravkukreja

Let us consider the dumb-waiter separately.
The man standing on it has a mass 80 kg, but the force exerted by him on the elevator is 200N.
He is applying some force on the rope, say F.
80g-F=200
You can solve this to know F.
Now the weight of the elevator is 40 kg ang the force exerted by the man is 200N. Let the acc. of the elevator be a.
F-200-40g=40a.
Substituting F=80g-200
we get 80g-200-200-40g=40a
Therefore,40g-400=40a
Therefore,a=g-10,
Therefore,a=-0.2m/s^2
That is 0.2 m/s^2 downwards

6. Nov 21, 2004

### eno

thx alot, gauravkukreja!


text:
Question

# A man filled his car tank with 20 litres of diesel to travel exactly 480 km. At the end of the day, he finds 8 litres of diesel left in the tank. How much distance did he cover?

A
258 km
B
210 km
C
250 km
D
288 km

Solution

## The correct option is D 288 kmGiven, 20 litres of diesel is required to cover 480 km. At the end of the day, 8 litres of diesel is left. So, litres of diesel consumed = (20 - 8) = 12 litres We know that, if, the number of litres of diesel consumed increases, then the distance covered also increases. So, Litres of diesel(x)∝Distance(y) ∴ x1y1 = x2y2 Given, x1 = 20 l y1 = 480 km x2 = 12 l and y2 = distance covered ⇒ y2 = x2 × y1x1 ⇒ y2 = 12 × 48020 = 288 km Mathematics

Suggest Corrections

1

Similar questions
View More

People also searched for
View More


text:
# What might the (normalized) pair correlation function of prime numbers look like?

You might have read about the fortuitous meeting between Montgomery and Dyson. The background is that the nontrivial zeros of the Riemann zeta function, when normalized to have unit spacing on average, (seem to) have the pair correlation function $1-\mathrm{sinc}^2(x)$, where $\mathrm{sinc}$ is the normalized function $\sin(\pi x)/ (\pi x)$. It’s still a conjecture but it has good numerical support.

So what about prime numbers? Let $\Sigma(x,u)$ be the number of pairs of primes $p,q\le x$ which satisfy the inequality $0\le p-q\le u\,x/\pi(x)$, where $\pi(x)$ is the prime counting function. This inequality is chosen because multiplying primes by $\pi(x)/x$ will ensure the gaps between consecutives is exactly unity (hence they are normalized). Then what might

$$g(u)=\frac{d}{du}\left(\lim_{x\to\infty}\frac{\Sigma(x,u)}{\pi(x)}\right)$$

end up looking like? This basically asks, “what is the density of normalized primes around so-and-so apart from each other?” (You can see the original Montgomery conjecture as equation 12 here. I’ve adapted it to prime numbers by essentially changing the asymptotic number of zeta zeros to the prime counting function instead.)

I have also posted this question on MathOverflow here. I figured this question might be at more of a researcher’s level than Math.StackExchange is used to and so would be beneficial to cross-post. MO user David Roberts informs me this is something of a malpractice, as it makes collecting answers awkward and a delay should be allowed for one site (presumably SE) to have a go at it. I’ll keep this in mind in the future.

#### Solutions Collecting From Web of "What might the (normalized) pair correlation function of prime numbers look like?"

The answer is posted here on MathOverflow.

The purpose of this answer is to redirect others, and also so that the question does not remain “unanswered”.


text:
# Research

## Post-doctoral research at CIMNE (2016-present)

### Objectives

This part of my research career starts in January 2016 and it extends up to the present. I joined CIMNE as a post-doc researcher in 2016 and I was promoted to Assistant Research Professor in view of my academic results in 2019. In CIMNE, I am pursuing a research agenda, whose main objectives are:

• Developing novel parallel finite element (FE) techniques for the simulation of complex problems in science an engineering using modern supercomputers

• Helping application experts to adopt these novel computational techniques to solve real-world problems

• Implementing these computer tools in open-source software projects in order to foster their adoption by the scientific community

### Research lines

In order to address these global objectives, my main research lines are:

• RL1: Simplify mesh generation in large-scale parallel computations via embedded FE methods

• RL2: Software design of scientific applications and open-source codes (the Gridap.jl project)

#### RL1: Simplify mesh generation in large-scale parallel computations via embedded FE methods

Mesh generation is known to be one of the main bottlenecks in real-world industrial FE simulations. Conventional FE methods require so-called body-fitted meshes, i.e., grids that conform to the geometrical boundaries of the computational domain (see Figure 1). Constructing such grids is not obvious for complex geometries. It often requires skilled humans, and it is time consuming as mesh generation is estimated to be 80% of total simulation time in industrial applications [cottrell_2009]. The goal of so-called embedded FE methods [burman_2015] (also known as unfitted or immersed methods) is to change this situation by allowing one to work on background Cartesian meshes that do not necessarily conform to the geometrical boundaries (see Figure 1). Generating such unfitted Cartesian grids is much simpler and more efficient that constructing body fitted meshes, specially in large parallel computations. One can use highly scalable octree-based mesh generators like the p4est package, which has shown excellent scaling properties up to thousands of hundreds of CPU cores.

Figure 1: Body-fitted vs. unfitted meshes

However, embedded methods have known drawbacks. One of the most notorious, still an open question today, is the so-called small cut cell problem. Some cells of the unfitted mesh can be intersected by a very small part of the domain, which can lead to arbitrarily large condition numbers in the underlying discrete FE operators. This is a major issue, when dealing with large-scale simulations that require Krylov sub-space iterative linear solvers because they are very sensitive to the conditioning and spectral properties of the underlying operators. The result is that embedded methods are mainly used in small to medium problems, which can be handled with direct linear solvers (i.e., Gaussian elimination) instead of iterative procedures. One of my main research goals at CIMNE is to address the conditioning problems of embedded methods in order to allow their usage in large-scale real-world computations.

##### Funding

This research line has several funding sources. On the one hand, I was awarded with a Beatriu Pinós fellowship (a competitive post-doc grant issued by the Catalan autonomous government) to develop embedded FE methods for the simulation of additive manufacturing processes. With the help of this grand I was able to develop new numerical techniques and mentor a PhD student in order to adopt these new tools in his additive manufacturing simulations. This work is also framed in the H2020 project "EMUSIC", which also focuses in the same application. This research line on embedded methods has also been supported by the H2020 project "ExaQUte". In particular, I am contributor in the work package "WP1 Embedded methods", where I have lead the research associated with task "Task 1.6: Development of robust (and scalable) linear solvers for the embedded case". Another funding source is the Spanish project "SOFAST". I am involved in the works packages "WP1 Embedded methods" and "WP2 Adaptive mesh refinement". In the frame of these projects, I am currently supervising a PhD student at UPC, who is developing novel techniques to couple CAD models and embedded simulations.

##### Results

This research line has lead to several major research results, which are detailed as follows.

###### Multi-level domain decomposition for embedded finite element methods

In FE analysis, the current way to solve linear systems at large-scales is using iterative Krylov sub-space methods in combination with parallel and scalable preconditioners. Unfortunately, existing preconditioners like algebraic multigrid (AMG) [briggs_2000] or multi-level domain decomposition [toselli_2005] are mainly designed for body-fitted meshes and cannot readily deal with the ill-conditioning associated with small cut cells.

Specific precontinoners for unfitted methods have been proposed in the literature in different contexts, but they are mainly serial non-scalable algorithms. This has motivated me to develop novel techniques in order to enable the usage of embedded method in much larger computations. As a first approach, I have considered BDDC preconditioners to solve such problems at large scales. This choice is motivated by the fact that BDDC methods are among the most scalable preconditioners for FE analysis. In particular, the BDDC methods implemented in my research team have shown an excellent weak scaling up to 458,752 cores and 30 billion unknowns [badia_2016]. Unfortunately, conventional BDDC preconditioners loose they optimal qualities, when the underlying problem is discretized with an unfitted grid. Thus, available BDDC solvers cannot be considered in combination with embedded FE methods.

In order to revert this unfavorable situation, I have introduced a novel BDDC method specifically tailored to deal with embedded grids. The proposed method is based on a modification of the coarse space of the BDDC solver, which makes it robust with respect to badly cut cells. The method has been shown to be algorithmically weak scalable for a wide range of 3D complex geometries. That is, the number of iterations needed to reach convergence in the preconditioned linear solver is asymptotically independent of the problem size (see Figure 2). This work is published in [badia_2017]) and has been presented in several conferences both at national and international level.

Figure 2: BDDC for embedded methods in a weak scaling test for a Poisson problem on different complex 3D geometries. A perfect weak scaling of the linear solver iterations is obtained.

###### The aggregated unfitted finite element method (AgFEM)

Most of the works enabling the usage of iterative linear solver in combination with embedded FE methods consider tailored preconditioners in order to deal with matrices affected by the small cut cell problem (e.g., the BDDC method for embedded grids previously presented). The main drawback of this approach is that one relies on highly customized solvers, and therefore, it is not possible to take advantage of well known and established linear solvers for FE analysis available in renowned scientific computing packages as Trilinos or PETSc. In order to address this issue, I have considered a second approach. I have developed an enhanced FE formulation that leads to linear systems, whose condition number is not affected by small cuts (see Figure 3). Therefore, they can be solved with standard linear solvers such as the AMG methods available in Trilinos or PETSc.

The enhanced FE formulation is called the aggregated unfitted finite element method (AgFEM), which is based on removal of shape functions associated with badly cut cells by introducing carefully designed constraints. The formulation of AgFEM shares the good properties of body-fitted FE methods such as stability, condition number bounds, optimal convergence, and continuity with respect to data. In contrast to previous works like CutFEM [burman_2015], it is easy to implement and to use in different problem types since it does not require to compute high order derivatives of the shape functions, and it does not introduce extra dissipation terms in the weak form. AgFEM has already been successfully applied to the solution of fluid [badia_2018b] and heat transfer problems [badia_2018a].

Figure 3: Poisson problem defined on a moving domain. Note that the standard embedded formulation leads to very high condition numbers, which are very sensitive to the relative position between the computational domain and the background mesh, specially for second order interpolations ($p=2$). In contrast, the condition number is much lower for the enhanced formulation (the AgFEM method) and it is nearly independent of the position of the domain.

Figure 4: Numerical solution of a (dimensionless) Stokes problem using the AgFEM method (streamlines colored by velocity magnitude and pressure). This computation is carried out without constructing an unstructured body-fitted mesh thanks to the application of the AgFEM method.

###### Extension of AgFEM to large-scale parallel computations.

I have implemented a distributed-memory version of AgFEM in the FEMPAR software project making use of MPI for inter-processor communications. The obtained results confirmed my expectations. When using AgFEM, the resulting systems of linear algebraic equations can be effectively solved using standard AMG preconditioners. In this case, I have considered the AMG methods available in the GAMG module of the PETSc library. With the parallel AgFEM, I was able to run weak scaling tests up to 300M degrees of freedom (DOFs) and 16K processors in the Marenostrum-IV platform. The results show that the optimal behavior of AMG solvers for body-fitted meshes is also recovered for AgFEM, i.e. number of linear solver iterations asymptotically independent of problem size. To my best knowledge, this is the first time that embedded methods are successfully applied to such large scales. These results have been published in [verdugo_2019].

###### Extension of AgFEM to adaptive computations.

Parallel implementations and scalable solvers are essential to dramatically reduce the computation times of challenging simulations, but not sufficient in many contexts. Several problems of interest are multi-scale in nature and, thus, require different mesh resolution in different spatial locations. In this context, trying to capture the finest scales with uniform meshes in overkill and the usage of adaptive mesh refinement becomes mandatory.

Parallel mesh adaptation is a challenging operation since mesh partition and load balance needs to be carefully realized to achieve performance. In large parallel computations, Cartesian grids locally adapted with forest-of-trees (also known as octree meshes) are among the few ways to locally adapt in a scalable way. They leverage so-called space-filing curves to reduce the mesh partition and load balance to a 1d problem that can be solved very efficiently. However, the main drawback of this approach is that the resulting computational grid contains so-called hanging nodes, which require extra work when defining conforming FE interpolations. If certain conditions are not satisfied, the constraints introduced by hanging nodes may expand beyond a single layer of ghost cells, thus leading to an incorrect parallel FE solver. Unfortunately, the current literature fails to explain under which conditions this happens for generic conforming FE discretizations (i.e., not only limited to Lagrangian elements). To address this situation, I have studied the correctness of a number of algorithms and parallel data structures needed to build conforming FE discretizations on octree meshes partitioned via space-filling curves. The proposed algorithms and data structures have been implemented within the FEMPAR scientific software library, using p4est as the forest-of-trees back-end. A strong scaling study reveals remarkable scalability up to 32.2K CPU cores and 482.2M DOFs (see reference [badia_2019a] ).

In a second step, I have combined the parallel AgFEM implementation previously developed with this adaptive FE framework. The result is a novel scalable distributed-memory version of AgFEM on locally-adapted Cartesian meshes. The main novelty of the method is a two-step algorithm that carefully mixes AgFEM constraints, which get rid of the small cut cell problem, and standard hanging node constraints, which ensure trace continuity. This method requires minimum parallelization effort since it can leverage standard functionality available in existing large-scale FE codes. Numerical experiments demonstrate its optimal mesh adaptation capability, robustness to cut location and parallel efficiency, on classical Poisson hp-adaptivity benchmarks. This work opens the path to functional and geometrical error-driven dynamic mesh adaptation with the AgFEM method in large-scale realistic scenarios. A research paper detailing this work is published in [badia_2021]).

###### Embedded finite element methods for 3D printing simulations

One the main driving applications of my research on embedded FE methods has been the simulation of additive manufacturing processes using advanced large-scale FEs. This is the main topic of my Beatriu Pinós fellowship and the EU H2020 project "EMUSIC", were I have participated as researcher. Additive manufacturing (also known as 3D printing) is an advanced manufacturing method used to build physical objects directly from 3D computer designs by the superposition of thin layers of materials such as metals, polymers or composites. 3D printers have been described in numerous occasions as a revolutionary technology with the potential to radically transform the manufacturing industry. However, high-energy sources used to melt metal powders during the printing process induce thermo-mechanical shape distortions and residual stresses, that deteriorate the geometrical quality and the requested material properties. Currently, the standard industrial practice to optimize the printing process in order to obtain quality components is through experimental testing, which is expensive and time consuming since it requires the production of hundreds of prototypes before reaching the final piece. Fortunately, predictive computer simulations can potentially be used to validate the process parameters before printing the component. However, current simulation software still has important limitations when it comes to predict shape distortions and residual stresses in complex settings with an acceptable level of accuracy and an acceptable time frame.

Figure 5: Snapshots of a thermal 3D printing simulation using the AgFEM method in order to effectively represent the geometry of the growing piece.

I have contributed to develop novel computational tools able to provide much faster and accurate results. In particular, generating computational meshes for additive manufacturing simulations is particularly challenging and time consuming. The shape of the 3D printed object grows in time, layer-by-layer, as it is produced. Capturing the growing shape requires a different mesh for each time step to represent the portion of the piece that has been produced so far. It is obvious that generating thousands of independent meshes with conventional methods is virtually impossible. Thus, embedded methods are well suited in this context. I have applied the AgFEM method to additive manufacturing simulations in collaboration with a PhD student of my research team (see Figure 5).

##### Current and future work

I plan to continue working on my current research line on large-scale FE solvers and embedded methods and its application to challenging engineering problems. I will extend these techniques to more challenging problem types and collaborate with application experts in order to simulate relevant real-world cases.

#### RL2: Software design of scientific applications and open-source projects

I have recently started a new research line whose goal is to develop a new generation of open-source FE codes since the development of high-performance scientific software for the numerical approximation of PDEs is a key research area with a broad impact in advanced scientific and engineering applications. Existing partial differential equation (PDE) solvers like FE codes are usually written in compiled programming languages introduced several decades ago, mainly C/C++ and Fortran 95/03/08. These languages are considered for performance reasons, but they are also related to poor code productivity. In contrast, interpreted languages like Python or MATLAB allow one to write scripts and applications in much less lines of code, boosting code productivity, but they lead to much slower programs. A trade-off between performance and productivity is usually achieved in scientific software libraries like FEniCS by combining an efficient C/C++ computational back-end with a user-friendly high-level Python user front-end. However, this approach is not satisfactory, when researchers need to extend these libraries with new features since they are forced to learn and modify a complex C/C++ back-end instead of benefiting from the productivity expected from the Python front-end. This problem is referred to as the two-language problem.

Fortunately, recent advances in compiler technology are starting to revert this situation. In the field of scientific computing, Julia is a new computer language that combines the performance of compiled languages with the productivity of interpreted ones by using recent advances in compiler technology like type inference and just-in-time compilation. As a result, the same language can be used both for the back-end and the front-end, thus eliminating the two-language problem. Based on this novel paradigm, I have started the Gridap.jl project [badia_2020], a new generation, open-source, FE framework completely written in the Julia programming language. Gridap.jl allows users to write FE applications in a notation almost one-to-one to the mathematical notation used to define the PDE weak form. For instance, see, in Figure 6, how a Poisson equation on a complex 3D domain can be solved in Gridap.jl with few lines of code. To my best knowledge, only libraries like FEniCS are able to achieve such compact user interfaces, but they are based on sophisticated compilers of variational forms, which generate, compile and link a specialized C++ back-end for the problem at hand. One of the limitations of this approach is that form compilers are rigid systems, not designed to be extended by average users. In contrast, Gridap.jl is based on a much simpler approach. It leverages the Julia just-in-time compiler to generate efficient problem-specific code without the need to maintain a custom compiler of variational forms.

Figure 6: User code to solve a 3D Poisson equation in Gridap.jl and view of the corresponding numerical solution. Note that the bilinear and linear forms of the problem, a and l, are specified with a syntax closely related to their mathematical notation thanks to an advanced software design based on the Julia computer language.

##### Funding

Gridap.jl appears as one of the two PDE codes selected to implement new novel FE methods in a "Discovery Project" of the Australian Research Council (ref: DP210103092, \$475000) co-lead by my collaborator at Monash University Prof. Santiago Badia. In the framework of this project, new collaborators are expected to joint and contribute in the expansion of the project. In addition, Gridap.jl has been accepted as a NumFOCUS affiliated project. The mission of NumFOCUS is to promote open practices in research, data, and scientific computing by serving as a fiscal sponsor for open source projects and organizing community-driven educational programs. Being an affiliated project, Gridap.jl is eligible to participate in NumFOCUS funding schemes and other events like the participation in the Google Summer of Code under the NumFOCUS umbrella. In 2021, we participated with the projects "Visualizing PDE approximations in Julia with Gridap.jl and Makie.jl" and "A fast finite element interpolator in Gridap.jl".

##### Results
###### Initial release of the open-source finite element project Gridap.jl

The first immediate result in this research line is the initial release of the project, whose source code is freely available at github under a MIT software license. In addition, a related article has been published in the "Journal of Open Scientific Software" (see reference [badia_2020]). Gridap.jl is already a fully functional general-purpose FE library ready to solve linear, non-linear, steady-state, and time-dependent PDEs. It already provides different types of conforming FE methods like nodal Lagrangian elements for grad-conforming approximations (e.g., for linear elasticity or thermal analysis) or non-nodal interpolations like Raviart-Thomas for div-conforming approximations (e.g., for flow in porous media). Discontinuous Galerkin schemes are also supported. Gridap.jl is currently used by several research groups worldwide in institutions such as Monash University, MIT, TU Delft, UPC, and CIMNE. A set of introductory tutorials to the library is available and a Gitter chat to ask questions and interact with the Gridap.jl community.

###### GridapEmbedded.jl: a Gridap.jl plugging providing embedded finite element methods

The Gridap.jl project is designed to be an extensible package ecosystem with several plugins that extend the functionality of the core repository. In particular, GridapEmbedded.jl is an extension that implements embedded FE methods. At this moment, it provides embedded methods based on classical ghost-penalty or methods based on AgFEM, being the only known open source package to provide both types of methods. GridapEmmbedded.jl will be the basis to implement the new space-time methods since it is implemented in a dimension-implemented fashion allowing to consider 4D meshes in the future.

##### Current and future work
###### GridapDistributed.jl: a Gridap.jl plugging for parallel distributed computations.

At this moment, Gridap.jl provides mainly serial algorithms and needs to be extended to parallel computations in order to cope with large-scale realistic simulations. To this end, I have started the plugin GridapDistributed.jl, whose goal is to provide the parallel functionality needed in parallel distributed-memory computations. I am designing a set of extensible distributed data structures that allow one to implement parallel algorithms in a generic way independent on the parallel computing environment (e.g., MPI or the Julia build-in distributed mode) used to run the computations. This is specially handy for developing new code since it allows one to debug parallel algorithms by running an emulated distributed computation in a standard (sequential) Julia session and using standard serial debuggers. Once the code works with the emulated parallel mode, it can be automatically deployed in a supercomputer via an MPI back-end implemented for this purpose. Thus, the package provides a very convenient way of developing parallel algorithms, while achieving the performance of MPI-based applications. This will help to develop new parallel FE methods in a very effective way. In particular, PhD students not necessarily experts in the MPI library can benefit from this framework to develop their parallel algorithms. At this moment, I have been able to solve the Poisson equation with up to 1B cells on 16K processors with GridapDistributed.jl on Gadi (an Australian super-computer) and I expect to further mature and extend the capabilities of this library.

###### Leveraging the Gridap.jl ecosystem to solve problems in science and engineering.

Several researchers have already realized the potential benefits of using the Gridap.jl framework for their applications and have asked to me for collaboration. My plan is to keep growing a network of scientific collaborators that use the library in several contexts, in order to increase my changes of publishing more research papers and to find relevant topics for preparing project proposals.

## Post-doctoral research at TUM (2013-2015)

In this post-doc stay, I have developed parallel AMG solvers for the solution of large systems of linear algebraic equations associated with the FE discretization of complex multi-physics problems. The main goal of this research was to provide a general framework able to be applied to several problem types. In particular, this work was applied to fluid-structure interaction (FSI), thermo-mechanical coupling, and human respiratory mechanics among others.

### General framework for the solution of coupled problems with monolithic schemes

The numerical simulation of coupled problems via discretization techniques such as the FE method requires special solution strategies for solving the coupling between the underlying physical fields. The so-called partitioned methods [felippa_2001] are often the preferred choice in industrial applications because they allow to reuse existing (black-box) solvers for the individual fields. However, this approach is unstable for many challenging strongly coupled problems [forster_2007] and, therefore, another family of methods called monolithic are required in a variety of complex settings. It has also been shown that monolithic schemes are often preferable in terms of efficiency as compared to partitioned ones. For that reason, this approach has been the preferred option for solving many strongly coupled problems in the literature. However, the price to be paid for the extra robustness of monolithic methods is a more challenging system of linear equations. The system matrix is a big sparse matrix with a special block structure representing each of the underlying physical fields and frequently has a very bad condition number. In real-world applications, iterative methods such as GMRES are used to attack this linear system, which requires efficient preconditioners for addressing the bad conditioning of the problem. Selecting a suitable preconditioner is the key point in the solution process.

The standard approach to design preconditioners for coupled problems is to use approximated block inverses in order to untangle the coupling between the physical fields, and then, to use efficient AMG solvers for the resulting uncoupled problems. The drawback of these methods is that the coupling is resolved only at the finest grid level. Thus, using efficient AMG solvers for the underlying problems does not necessarily imply a good treatment of the coupling and a fast global solution. This drawback is overcome by Gee et al. [gee_2011], who propose an enhanced block preconditioner (referred to as monolithic AMG) for FSI applications, which enforces the coupling at all grid levels, and often results in a better solver performance. Monolithic AMG preconditioners are a promising approach for other coupled problems as well but, this strategy was only applied to FSI. In order to allow the usage of this enhanced AMG methods for a wide range of problem types, I have developed an general computational framework based on monolithic AMG techniques. For comparison purposes, conventional AMG solvers were also included. The method was implemented in the high performance multi-physics code BACI and it was published in a Q1 journal (see reference [verdugo_2016a]). This framework has been used at TUM since then, and it has been considered by several papers in top international journals (see, e.g., [kremheller_2018][fang_2018]), with a wide range of applications including simulation of vascular tumor growth and simulations of lithium ion cells.

### Solvers for the thermo-mechanical coupling in rocket nozzles

In the framework of the German research project "Fundamental Technologies for the Development of Future Space-Transport-System Components under High Thermal and Mechanical Loads", I have applied the general linear solver framework to the simulation of the thermo-mechanical coupling in rocket nozzles. I exemplary show here the performance of the developed preconditioners. The nozzle geometry (see Figures 7 and 8) and other problem parameters are inspired by the "Vulcain" rocket engine installed in the Ariane space launcher, see [verdugo_2016a] for further details.

Figure 7: Rocket nozzle example: Full geometry of the nozzle (left), computational domain including one cooling channel (center), and generic cross section of the computational domain with the applied thermo-mechanical loads (right)

Figure 8: Rocket nozzle example: Deformation of the nozzle (left), temperature distribution (center) and original and deformed longitudinal section (right). The results are given at time $t=1$ s and the deformation is magnified 20 times.

After the usual space and time discretization, the simulation results into a non-linear problem to be solved at each time step, which is handled with a monolithic Newton scheme. At each Newton iteration, the associated monolithic linear system of equations is solved with a GMRES method preconditioned with four different solvers available in our computational framework. The first method, namely BGS(AMG), considers an outer block Gauss-Seidel (BGS) scheme for uncoupling the fields and then independent AMG solvers are used to handle the thermal and mechanical problems separately. The second method, namely SIMPLE(AMG), is a similar method that considers an idea based on the SIMPLE method [elman_2008] for uncoupling the fields instead of BGS. The third method, namely AMG(BGS), is an extension of the monolithic AMG solver to a generic coupled problem. Finally, the fourth method, namely BGS(DD), is an outer BGS for uncoupling the fields and then standard single-level additive Schwartz preconditioners are used to attack the uncoupled problems. The fourth method is one of the most simple parallel preconditioners that can be considered in such a problem, and therefore, it is considered here as a reference. All this solvers could be built easily by means of parameter lists using the general preconditioning framework.

Figure 9: Rocket nozzle example: Results of the weak scalability study. The CPU times include the setup costs of the preconditioner.

The performance of the preconditioners is studied with a weak scalability test, see Figure 9. In this experiment, the ratio between processors and DOFs is kept constant with a value about 12500 DOF/processor. The multi-grid methods AMG(BGS), BGS(AMG) and SIMPLE(AMG) have a very good scalability as the iteration count and CPU time of the linear solver increase only mildly with the problem size. On the other hand, the single-level method BGS(DD) is not scalable since the solver time strongly grows as the problem size increases. The performance of the single-level method BGS(DD) is particularly poor in this complex example which demonstrates that multi-grid preconditioners such as AMG(BGS), BGS(AMG) and SIMPLE(AMG) are required in this challenging setting. In conclusion, the AMG solvers implemented in our generic computational framework were able to solve this complex example efficiently.

### Efficient solvers for respiratory mechanics

Another application of the general linear solver framework has been the simulation of human respiratory mechanics. In recent years, advances have been made towards more protective ventilation strategies [tobin_2001] trying to minimize negative side effects of the treatment, but it is still not fully clear what is the best ventilation strategy for a specific patient. Advanced modeling and simulation offer the possibility of predicting the mechanical response of the respiratory system under different ventilation scenarios, and give an opportunity to design better patient-tailored treatments. However, simulating the human lung poses several computational challenges including large and multiply coupled systems of linear equations. Thus, the underlying motivation of this work is to enable the efficient simulation of virtual lung models on high-performance computing platforms in order to assess mechanical ventilation strategies and contributing to design more protective patient-specific ventilation treatments.

Figure 10: Patient-specific lung example: Numerical solution of the lung model consisting of the structural displacement (left), fluid pressure (center) and fluid velocity (right) at time $t=0.75$ s.

The system of linear equations to be solved in this application is essentially the monolithic system arising in FSI extended by additional algebraic constraints. The introduction of these constraints leads to a saddle point problem that cannot be solved with usual FSI preconditioners available in the literature. The key ingredient in this work is to use the idea of the semi-implicit method for pressure-linked equations (SIMPLE) for getting rid of the saddle point structure, resulting in a standard FSI problem that can be treated with available techniques. Even though the lung model is a complex multi-physics problem (see Figure 10), the numerical examples show that the resulting preconditioners approaches the optimal performance (see Figure 11). Moreover, the preconditioners are robust enough to deal with physiologically relevant simulations involving complex real-world patient-specific lung geometries. The same approach is applicable to other challenging biomedical applications where coupling between flow and tissue deformation is modeled with additional algebraic constraints. This work has lead to 1 paper in a Q1 journal (see reference [verdugo_2016b]). In the framework of this research, I have been junior co-PI in the Bavarian regional project "Efficient solvers for coupled problems in respiratory mechanics".

Figure 11: Patient-specific lung example: Results of the strong scalability test. The figure shows the dependence of the linear solver iterations with respect to the number of processors (left), and the parallel speed up (right).

## Early-stage research at UPC (2009-2013)

### PhD thesis overview

My PhD thesis, entitled "Error assessment and adaptivity for structural transient dynamics", is devoted to the development of new automatic adaptive mesh refinement tools and goal-oriented error assessment techniques in the context of structural dynamics. Any FE based simulation has an intrinsic amount of error with respect to the exact solution of the selected physical model. Being aware of this error is of notorious importance if sensitive engineering decisions are taken on the basis of the numerical results. Assessing the error in elliptic problems (as structural statics) was a well known problem at the time of this PhD thesis. However, assessing the error in other more challenging problem types such as structural transient dynamics was an open research topic. In this context, most of the works provided a posteriori error estimates of the energy norm of the discretization error. The challenge was to develop so-called goal-oriented error estimates for this application. That is, a posteriori approximations of the error in a given quantity of interest of the underlying physical problem. This goal-oriented error estimation is specially well suited for real-world industrial applications since it provides information of the quality of the computed solution in the targeted quantities instead of a global function norm.

The main contributions of the PhD thesis are 1) the introduction of a novel technique to compute bounds of the (unknown) discretization error in a given quantity of interest (see reference [verdugo_2012]), 2) a goal-oriented space-time adaptive mesh refinement method specifically designed for efficiency in transient problems (see references [casadei_2013][verdugo_2014a]), and 3) a novel paradigm for error estimation in transient problems based on a new type of quantities of interest (see reference [verdugo_2013]). I published a review paper with my main thesis results (see reference [verdugo_2014b]) in the "Archives of Computational Methods in Engineering", which is the 1st ranked journal in the category "mathematics, interdisciplinary applications" of the Journal Citation Reports (JCR) in the year of publication. In the following, I briefly introduce items 2) and 3), which are the major thesis novelties.

Goal-oriented error estimation and adaptivity is particularly challenging in time-dependent problems. Assessing the error in the quantity of interest requires introducing an auxiliary problem, referred to as the adjoint or dual problem [becker_2001]. The main difficulty is associated with the fact that the adjoint solution has to be solved backwards in time. This means that, in order to assess the error by weighting the residual of the direct (or forward) solution with the adjoint (or backward) solution, at least one of the two solutions have to be stored in the full time-space domain. In non-linear problems, the situation is even worse because the full forward problem has to be computed and stored to define the backwards adjoint. This means that assessing the error of each iteration of the forward problem potentially requires computing a different backward adjoint. The conventional approach to alleviate the storage requirements is to use checkpointing, where the forward solution is stored only at a small number of pre-selected time points. These stored snapshots are used as initial conditions on each sub-interval for recomputing the forward solution during the backwards adjoint computation. This approach mitigates the storage requirements, but for some applications, recomputing the forward solution repeatedly can be still too expensive.

Figure 12: Simulation of elastic waves propagating in a perforated plate. The underlying space-time discretization has been automatically adapted using the goal-oriented error estimators in [verdugo_2013]. A smaller number of mesh elements are required with the adapted meshes than with uniform discretizations in order to achieve the same level of accuracy.

In the thesis, I have proposed an alternative approach based on a well known technique for structural dynamics: modal analysis. The modal-based strategy is particularly well suited for computing the adjoint problem associated with some particular quantities of interest. Following this approach, the adjoint solution is computed and stored for each vibration mode instead of for each time step, which reduces the storage requirements enormously. Using this novel approach, one can compute efficiently local error indicators that for each element and time step in the chosen discretization. This information can be used to automatically increase the resolution of the space and time discretizations only in the regions, where it is actually needed, leading to efficient computations (see Figure 12).

### A novel a-posteriori error estimation paradigm based on time-dependent quantities of interest

Virtually all the literature on goal-oriented a posteriori error assessment is based on scalar quantities of interest. While this approach is well suited for steady-state problems, a single scalar value does not give enough pieces of information about a complex space-time solution. For this reason, the preferred quantities of interest in time-dependent problems are typically the history (or evolution) of the space average of the solution in a sub-region of the domain, which are referred to as time-line dependent quantities of interest [verdugo_2013]. At the time of this PhD thesis, there was no error estimation method for this kind of quantities in the literature. One of the main thesis contributions is a new paradigm for a posteriori error estimation using this new type of quantities of interest.

As already announced, in conventional goal-oriented error assessment in a given scalar quality, one needs to introduce and solve an adjoint problem. Dealing with time-line dependent quantities is much more challenging. A time-line dependent quantity can be understood as a family of infinite scalar quantities (one for each time point in the selected computation time interval). Thus, one needs the solution of a family of infinite adjoint problems. This is computationally un-affordable in practice. However, for a number of meaningful cases, I have mathematically proven in reference [verdugo_2013] that all this adjoint problems are the equivalent after a translation of the time variable. This fundamental result is the crucial observation that allows one to assess the error in the time-line dependent quantities with an affordable cost. In addition, using a modal-based approximation of the adjoint problem allows one to accurately estimate the error in this new type of quantities in an efficient way (see Figure 13).

Figure 13: Error estimation of a time-line dependent quantity of interest (in this case the time-evolution of the averaged displacement at region $\Gamma_g$). Note that by approximating the family of adjoint problems associated with this quantity using only 60 vibration modes, an accurate estimation of the numerical error is achieved.

## References

[badia_2016] S. Badia, A.F. Martín, and J. Principe. Multilevel Balancing Domain Decomposition at Extreme Scales. SIAM Journal on Scientific Computing, 38(1): C22–C52, 2016. DOI: 10.1137/15M1013511.

[badia_2017] S. Badia and F. Verdugo. Robust and scalable domain decomposition solvers for unfitted finite element methods. Journal of Computational and Applied Mathematics, 344: 740–759, 2018. DOI: 10.1016/j.cam.2017.09.034.

[badia_2018a] S. Badia, F. Verdugo, and A.F. Martín. The aggregated unfitted finite element method for elliptic problems. Computer Methods in Applied Mechanics and Engineering, 336: 533–553, 2018. DOI: 10.1016/j.cma.2018.03.022.

[badia_2018b] S. Badia, A.F. Martín, and F. Verdugo. Mixed Aggregated Finite Element Methods for the Unfitted Discretization of the Stokes Problem. SIAM Journal on Scientific Computing, 40(6): B1541–B1576, 2018. DOI: 10.1137/18M1185624.

[badia_2019a] S. Badia, A.F. Martín, E. Neiva, and F. Verdugo. A generic finite element framework on parallel tree-based adaptive meshes. SIAM Journal on Scientific Computing, 42(6): C436–C468, 2020. DOI: 10.1137/20M1328786.

[badia_2020] S. Badia and F. Verdugo. Gridap: An extensible Finite Element toolbox in Julia. Journal of Open Source Software, 5(52), 2020. DOI: 10.21105/joss.02520.

[badia_2021] S. Badia, A.F. Martín, E. Neiva, and F. Verdugo. The aggregated unfitted finite element method on parallel tree-based adaptive meshes. SIAM Journal on Scientific Computing, 43: C203–C234, 2021. DOI: 10.1137/20M1344512.

[becker_2001] R. Becker and R. Rannacher. An optimal control approach to a posteriori error estimation in finite element methods. Acta Numerica, 10: 1–102, 2001. DOI: 10.1017/S0962492901000010.

[briggs_2000] W.L. Briggs, V.E. Henson, and S.F. McCormick. A Multigrid Tutorial, Second Edition. Society for Industrial and Applied Mathematics, 2000. DOI: 10.1137/1.9780898719505.

[burman_2015] E. Burman, S. Claus, P. Hansbo, M.G. Larson, and A. Massing. CutFEM: Discretizing Geometry and Partial Differential Equations. International Journal for Numerical Methods in Engineering, 104(7): 472–501, 2015. DOI: 10.1002/nme.4823.

[casadei_2013] F. Casadei, P. Díez, and F. Verdugo. An algorithm for mesh refinement and un-refinement in fast transient dynamics. International Journal of Computational Methods, 10(04): 1350018, 2013. DOI: 10.1142/S0219876213500187.

[cottrell_2009] J.A. Cottrell, T.J.R. Hughes, and Y.Bazilevs. Isogeometric analysis: toward integration of CAD and FEA. Wiley, 2009. DOI: 10.1002/9780470749081.ch7.

[elman_2008] H. Elman, V.E. Howle, J. Shadid, R. Shuttleworth, and R. Tuminaro. A taxonomy and comparison of parallel block multi-level preconditioners for the incompressible Navier-Stokes equations. Journal of Computational Physics, 227(3): 1790–1808, 2008. DOI: 10.1016/j.jcp.2007.09.026.

[fang_2018] R. Fang, P. Farah, A. Popp, and W.A. Wall. A monolithic, mortar-based interface coupling and solution scheme for finite element simulations of lithium-ion cells. International Journal for Numerical Methods in Engineering, 114(13): 1411–1437, 2018. DOI: 10.1002/nme.5792.

[felippa_2001] C.A. Felippa, K.C. Park, and C. Farhat. Partitioned analysis of coupled mechanical systems. Computer Methods in Applied Mechanics and Engineering, 190(24-25): 3247–3270, 2001. DOI: 10.1016/S0045-7825(00)00391-1.

[forster_2007] C. Förster, W.A. Wall, and E. Ramm. Artificial added mass instabilities in sequential staggered coupling of nonlinear structures and incompressible viscous flows. Computer Methods in Applied Mechanics and Engineering, 196(7): 1278–1293, 2007. DOI: 10.1016/j.cma.2006.09.002.

[gee_2011] M.W. Gee, U. Küttler, and W.A. Wall. Truly monolithic algebraic multigrid for fluid-structure interaction. International Journal for Numerical Methods in Engineering, 85(8): 987–1016, 2011. DOI: 10.1002/nme.3001.

[kremheller_2018] J. Kremheller, A.T. Vuong, L. Yoshihara, W.A. Wall, and B.A. Schrefler. A monolithic multiphase porous medium framework for (a-)vascular tumor growth. Computer Methods in Applied Mechanics and Engineering, 340: 657–683, 2018. DOI: 10.1016/j.cma.2018.06.009.

[tobin_2001] T. Martin. Advances in mechanical ventilation. The New England Journal of Medicine, 344(26): 1986–1996, 2001. DOI: 10.1056/NEJM200106283442606.

[toselli_2005] A. Toselli and O. B. Widlund. Domain Decomposition Methods — Algorithms and Theory, volume 34 of Springer Series in Computational Mathematics. Springer Berlin Heidelberg, Berlin, Heidelberg, 2005. DOI: 10.1007/b137868.

[verdugo_2012] F.~Verdugo and P. Díez. Computable bounds of functional outputs in linear visco-elastodynamics. Computer Methods in Applied Mechanics and Engineering, 245–246: 313–330, 2012. DOI: 10.1016/j.cma.2012.06.016.

[verdugo_2013] F. Verdugo, N. Parés, and P. Díez. Modal-based goal-oriented error assessment for timeline-dependent quantities in transient dynamics. Int. J. Numer. Meth. Engng., 95(8): 685–720, 2013. DOI: 10.1002/nme.4538.

[verdugo_2014a] F. Verdugo, N. Parés, and P. Díez. Goal-oriented space-time adaptivity for transient dynamics using a modal description of the adjoint solution. Comput. Mech., 54(2): 331–352, 2014. DOI: 10.1007/s00466-014-0988-2.

[verdugo_2014b] F. Verdugo, N. Parés, and P. Díez. Error Assessment in Structural Transient Dynamics. Archives of Computational Methods in Engineering, 21(1): 59–90, 2014. DOI: 10.1007/s11831-014-9096-x.

[verdugo_2016a] F. Verdugo and W.A. Wall. Unified computational framework for the efficient solution of n-field coupled problems with monolithic schemes. Computer Methods in Applied Mechanics and Engineering, 310: 335–366, 2016. DOI: 10.1016/j.cma.2016.07.016.

[verdugo_2016b] F. Verdugo, C.J. Roth, L. Yoshihara, and W.A. Wall. Efficient solvers for coupled models in respiratory mechanics. International Journal for Numerical Methods in Biomedical Engineering, 2016. DOI: 10.1002/cnm.2795.

[verdugo_2019] F. Verdugo, A.F. Martín, and S. Badia. Distributed-memory parallelization of the aggregated unfitted finite element method. Computer Methods in Applied Mechanics and Engineering, 357, 2019. DOI: 10.1016/j.cma.2019.112583.


text:
# Cyclotron resonance

## Homework Statement

Calculate the lower limit of the electron scattering time in a material placed in a magnetic field of 1 T which is necessary to observe cyclotron resonance. The electron effective mass in the material
is 0.06 ##m_o## (where ##m_o## is the free electron mass).

## Homework Equations

##\omega_c=\frac{eB}{0.06m_o}##
##\tau_{min}=\frac{2\pi}{\omega_c}##

## The Attempt at a Solution

So I basically substituted values into ##\omega_c## and then into the equation for ##\tau_c## i got ##\tau_c=2.14ps## whereas the answer says ##\tau_c=0.54ps##, have I gone wrong? or is the solution given wrong, because i have done it multiple times.


text:
# All Questions

211 views

### How can one encrypt with RSA (or ElGamal) without revealing whom the ciphertext is intended for?

Imagine Alice wants to encrypt for Bob and post this encryption publicly, so that only Bob can decrypt but no one can other than Alice or Bob tell that the message was encrypted for Bob. The naive ...
2k views

### how to use common modulus attack?

I am struck with the following problem: Let Alice, Bob, Chris and Eve communicate over a public network. They encrypt all messages they send using RSA system. Bob and Chris have the RSA modulus ...
612 views

### Perfect Forward Secrecy with NaCl

I would like to use the NaCl cryptography library (or TweetNaCl), but I would very much like to have perfect forward secrecy for my application. From what I understand, all Bob needs to to decrypt a ...
194 views

### Advantages to knowing $p$ and $q$ in Blum Blum Shub?

Do you gain any advantage by knowing the factorization of $M$ (over just knowing $M$ itself) in the Blum Blum Shub generator? The only advantage I see is being able to calculate the $i$-th number ...
287 views

### Is C25519/Ed25519 “twist secure”?

This recent new curve mentions something that's new to me: twist security. http://safecurves.cr.yp.to/bada55.html Are the existing C25519/Ed25519 curves secure against this form of attack?
195 views

### ElGamal digital signature. why mod p-1 in delta?

Im trying to figure out why $\delta$ in the signature part of ElGamal has mod $p-1$ when $\gamma$ has mod $p$? $\gamma = \alpha^k \mod p$ $\delta = (x-a\gamma)k^{-1} \mod p-1$
72 views

### How exactly are PRNG's used to encrypt material, and what makes one any more secure than the other?

I hope my question isn't as lazy as the title indicates. What I want to ask is how people literally integrate a PRNG with encrypting material. I wrote a silly little script in Python a while back ...
74 views

### Knapsack Public to Private (Superincreasing knapsack)

I need to convert a hard knapsack to a superincreasing knapsack. I have these superincreasing values (3,6,11,22,43,87). I also have w = 7 and n = 173. I converted the superincreasing values to hard ...
124 views

### Ed25519 with R replaced by H(RAM)?

Ed25519 signatures consist of $(R, s)$, where $s = r + H(RAM)a$ $mod$ $l$, and $R = rB$. This differs from the Schnorr signature where instead of $R$, the signature contains the hash $h=H(RAM)$. ...
165 views

### Is it possible to find data which makes sense when decrypted with different keys?

In theory, does a piece of data exist which, when encrypted (using any method) with a given key, makes some sense when decrypted with the wrong key? Here, a definition of "some sense" might be ...
221 views

### Building a stream-cipher out of a hash function?

I've already read this: Is it feasible to build a stream cipher from a cryptographic hash function? However, my proposed construction differs… Suppose the hash generates N bits. These bits are split ...
572 views

146 views

### Is it possible to construct a secure block cipher of size $2n$ given a secure block cipher of size $n$?

Given, say, the Blowfish block cipher, which is considered secure but only has a 64-bit block size, can we construct a secure block cipher of 128-bit block size? Say we run the key through two KDFs, ...
106 views

### RSA private exponent primality

I know that the public exponent is always a prime, but what about the private exponent? Is it always a prime too?
124 views

### Is there a number of tries after which Hashcash is guaranted to be solved?

Hashcash is a proof-of-work system in which the Sender needs to find $Y$ such as the first (let's say 20) bits of $H(X+Y)$ are zeros where $H$ is a one-way hash function, $X$ is a fixed value and $+$ ...
826 views

### Is AES key length a size of the key or entropy?

While educating my self I'm having hard time to understand what an 128 bit AES key actually means? Is it a key length or entropy? Please explain to me trough following example (assuming AES): ...
1k views

### Problems with using AES Key as IV in CBC-Mode

I'm a pentester and currently analysing a web application which are using some strange encryption scheme. The point is: They encrypt using AES-128, generate a (not cryptographic secure) key and use ...
186 views

### Breaking RSA when some bits of one prime are known

RSA primes are 100 bit. You know first 80 bits of one of the primes. In this system, come up with an efficient way to decrypt the cipher-text. This was the question on my quiz. I'm not sure how ...
1k views

### What are Cryptographic Multi-linear Maps?

I've encountered this term many times in the fields of Fully-Homomorphic Encryption and Obfuscation. I want to learn those subject and Cryptographic Linear Maps seems to be an obstacle in the way. ...
2k views

### ECDSA vs RSA: Performance on Android platform and surprising results

For our privacy-preserving protocol, an encrypted channel is established. In order to protect our system from man-in-the-middle attacks, signature-based approach is used. After we've implemented it ...
41 views

### What constitutes a “description of B” for probabilistic encryption as defined in Cryptology 6.3.4?

On page 21 of the Rivest's Cryptology chapter, he defines a trapdoor predicate as a boolean function for which it is easy to choose an x such that ...
63 views

### Special random distribution algorithm

I am implementing ring signatures as a part of an authorization system. Since the number of users could get high enough to make computation on end-user devices infeasible, I am thinking of ...
315 views

### Are hash functions chaotic?

I'm looking into "bitcoin like" mining processes. Say a security process uses a hash of data as proof that the data was known at some point in time. From what I understand, hash functions are ...
744 views

### How to solve cipher encrypted with Vigenère + Columnar Transposition?

Vigenère's weakness is Kasiski's test and index of coincidence. However, if you put columnar transposition on top of Vigenère, that weakness is gone. The text is now shuffled and you can't search for ...
106 views

### RSA Key Blinding

I was looking the answer to the following question (Timing attack on modular exponentiation), discussing the Private Key Blinding as a countermeasure for timing attacks. Therefore I'm asking if ...
Use case: I have a random number generator that can generate random numbers in a range that is limited by a number $x$, say $x$ ranges from $2$ to $2^{(n - 1)} - 1$ exclusive. In this case $n$ is ...


text:
# How far would a radio signal propagate in free space as compared to Earth's atmosphere?

A curiosity question.

Radio Propagation within Earth's atmosphere is via atmosphere. Broadly speaking a signal loses strength between bouncing off the ionized layer, and absorption by various earthy elements.

If an identical signal were to be produced in free space, how far would it travel as compared to it's range within Earth's atmosphere?

EDIT: A commercial FM transmitter on Earth probably has a range no more than 25 miles where the listener uses a broadcast receiver. For the purpose of elaboration assume the the receiver being placed in static orbit - how far out could the same signal be generated, and still be intelligible?

-
I wonder how information is conveyed to satellites.(THIS is an answer to your question) –  Nix Jul 9 '13 at 12:12
Another thing to think about: The spacecraft 'Voyager 1' was launched in 1977. It is now at a distance of $1.866 × 10^{10}$km, and it communicates to the earth by means of radio signals. –  mikhailcazi Jul 9 '13 at 12:36
The question is ill-posed. You don't specify noise conditions, receiver sensitivity, and initial signal's ERP to get a sensible answer as to the maximum ranges at which both signals will be detected. –  Deer Hunter Jul 9 '13 at 12:42
The main problem in radio communications is being able to recover the transmitted signal from the received, noisy signal; and it is mainly a channel coding problem. also, because the distances between spacecrafts (or stations, etc.)in space are very large, the transmission power is not too important and the successful communication depends on error-correction methods used. –  Mostafa Jul 9 '13 at 12:47
@mikhailcazi: The Voyagers use the Deep Space Network; apparently using PSK. My query is about the range of a system in space relative to the range of the same system on Earth. –  Everyone Jul 10 '13 at 1:28

## 1 Answer

First, no, "radio propagation" is not "via atmosphere". Different wavelengths get absorbed, reflected, or simply passed by different parts of the atmosphere. There is no one general rule. Many of our radio communications within the atmosphere are pretty much like they would be in free space, for example.

Second, all radio waves propagate infinitely in free space. There is no finite end to the propagation. What does matter in a practical sense is signal to noise ratio. Below some signal to noise ratio for whatever information encoding scheme is used, that information can't be recovered. Or more accurately, the error rate goes up as the signal to noise ratio goes down. At some point the errors in the information make is useless or "unreceivable" in a practical sense.

## Added:

You are now asking specifically about "commercial FM", which I take to mean radio at around 100 MHz (3 meter wavelength). The primary mechanism limiting reception distance of such commercial FM stations is the curvature of the earth. The wavelength is too short for significant refraction around the earth, as happens with commercial AM at around 1 MHz (300 meters). Note that when you are in a car listening to a FM station at the fringe of its range, it will come and go as you get to tops of hills or dip between them.

Another factor is that here on earth there is significant interference from all kinds of unintentional broad-band radiators. Eventually at some distance the intended signal becomes too small relative to this background noise for the signal to be picked up well enough for your liking.

In the end, there are no hard limits and reception is about signal to noise ratio. That means you can extend the useful range of a transmission by reducing noise or selectively amplifying the signal. Note that spaceprobes usually emit only a few Watts or tens of Watts, whereas commercial FM stations usually a few kW. One important difference is that spaceprobe signals are picked up with highly directional antennas and extra low noise receivers. You wouldn't want to pay for one of those receivers in your car. The narrow beam of the receiving antenna greatly increases signal to noise ratio. Since the signal is coming from a point, the same signal is still picked up along a narrow beam. But, only a tiny fraction of the noise that is coming from all around is picked up along that same beam.

-
Pretty close to the answer I wished to learn; I've elaborated on the question a bit ... –  Everyone Jul 10 '13 at 1:46
Hm.. the reference to an FM signal was merely for the purpose of illustration –  Everyone Jul 10 '13 at 16:29


text:
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

# NAG Library Routine DocumentF06FRF

Note:  before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

## 1  Purpose

F06FRF generates a real elementary reflection in the NAG (as opposed to LINPACK) style.

## 2  Specification

 SUBROUTINE F06FRF ( N, ALPHA, X, INCX, TOL, ZETA)
 INTEGER N, INCX REAL (KIND=nag_wp) ALPHA, X(*), TOL, ZETA

## 3  Description

F06FRF generates details of a real elementary reflection (Householder matrix), $P$, such that
 $P α x = β 0$
where $P$ is orthogonal, $\alpha$ and $\beta$ are real scalars, and $x$ is an $n$-element real vector.
$P$ is given in the form
 $P=I- ζ z ζ zT ,$
where $z$ is an $n$-element real vector and $\zeta$ is a real scalar.
If $x$ is such that
 $maxxi≤maxtol,εα$
where $\epsilon$ is the machine precision and $\mathit{tol}$ is a user-supplied tolerance, then $\zeta$ is set to $0$, and $P$ can be taken to be the unit matrix. Otherwise $1\le \zeta \le \sqrt{2}$.

None.

## 5  Parameters

1:     N – INTEGERInput
On entry: $n$, the number of elements in $x$ and $z$.
2:     ALPHA – REAL (KIND=nag_wp)Input/Output
On entry: the scalar $\alpha$.
On exit: the scalar $\beta$.
3:     X($*$) – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least $\mathrm{max}\phantom{\rule{0.125em}{0ex}}\left(1,1+\left({\mathbf{N}}-1\right)×{\mathbf{INCX}}\right)$.
On entry: the $n$-element vector $x$. ${x}_{\mathit{i}}$ must be stored in ${\mathbf{X}}\left(1+\left(\mathit{i}-1\right)×{\mathbf{INCX}}\right)$, for $\mathit{i}=1,2,\dots ,{\mathbf{N}}$.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the real elementary reflection.
4:     INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of $x$.
Constraint: ${\mathbf{INCX}}>0$.
5:     TOL – REAL (KIND=nag_wp)Input
On entry: the value $\mathit{tol}$.
6:     ZETA – REAL (KIND=nag_wp)Output
On exit: the scalar $\zeta$.

None.

Not applicable.


text:
# Find unique range numbers

im using the following code which is working. The code provide range of random values but unique one i.e. it doesn't return the same values until the full range was provided ,what do you think and doest in ES6 there is shorter way to achieve this?

var range = [10, 20];
var not = [];

function randomRange(range, n) {
if (not.length >= range[1] - range[0]) {
not.length = 0;
}
var curr = [];
var res = [];
for (let i = range[0]; i < range[1]; i++) {
if (!not.some(function(num) {
return i == num
}) && not.length < range[1] - range[0]) {
curr.push(i)
}
}
for (let i = 0; i < n; i++) {
var j = curr.splice(Math.floor(Math.random() * curr.length), 1)[0];
res[i] = not[not.length] = j;
}

return res.filter(Boolean)
}

function log(result) {
document.body.innerHTML += JSON.stringify(result) + "<br>"
}

log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
}

### Confusing API

The current API is a bit confusing. range is a parameter of randomRange, but in the usage example you gave you always call the function with the same range value. It's unclear if you ever intend to call it with a different value. And if you do, it's unclear what realistic purpose it could serve. The behavior would seem rather chaotic.

Also note that the current API and the global not variable prevents you from using multiple different random ranges at the same time.

Instead of making range a parameter of randomRange, it would be better to use it once for initialization, and store it in an internal data structure not accessible from outside.

An array seems a strange choice for storing two values. Instead of range as an array, why not use simply start and end variables?

### Fragile implementation

The implementation is very fragile. not is quite crucial for the inner workings of the randomRange function, but it's easily accessible in the global namespace, making it vulnerable to accidental or malicious modifications.

### Performance

The current implementation is inefficient. On each call, it scans the range and populates curr with values that are not in not, and then selects random values from curr. It would be better to shuffle the range of values, splice from the shuffled range, and reshuffle when it's emptied.

### Alternative implementation

Consider this alternative implementation that solves all the above issues:

var shuffle = function(arr) {
for (let i = arr.length - 1; i > 0; i--) {
let target = nextInt(i + 1);
swap(arr, i, target);
}
};

var swap = function(arr, i, j) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
};

var nextInt = function(bound) {
if (bound === undefined) {
bound = Number.MAX_SAFE_INTEGER;
}
return Math.floor(bound * Math.random());
};

var recyclingRandomRange = function(start, end) {
var range = [];
var resetRange = function() {
for (let i = start; i < end; i++) {
range.push(i);
}
shuffle(range);
};

return function(n) {
if (range.length === 0) {
resetRange();
}
return range.splice(0, n);
};
};

This usage would be equivalent to your example:

var ranger = recyclingRandomRange(10, 20);
log(ranger(3));
log(ranger(3));
log(ranger(3));
log(ranger(3));
log(ranger(3));
log(ranger(3));
log(ranger(3));

• Thank you very much, the only problem I see it that I need to get an array and this return diff structure, how it should be adapt? – John Jerrby Dec 7 '16 at 7:07
• I don't understand what you mean. The ranger(n) function returns an array. – janos Dec 7 '16 at 7:25
• sorry :-) my mistake , 2 point 1. does with lodash/es6 the code can be more readable/clean (we use it in our framework, my fault that I didn't mention it ...2. I use the function like the following recyclingRandomRange(10,20)(3) to provide data , I didnt use function like this before is it ok? – John Jerrby Dec 7 '16 at 7:37
• I don't know if lodash has some utilities to shuffle or get random integers. If yes then you could use those instead of these home-made shuffle and nextInt. On the other hand, these are simple enough, and give you independence and flexibility. As for recyclingRandomRange(10,20)(3), that's legal, but I don't think you want to do that. Repeated calls to recyclingRandomRange(10,20)(n) don't share the tracking of already used numbers. If you want that tracking, you need to use like in my example at the end. – janos Dec 7 '16 at 10:57

If what you want is to call the same function with the same array and obtain random numbers from that array every time, but without them repeating, well, that's almost literally the definition of "shuffle".

Have a look at this answer on stackoverflow. The idea in your case is that you shuffle the array and pick the first (or last) n elements.

function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;

while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}

return array;
}

var arr = [];
for (var i = 10; i <= 20; i++) {
arr.push(i);
}
shuffle(arr);
console.log(arr.slice(0,3));
console.log(arr.slice(3,6));

The advantage is that you need to randomize only once, no need to loop through the array and generate random numbers every time.

The disadvantage is that if you want different numbers, you'll have to keep track of the index by yourself, because requesting arr.slice(0,3) will always return the same numbers. But considering that you'd have to keep track of which numbers have already been used anyway, this should not be a problem.

Also, this may actually not be a disadvantage depending on what you use the function for. (Of course you could shuffle every time, but that would lose any speed benefit of shuffling).

Another approach would be to shuffle once and then having a function that returns the first n numbers but also removes them from the list. The obvious disadvantage in that case would be that you have to keep a copy of your original array, and when the shuffled array is empty, copy it and shuffle it again.

If you still want to use your approach (which works anyway), at least make sure to use meaningful variable names. In my opinion not is probably the worst possible name for a variable.


text:
# Tag Info

0

After inspecting the code, I could get through the compilation by commenting \ressubheading{My High School}{Hick Town, ON}{High School Diploma}{2000 - 2004} for which the entry part code was \begin{tabular*}{6.5in} {l@{\cftdotfill{\cftsecdotsep}\extracolsep{\fill}}r} \textbf{#1} & #2 \\ \textit{#3} & \textit{#4} \\ ...

1

The real problem is earlier. If you replace the line, where IIT Madras Logo is called (line 68 of the original template), e.g. as in the example, everything works OK. (You don't have this logo, I suppose.) % (c) 2002 Matthew Boedicker <mboedick@mboedick.org> (original author) http://mboedick.org % (c) 2003-2007 David J. Grant ...

2

I also encountered this problem while trying to achieve exactly the same thing as you with the Friggeri template. This problem comes from a bug with the pdf engine of XeLaTex with OTF font file format when it is at a particular resolution as discussed in http://typophile.com/node/46451. As a workaround, you can use the .ttf version of the font. To do this, ...

3

You need \newenvironment{aside}{% \noindent %% added \begin{minipage}[t]{0.25\textwidth}% \begin{flushright} }{% \end{flushright}% \end{minipage}% } \newenvironment{main}{% \noindent \begin{minipage}[t]{\dimexpr0.75\textwidth-1pt-2em\relax}% %% modified }{% \end{minipage}% } and \end{aside}% %% % here is badly needed % ...

1

You have parindent+0.25\textwidth+1em+\space+1em+\space+0.75\textwidth=\textwidth+parndent+2em+2\space > textwidth Try redifine your environment like this Edit: thanks to Harish Kumar's answer i add \ignorespaces \newenvironment{aside}{\noindent \begin{minipage}[t]{0.25\textwidth} \begin{flushright} }{ \end{flushright} ...

1

Use tabulars like this \address{% \begin{tabular}{@{}l} Address 123\\ 222 22 City \\ 123 123 \end{tabular} \hspace{1cm} \begin{tabular}{@{}l} \includegraphics[width=2cm]{photo} \end{tabular} } If you want to flush the photo, use two \address fields \address{% \begin{tabular}{@{}l} Address 123\\ 222 22 City \\ 123 123 \end{tabular} } \address{% ...

Top 50 recent answers are included


text:
Uniquely defined

$\LARGE {{\color{blue}n}{\color{red}!} = {\color{blue}n}^{\color{red}2} + {\color{blue}n}^{\color{red}{\frac{3}{2}}} }$

Find the sum of value(s) of positive integer $$n$$.

×


text:
# \$C^*\$ algebras which admit bounded outer derivation but \$1\$ can not be in the range of any bounded derivation

What is an example of a $$C^*$$ algebra $$A$$ which admits bounded outer derivation but $$1$$ can not be in the range of any bounded derivation $$D:Ato A$$?


text:
33 views

The solution of the differential equation $\frac{d^2y}{dt^2} + 2 \frac{dy}{dt}+y=0$ with $y(0)=y’(0)=1$ is

1. $(2-t)e^t$
2. $(1+2t)e^{-t}$
3. $(2+t)e^{-t}$
4. $(1-2t)e^t$


text:
# Polynomial with exactly one complex root

Is it possible that a polynomial of degree $n$ with real coefficients has exactly one complex root? I saw https://en.wikipedia.org/wiki/Complex_conjugate_root_theorem but wondered if this can happen for polynomials several variables.

• The polynomial $z^n$... – Zev Chonoles Jul 14 '15 at 15:47
• This is easily answered by considering the single variable case, where the answer is no. Specifically, for $n-1$ of the variables, choose any real values, and then you are solving for a single variable polynomial, which will have multiple complex roots if it has any at all. – rondo9 Jul 14 '15 at 15:49

What do you mean with complex root? If you consider real numbers as particular complex numbers ($i.e.$ complex numbers with zero-imaginary part) then every polynomial of the form $p(z)=(z-z_0)^n$ where $z_0$ is a real number has exactly one complex root.
But if you mean a complex number which is not real; then this is impossible. Indeed, let $z_0=a+ib$ be any complex number; then the only polynomials which have $z_0$ as unique complex solution are $p(z)=(z-z_0)^n$ where $n$ is a non-zero natural number. But clearly, in this case, your polynomial has not real coefficients.


text:
# Mobility Centrality

#### Definition

This method is constructed by the use of the anagogic method considering the formula of the kinetic energy of a particle in Physics and adjusting its mathematical analogue to the case of the interregional road network. This centrality represents by $C_i^m$ and defines as fallows:

$$C_i^m={w_i\over 2(N-1)}. {\underset{j=1,i\ne j}{\overset{N}{\sum}}} , \left({d_{ij}^E} \over {w_{ji}}\right)$$

were $w_i$ is node’s weight and $d_{ij}$ is the network distance, $N$ expresses the dimension of the set $V (N = |V |)$ for the network $G(V,E)$ and impedance weight that represented by $w_{ji}$ of the edge $E$.

This centrality measure is estimated to be useful for the operational analysis of a network (such as the analysis of network flows), since it characterizes as central these vertices that appear to have the greatest tendency to attract or expel network flows.

#### References

• Tsiotas D., Polyzos S., 2015. Introducing a new centrality measure from the transportation network analysis in Greece. Annals of Operations Research, 227(1), pp.93-117. DOI: 10.1007/s10479-013-1434-0


text:
Kirchoff’s Rules

1. Feb 25, 2008

danbone87

A triangular array of resistors is shown in the figure. What current will this array draw from a 35.0 V battery having negligible internal resistance if we connect it across (a) ab, (b) bc, (c) ac?

Kinda confused... just anything to start me off on the right track would be very helpful.

2. Feb 25, 2008

univac

Have a good look at the circuit the triangular arrangement is probably throwing you off.
If you put a voltage source between b (positive terminal) and c (negative terminal) the c node becomes your circuit ground. So you can stretch this point and make the circuit look more rectangular. This would result in the voltage source Vbc in parallel with the 10 ohm resistor which is in series with the 15 Ohm resistor which is then in series witht he 20 Ohm resistor. Redraw the circuit that way and you should have no problem figuring out the rest of it.

hope this helps.

3. Feb 26, 2008

Thanks a ton

4. Mar 4, 2011

johnsonc007

This is actually a homework problem that I am also stuck on. Following the above method equals the wrong answer. I can honestly say it doesn't make sense either. That doesn't make a rectangle.

5. Mar 5, 2011

rafehi

There are two resistors in series, which are parallel with the 3rd resistor and voltage source in each case. You should easily be able to find the equivalent resistance of the circuit and thus the current knowing this.

For a), I get 3.5A as the answer.

6. Mar 5, 2011

johnsonc007

Still doesn't help. Trying to teach myself via text this due to lack of interaction from professor. Ended up buying the solution online. Would have never seen the setup, still don't follow how it becomes that.

7. Mar 5, 2011

rafehi

For a), by adding a voltage source across the terminals AB, you have a voltage source in parallel with the resistor.

The other two resistors are in series with another, i.e. all current entering BC must exit through CA (and vice versa).

Because the two resistors are in series, you can add up their resistances to get the equivalent resistance (that is, you can replace the 10 and 20 ohm resistors by a single resistor of 30 ohms).

You're then left with the voltage source in parallel with the 15 ohm resistor, in parallel with the 30 ohm resistor. To find the equivalent resistance of two parallels resistors, you use:
$$\frac{1}{R_{eq}} = \frac{1}{R_{1}} + \frac{1}{R_{2}}$$
which simplifies to:
$$R_{eq} = \frac{R_{1}*R_{2}}{R_{1}+R_{2}}$$

So, Req = 15*30 / (30+15) = 10 ohms.

Then, to find the current, you simply apply Ohm's Law: i = V/R = 35/10 = 3.5A.

Does that clear it up for you? If not, which of the above steps don't you follow? It might be easier for you to visualise it as a rectangle (i.e. the AB resistor on the left, BC resistor on the top, AC resistor on the bottom, with nothing on the right line).

8. Mar 6, 2011

Staff: Mentor

Here's a picture showing rearrangements of the circuit for case (a). You should be able to convince yourself that the underlying topology of each version is the same -- moving components and wires around the page doesn't affect the circuit so long as all connections remain the same.

Attached Files:

• Topo1.jpg
File size:
17.6 KB
Views:
945
9. Jul 24, 2012

lara.brian

Thank you Gneil, your picture helped a ton.