Saturday, January 13, 2024

Can you give the example of an odd integrand and prove that it is odd?

Example of an odd integrand and it's proof.

Certainly! Let's consider the function f ( x ) = x 3 f(x) = x^3 . We'll integrate this function over a symmetric interval, say [ a , a ] [-a, a] , and then show that the result is zero, proving that f ( x ) f(x) is an odd function.

The integral is given by:

a a x 3 d x \int_{-a}^{a} x^3 \,dx

To evaluate this integral, we'll use the properties of odd functions. An odd function f ( x ) f(x) satisfies f ( x ) = f ( x ) f(-x) = -f(x) . Let's evaluate f ( x ) f(-x) for f ( x ) = x 3 f(x) = x^3 :

f ( x ) = ( x ) 3 = x 3 f(-x) = (-x)^3 = -x^3

Now, compare f ( x ) f(-x) with f ( x ) -f(x) :

f ( x ) = x 3 -f(x) = -x^3

As we can see, f ( x ) = f ( x ) f(-x) = -f(x) . This property holds for all values of x x .

Now, let's calculate the integral:

a a x 3 d x = 1 4 x 4 a a \int_{-a}^{a} x^3 \,dx = \frac{1}{4}x^4 \Big|_{-a}^{a}

= 1 4 ( a 4 ( a ) 4 ) = \frac{1}{4}(a^4 - (-a)^4)

= 1 4 ( a 4 a 4 ) = \frac{1}{4}(a^4 - a^4)

= 1 4 ( 0 ) = \frac{1}{4}(0)

= 0 = 0

The result is zero, which means that the integral of the odd function f ( x ) = x 3 f(x) = x^3 over the symmetric interval [ a , a ] [-a, a] is zero. This demonstrates that f ( x ) = x 3 f(x) = x^3 is an odd function.

Friday, January 12, 2024

Gaussian Integral: Integrate exp(-x^2) from -infinite to +infinite

Integrate exp(-x^2) from -infinite to +infinite

Note: this integral is also known as Gaussian integral.

The integral of ex2e^{-x^2} from -\infty to ++\infty is a well-known mathematical constant and is denoted by π\sqrt{\pi}. The integral is often expressed as:

ex2dx=Ï€\int_{-\infty}^{\infty} e^{-x^2} \, dx = \sqrt{\pi}

This result is commonly encountered in probability theory and statistics, especially in the context of the normal distribution. The integral doesn't have a simple elementary function representation and is typically solved using advanced mathematical techniques. The proof involves the use of polar coordinates and complex analysis.

Some of the mathematical results and properties we will use today:

Note (1):

I = Integral of f(x) w.r.t. dx
Then I^2 = Integral of f(x).f(y) w.r.t. dxdy

Note (2): Well known step:

When changing to polar coordinates from (x, y) to (r, theta):

# (dx dy) changes to (r dr dtheta) 

Note (3): Well known trigonometric property:

sq(sin(theta)) + sq(cos(theta)) = 1

Note (4):

(integral of e^(x)) = e^(x)

The result that folows from this is: (integral of e^(-x)) = -e^(-x)

Fig 1:
Fig 2:

Thursday, January 11, 2024

What this book (Why We Meditate) offers you (Chapter 1)

Translate this page:

Why We Meditate: The Science And Practice of Clarity and Compassion
CH 1: WHAT THIS BOOK OFFERS YOU

A word about the authors:

Who is Tsoknyi Rinpoche?

Tsoknyi Rinpoche is a Tibetan Buddhist teacher and the spiritual head of the Pundarika Foundation. He was born in 1966 in Nubri, Nepal, and is a renowned meditation master and author. Tsoknyi Rinpoche is part of the Nyingma school of Tibetan Buddhism, which is one of the oldest schools of Tibetan Buddhism.

Tsoknyi Rinpoche comes from a long line of meditation masters, and he received extensive training in both the Kagyu and Nyingma traditions. He is known for his accessible and humorous teaching style, making ancient Buddhist wisdom relevant and applicable to contemporary audiences.

Who is Daniel Goleman?

Daniel Goleman is an American psychologist and science journalist best known for his work on emotional intelligence. He was born on March 7, 1946, in Stockton, California. Goleman earned his PhD in psychology from Harvard University.

He gained widespread recognition with the publication of his book "Emotional Intelligence: Why It Can Matter More Than IQ" in 1995. In this influential book, Goleman explores the concept of emotional intelligence and argues that it is a crucial factor in personal and professional success. He contends that emotional intelligence, which includes skills like self-awareness, self-regulation, empathy, and interpersonal skills, plays a significant role in determining a person's effectiveness in various aspects of life.

Apart from his work on emotional intelligence, Goleman has written extensively on topics related to psychology, education, and leadership. Some of his other notable books include "Social Intelligence," "Working with Emotional Intelligence," and "Focus: The Hidden Driver of Excellence."

This book is for you:

(1) if you have been considering starting meditation and are not sure why you should or how to begin;

(2) if you are meditating but wonder why or what to do next to progress;

(3) or if you already are a convinced meditator and want to help someone you care about get going, by giving them this book.

Tags: Psychology,Buddhism,Book Summary,

Wednesday, January 10, 2024

Why Write about Emotional Upheaval? (Chapter 1)

Translate this page:





Emotional Writing: A Brief History

Figure 1. Yearly physician visits for illness among people who report not having had a childhood trauma (No Trauma), having had one or more traumas about which they confided (Trauma — Confide), or having had at least one significant childhood trauma that they had kept secret (Trauma — No Confide).

Figure 2. Yearly number of physician visits for illness in the three months after the experiment for participants in the emotional writing and control (non-emotional writing) conditions.

The No Writing data is based on students who did not participate in the experiment.

What Are the Effects of Writing?

Biological effects

The immune system.

The body’s immune system can function more or less effectively, depending on the person’s stress level.

Studies find that emotional writing is associated with general enhancement in immune function [1]

Medical markers of health.

Expressive writing finds usage in tracking general / overall health of the patient of any illness.

[1]: Koschwanez et al., 2013; Pennebaker, Kiecolt-Glasser & Glasser 1988; Lumley et al. 2011

Physiological indicators of stress

Somewhat surprisingly, while people write or talk about traumas, they often show immediate signs of reduced stress: lower muscle tension in their face, and drops in hand skin conductance (often used in lie detection to measure the stress of deception and also easily measured with readily available Biodot® skin thermometers). Immediately after writing about emotional topics, people have lower blood pressure and heart rates.

Psychological Effects

# Mood changes immediately after writing: Feeling sad is normal.

# Long-term mood changes.

Writing may make you sad for a brief time after writing, but the long-term effects are far more positive.

Behavioral Changes

# Performance at school or work:

Among beginning college students, expressive writing helps people adjust to their situation better.

# Working Memory

Working memory is the technical term for our general ability to think about complex tasks. If we are worrying about things — including emotional upheavals from the past — we have less working memory.

Expressive writing, we now know, frees working memory, allowing us to deal with more complicated issues in our lives (Klein & Boals 2001).

Students who did expressive writing about upcoming exams reported improved mood prior to their exams and improved performance (Dalton & Glenwick 2009; Frattaroli, Thomas, & Lyubomirsky 2011).

Dealing with our social lives.

Working with other people can sometimes be a daunting psychological task. The more emotional stress we are under, the more draining it is. Recent studies have suggested that expressive writing can enhance the quality of our social lives.

Writing Style

Some ways of writing appear to work better than others do. Recent studies by multiple labs are converging on some common guidelines. People tend to benefit most from expressive writing if they:

Openly acknowledge emotions.

Emotional experience is part of a trauma. The ability to feel and label both the negative and the positive feelings that occurred during and following the trauma is important.

Work to construct a coherent story.

Immediately after a trauma, things often seem out of control and disconnected. One goal of expressive writing is to begin to put things together again. One way of accomplishing this is to make a meaningful story of what happened and how it is affecting you. Many argue that the brain is a narrative organ and that story-making is hardwired into our very nature. Creating a narrative, including a coherent beginning, middle, and end, is a well-documented part of trauma treatment and holds much promise for benefits from writing about trauma.

Switch perspectives.

People who have experienced a trauma initially see it from one perspective — their own. Indeed, when individuals first write about a massive upheaval, they first describe what they saw, felt, and experienced. Recent studies indicate that people who benefit the most from writing have been able to see events through others’ eyes. Indeed, even writing about a personal event in the third person has proven beneficial (Andersson & Conley 2013; Campbell & Pennebaker 2003; Seih et al. 2011).

Find your voice.

A guiding principle of expressive writing is that you express yourself openly and honestly. People who write in a cold, detached manner and who quote Shakespeare, Aristotle, or Henry Ford may be fine historians and may even write a great editorial in the local newspaper. But impressive writing is not the point of expressive writing. People who benefit the most from writing are able to find a voice that reflects who they are.

Tags: Book Summary,Psychology,

Tuesday, January 9, 2024

Genomic Range Query: Find the minimal nucleotide from a range of sequence DNA (Medium Complexity)

Problem

A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence?

The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive).

Write a function:

def solution(S, P, Q)

that, given a non-empty string S consisting of N characters and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries.

Result array should be returned as an array of integers.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..100,000];

M is an integer within the range [1..50,000];

each element of arrays P and Q is an integer within the range [0..N - 1];

P[K] ≤ Q[K], where 0 ≤ K < M;

string S consists only of upper-case English letters A, C, G, T.

Example

For example, consider string S = CAGCCTA and arrays P, Q such that:

P[0] = 2 Q[0] = 4

P[1] = 5 Q[1] = 5

P[2] = 0 Q[2] = 6

The answers to these M = 3 queries are as follows:

The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2.

The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4.

The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1.

The function should return the values [2, 4, 1], as explained above.

Brute Force Solution

def solution(S, P, Q):
    impact_factors = {
        'A': 1,
        'C': 2,
        'G': 3,
        'T': 4
    }

    X = [impact_factors[i] for i in S]

    # Implement your solution here
    rtn = []
    for i in range(len(P)):
        start = P[i]
        end = Q[i] + 1

        s = X[start:end]

        rtn.append(min(s))

    return rtn 

Detected time complexity:

O(N * M)

Smart Solution Using Prefix Sums (Part 1)

def solution(S, P, Q):
    N = len(S)
    M = len(P)

    impact_factors = {'A': 1, 'C': 2, 'G': 3, 'T': 4}

    # Calculate prefix sums for each nucleotide type
    prefix_sums = [[0] * (N + 1) for _ in range(4)]
    for i in range(1, N + 1):
        for j in range(4):
            prefix_sums[j][i] = prefix_sums[j][i - 1]
        prefix_sums[impact_factors[S[i - 1]] - 1][i] += 1
        print(i, S[i-1])
        print(prefix_sums)

    print(':1 ~ ~ ~ ~ ~ ~ ~ ~ ~')
    S = 'CAGCCTA'
    P = [2, 5, 0]
    Q = [4, 5, 6]
    print(solution(S, P, Q))  # Output: [2, 4, 1]

    print(':2 ~ ~ ~ ~ ~ ~ ~ ~ ~')
    print(solution('AGCT', [], []))

    print(':3 ~ ~ ~ ~ ~ ~ ~ ~ ~')
    print(solution('AACT', [], []))

This is a two part solution.

In the first part, we build prefix sum sequences for each nucleotide to track it’s occurrence.

Output (Part 1)

S = 'CAGCCTA'

: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, 0, 1, 1], [0, 0, 1, 1, 1], [0, 0, 0, 0, 1]]

For 'AACT'

:3 ~ ~ ~ ~ ~ ~ ~ ~ ~

1 A

[[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

2 A

[[0, 1, 2, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

3 C

[[0, 1, 2, 2, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

4 T

[[0, 1, 2, 2, 2], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1]]

Smart Solution Using Prefix Sums (Part 2)

def solution(S, P, Q):
    N = len(S)
    M = len(P)

    impact_factors = {'A': 1, 'C': 2, 'G': 3, 'T': 4}

    # Calculate prefix sums for each nucleotide type
    prefix_sums = [[0] * (N + 1) for _ in range(4)]
    for i in range(1, N + 1):
        for j in range(4):
            prefix_sums[j][i] = prefix_sums[j][i - 1]
        prefix_sums[impact_factors[S[i - 1]] - 1][i] += 1

    # Process queries
    result = []
    for k in range(M):
        start_position = P[k]
        end_position = Q[k] + 1

        for nucleotide_type in range(4):
            if prefix_sums[nucleotide_type][end_position] - prefix_sums[nucleotide_type][start_position] > 0:
                result.append(nucleotide_type + 1)
                break

    return result

    # Example usage:
    S = 'CAGCCTA'
    P = [2, 5, 0]
    Q = [4, 5, 6]
    print(solution(S, P, Q))  # Output: [2, 4, 1]

In the second part of the solution we determine from start to end if a low factor nucleotide is present or not.

Here, let seq_X be sequence from as in prefix_sums[nucleotide_type]

It takes the form:

seq_A: [0, 0, 1, 1, 1, 1, 1, 2],

seq_C: [0, 1, 1, 1, 2, 3, 3, 3],

seq_G: [0, 0, 0, 1, 1, 1, 1, 1],

seq_T: [0, 0, 0, 0, 0, 0, 1, 1]

For input sequence: CAGCCTA

Then from any of this seq, we determine whether if A is appearing between start and end using seq_A[end] - seq_A[start]

Or if C is appearing between start and end using:

seq_C[end] – seq_C[start]

Or if G is appearing between start and end using:

seq_G[end] – seq_G[start]

Or if T is appearing between start and end using:

seq_T[end] – seq_T[start]

If a nucleotide is found in this second part of the code, we record this nucleotide and break out.

Time Complexity

Detected time complexity:

O(N + M)

Tests

Correctness tests

extreme_sinlge

single character string

extreme_double

double character string

simple

simple tests

small_length_string

small length simple string

small_random

small random string, length = ~300

Performance tests

almost_all_same_letters

GGGGGG..??..GGGGGG..??..GGGGGG

large_random

large random string, length

extreme_large

all max ranges

Explanation of Code Using Bard

I'd be glad to explain the code you provided:

Here's a breakdown of the code's key steps:

  1. Initialization:

    • N stores the length of the DNA sequence S.
    • M stores the number of queries (the length of arrays P and Q).
    • impact_factors maps each nucleotide to its corresponding impact factor.
  2. Prefix Sums Calculation:

    • prefix_sums is a 2D array with 4 rows (one for each nucleotide type) and N+1 columns. It's used to store the counts of each nucleotide type up to each position in the DNA sequence.
    • The nested loops iterate through the DNA sequence and update prefix_sums accordingly:
      • The first loop iterates through each position in the sequence.
      • The second loop iterates through each nucleotide type.
      • For each position and nucleotide type, the code copies the count from the previous position and then increments the count if the current nucleotide matches the type.
  3. Query Processing:

    • result is an empty list to store the answers to the queries.
    • The outer loop iterates through each query, accessing its start and end positions from P and Q.
    • The inner loop iterates through each nucleotide type.
    • It checks if the count of the current nucleotide type within the query range (end_position - start_position) is greater than 0. If so, it means that nucleotide type is present within the range, and its impact factor is added to the result list. The loop then breaks because we've found the minimum impact factor for that query.
  4. Returning Results:

    • The function returns the result list containing the answers to all queries.

Example Usage:

  • The provided example demonstrates how to use the function with a sample DNA sequence S and query arrays P and Q.
  • The output [2, 4, 1] correctly represents the minimum impact factors for the specified query ranges in S.

Key Points:

  • The code efficiently calculates prefix sums to count the occurrences of each nucleotide type up to each position.
  • This precomputation allows for quick calculation of minimum impact factors within any query range, using simple subtractions of prefix sums.
  • The time complexity of the code is O(N + M), making it efficient for large DNA sequences and multiple queries.

Monday, January 8, 2024

Div Count (Problem on Prefix Sums)

Div Count Problem
Compute number of integers divisible by k in range [a..b].

Problem

Write a function:

def solution(A, B, K)

that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:

{ i : A ≤ i ≤ B, i mod K = 0 }

For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.

Write an efficient algorithm for the following assumptions:

# A and B are integers within the range [0..2,000,000,000];

# K is an integer within the range [1..2,000,000,000];

# A ≤ B

Code

from math import ceil, floor 

def solution(A, B, K):
    
    start = ceil(A/K)
    end = floor(B/K)
    return end - start + 1

Complexity

Detected time complexity:

O(1)

Tests

Correctness tests

simple

A = 11, B = 345, K = 17

minimal

A = B in {0,1}, K = 11

extreme_ifempty

A = 10, B = 10, K in {5,7,20}

extreme_endpoints

verify handling of range endpoints, multiple runs

Performance tests

big_values

A = 100, B=123M+, K=2

big_values2

A = 101, B = 123M+, K = 10K

big_values3

A = 0, B = MAXINT, K in {1,MAXINT}

big_values4

A, B, K in {1,MAXINT}