calculus and analysis – How to find a numerical antiderivative with NIntegrate methods?

We construct an NDSolve method which can pass an NIntegrate method to NIntegrate to set up an integration rule. We define a method nintegrate implements such a method. The requirements are

  • the ODE is of the form y'(x) == f(x), and
  • the NIntegrate method returns an interpolatory rule.

Example:

foo = NDSolveValue({y'(x) == Sin(x^2), y(0) == 0}, y, {x, 0, 15}, 
  Method -> nintegrate, InterpolationOrder -> All)

Error plot:

Plot(
 Evaluate@RealExponent(Integrate(Sin(x^2), x) - foo(x)),
 {x, 0, 15},
 GridLines -> {Flatten@foo@"Grid", None}, (* show steps *)
 PlotRange -> {-18.5, 0.5})

Another example:

foo = NDSolveValue({y'(x) == Sin(x^2), y(0) == 0}, y, {x, 0, 15}, 
  Method -> {nintegrate, 
    Method -> {"ClenshawCurtisRule", "Points" -> 33}}, 
  InterpolationOrder -> All, WorkingPrecision -> 32, 
  PrecisionGoal -> 24, MaxStepFraction -> 1, StartingStepSize -> 15)

Error plot:

Block({$MaxExtraPrecision = 500},
 ListLinePlot(
  Integrate(Sin(x^2), x) - foo(x) /. x -> Subdivide(0, 15, 1000) // 
   RealExponent, DataRange -> {0, 15}, PlotRange -> {-35.5, 0.5}, 
  GridLines -> {Flatten@foo@"Grid", None})
 )

Code for method

nintegrate::nintode = 
  "Method nintegrate requires an ode of the form ``'(``) == f(``)";
nintegrate::nintinit = 
  "NIntegrate method `` did not return an interpolatory integration rule.";

nintegrate(___)("StepInput") = {"F"("T"), "H", "T", "X", "XP"};
nintegrate(___)("StepOutput") = {"H", "XI"};
nintegrate(rule_, order_, ___)("DifferenceOrder") := order;
nintegrate(___)("StepMode") := Automatic

Options@nintegrate = {Method -> "GaussKronrodRule"};
getorder(points_, method_) :=
  Switch(method
   , "GaussKronrodRule" | "GaussKronrod",
   (* check points should be odd ??? *)
   With({gp = (points - 1)/2},
    If(OddQ(gp), 3 gp + 2, 3 gp + 1)
    )
   , "GauseBerntsenEspelidRule", 2 points - 1
   , "LobattoKronrodRule",
   (* check points should be odd ??? *)
   With({glp = (points + 1)/2},
    If(OddQ(glp), 3 glp - 2, 3 glp - 3)
    )
   , "GauseBerntsenEspelidRule",
   2 points - 1
   , "NewtonCotesRule",
   If(OddQ(points), points, points - 1)
   , _, points - 1
   );
nintegrate /: 
  NDSolve`InitializeMethod(nintegrate, stepmode_, sd_, rhs_, state_, 
   mopts : OptionsPattern(nintegrate)) := 
  Module({prec, order, norm, rule, xvars, tvar, imeth},
   xvars = NDSolve`SolutionDataComponent(state@"Variables", "X");
   tvar = NDSolve`SolutionDataComponent(state@"Variables", "T");
   If(Length@xvars != 1,
    Message(nintegrate::nintode, First@xvars, tvar, tvar);
    Return($Failed));
   If(! VectorQ(rhs("FunctionExpression")(
       N@NDSolve`SolutionDataComponent(sd, "T"),
       Sequence @@ xvars),
      NumericQ
      ),
    Message(nintegrate::nintode, First@xvars, tvar, tvar);
    Return($Failed));
   prec = state@"WorkingPrecision";
   norm = state@"Norm";
   
   imeth = Replace(Method /. mopts, Automatic -> "GaussKronrodRule");
   rule = 
    NIntegrate(1, {x, 0, 1}, 
     Method -> {"GlobalAdaptive", "SymbolicProcessing" -> 0, 
       Method -> imeth},
     WorkingPrecision -> prec,
     IntegrationMonitor :>
      (Return(Through(#@"GetRule"), NIntegrate) &));
   rule = Replace(rule, {
      {(NIntegrate`GeneralRule | NIntegrate`ClenshawCurtisRule)(idata_)} :>
       idata,
      _NIntegrate :>
       Return($Failed),
      _ :>  (* What happened here? *)
       (Message(nintegrate::nintinit, Method -> imeth);
        Return($Failed))
      });
   order = 
    getorder(Length@First@rule, imeth /. {m_String, ___} :> m);
   
   nintegrate(rule, order, norm)
   );

(rule : nintegrate(int_, order_, norm_, ___))(
   "Step"(rhs_, h_, t_, x_, xp_)) := 
  Module({prec, tt, xx, dx, normh, err, hnew, temp},
   (* Norm scaling will be based on current solution y. *)
   normh = (Abs(h) temp(#1, x) &) /. {temp -> norm};
   tt = Rescale(int((1)), {0, 1}, {t, t + h});
   xx = rhs /@ tt;
   dx = h*int((2)).xx;
   (* Compute scaled error estimate *)
   err = h*int((3)).xx // normh;
   hnew = Which(
     err > 1 (* Rejected step: reduce h by half *)
     , dx = $Failed; h/2
     , err < 2^-(order + 2), 2 h
     , err < 1/2, h
     , True, h Max(1/2, Min(9/10, (1/(2 err))^(1/(order + 1))))
     );
   (* Return step data along with updated method data *)
   {hnew, dx});

world of darkness – Did I understand how thin-blood alchemy distilation methods work right?

Long ago, I prepared a Vampire the Masquerade 5e and ask a lot of questions about thin-blood. After a short time, my players decide to play non thin-blood characters. Now, I want to play a campaign with only thin-blood characters.

Thin-blood alchemy have three distilation methods. Athanor corporis, Calcinatio and Fixatio. I understand them in a way that look strange for me (mostly Athanor corporis and Calcinatio):

  • Athanor corporis: You make your formulas with your own body, and you can keep them indefinitely. But you can use only one at a time, and you have to concentrate for 3 turn to switch formulas. But something that I don’t understand is “does you keep the previous formula in your body, and just have to switch to have it again, or did you need to re-distill it later to have it again?”
  • Calcinatio: You make your formulas with kine. They have the formula in them until they have an emotional shift. If you drink there blood, you have the power. But what I don’t understand is “Is the formula is still in the human after drinking?” and “What happend if someone else drink the formula?”
  • Fixatio: Classic rpg alchemy. You make a potion, it give you powers for a short time if you drink it. The only question that I have is “can you share your formula with another thin-blood, so they can use the power too?”

related: How do thin-bloods and thin-blood alchemy work?

c# – How would you refactor these three methods?

We have three methods, the first calls the second one. How would you refactor so the third one can call the second one too as they have similar code?

public async Task UnpublishPersonAsync(string id)
{
    await QueueAndUpdateStatusAsync(id, PersonStatus.Unpublishing, QueueNames.Unpublish);
}


private async Task QueueAndUpdateStatusAsync(string id, PersonStatus status, string queueName)
{
    var personDto = await _cosmosDbService.GetItemAsync<PersonDto>(id, id);
    var operationIsValid = ValidateOperation(status, personDto);

    if (operationIsValid)
    {
        personDto.Status = status;
        personDto = await _cosmosDbService.UpdateItemAsync(id, id, personDto);
        var person = _mappingService.MapToPerson(personDto);

        await _queue.PublishToStorageQueueAsync(person, queueName);
    }
    else
    {
        throw new InvalidOperationException();
    }
}

public async Task DeletePersonAsync(string id, bool deleteAssociatedData)
{
    var personDto = await _cosmosDbService.GetItemAsync<PersonDto>(id, id);
    var operationIsValid = ValidateOperation(PersonStatus.Deleting, personDto);

    if (operationIsValid)
    {
        personDto.Status = PersonStatus.Deleting;
        personDto = await _cosmosDbService.UpdateItemAsync(id, id, personDto);
        var person = _mappingService.MapToPerson(personDto);

        var deleteCommand = new DeletePersonCommand()
        {
            Person = person,
            DeleteAssociatedData = deleteAssociatedData
        };

        await _queue.PublishToStorageQueueAsync(deleteCommand, QueueNames.Delete);
    }
    else
    {
        throw new InvalidOperationException();
    }
}

I thought about using generics and make it optional, but it seems that’s not possible. By the way, PublishToStorageQueueAsync is already generic for the first argument.

functions – Could multiple dynamic dispatch methods be bound to classes like traditional single dynamic dispatch methods?

C++ only supports single dynamic dispatch methods. Indeed, the following C++ program:

#include <iostream>

struct Shape {
  virtual void overlap(Shape* y) { std::cout << "Shape, Shape" << std::endl; }
};

struct Circle: Shape {
  void overlap(Shape* y) { std::cout << "Circle, Shape" << std::endl; }
  void overlap(Circle* y) { std::cout << "Circle, Circle" << std::endl; }
};

void overlap(Shape* x, Shape* y) { std::cout << "Shape, Shape" << std::endl; }
void overlap(Circle* x, Shape* y) { std::cout << "Circle, Shape" << std::endl; }
void overlap(Circle* x, Circle* y) { std::cout << "Circle, Circle" << std::endl; }

int main() {
  Shape* x = new Circle();
  Shape* y = new Circle();
  x->overlap(y);
  overlap(x, y);
  return 0;
}

outputs:

Circle, Shape
Shape, Shape

If C++ supported multiple dynamic dispatch methods (i.e. bound to classes) and multiple dynamic dispatch functions (i.e. not bound to classes), the previous program would output:

Circle, Circle
Circle, Circle

Common Lisp, Dylan and Julia support multiple dynamic dispatch functions but do not support methods (single or multiple dynamic dispatch).

Would it be possible for a language to support multiple dynamic dispatch methods instead of or in addition to multiple dynamic dispatch functions?

I am asking this because supporting only multiple dynamic dispatch functions look like a step backward to procedural programming. Encapsulation (implementation hiding behind an interface) is a pillar of object-oriented programming. Using functions in place of methods forces the exposure of the supposedly hidden states of objects to be able to manipulate them, because contrary to methods, functions do not have a privileged access to these states.

shutter – What DIY methods exist to trigger a Lumix G3 without touching the camera?

I have a Panasconic Lumix DMC-G3 with a 175 mm lens which I need to trigger without touching the camera to reduce camera shake1.

I know of the following ways to take a photo without touching the camera, however at the moment I cannot use any of those:

  1. Cable release: A device that you plug into your camera with a button that releases the camera shutter.
    • I don’t own a cable release for this camera.
  2. Intervalometer: A cable releases with the possibility to set up timers, e.g. for timelapses.
    • I don’t own an intervalometer for this camera.
  3. Remote Release: Similar to cable releases, but they are not plugged into the camera and work via infrared.
    • I don’t own a remote release for this camera.
  4. Smartphone App: Many (modern) cameras have built-in WiFi or Bluetooth which allows you to take a photo and sometimes even change settings using a smartphone app.
    • This camera has no WiFi or Bluetooth
  5. PC software: Some cameras can be tethered to a PC (usually using a cable) and can be controlled and fired with some software.
  6. Camera self-timer: Most cameras have a self-timer (e.g. 2 or 10 seconds).
    • I experienced that this can still cause camera shake when using a telephoto lens, about 3/4 of the images were shaky taken this way1.

Are there any DIY methods than those described above to take a photo without touching the camera?


1: My other question contains more information on the problem at hand: I’m trying to photograph comet C/2020 F3 (Neowise) by stacking images, but the results are too shaky.

game design – Godot: is it possible to Call custom methods in animation?

My Problem

I just found out that one can set an animation Player to call methods from a given node. This was great for me as it allows me to better coordinate methods with animation frames.

My problem is that the interface only displays default node methods. Why is it like that and what needs to be done so that I can call my own methods?

data – Name of classes that contain only methods, and classes that contain both fields and methods

I am studying the Java jvm programming language Kotlin, and I just came across the idea of a Data Class. I understand what a Data Class in Kotlin is, so I don’t have a question on it. Instead, my question is about the name of classes that have only methods, or have both fields and methods.

I have a background in Java programming, where classes can have either one of, or both of fields and methods. I have heard of programmers calling a class that contains only fields and not containing methods, as a “Value Class”. Also, I am familiar with the idea of Structures in C++ which to my knowledge, typically contain only fields. However, I have not heard of a name for classes that contain only methods, and I have not heard of the name of a class that contains both fields and methods. Based on my background in Java, it seems to me that a class that contains only methods would probably be a static utility class containing only static methods. Also, since interfaces in Java 9 can contain default methods, you could have a method-only structure with interfaces. But I don’t know what the metaprogramming term would be for this style of method-only class. And I don’t know what you would call a class that contains both fields and methods, other than just a “Class” or standard class.

Question #1: what is the name of a class that contains only methods?

Question #2: what is the name of a class that contains both fields and methods?

I am not looking for names that are programming language specific, but rather for names that apply across programming languages. For instance, a “Value Class” contains only fields/data, and can be used to apply to any programming language concept of class, object, structure, etc.

java – Should all third party methods that access outside resources (like other databases) be wrapped up?

From the perspective of unit testing, the code under test should obviously not be accessing outside resources so the third party methods need to be mocked. However, it seems like this is poor practice because third party methods can change and become static/final which makes mocking difficult in Mockito. So in that sense, is it best practice to always wrap up third party methods?

I suppose this question may also apply to other programming languages and testing frameworks.