text:
Outlook: MEDALLION METALS LIMITED. is assigned short-term Ba1 & long-term Ba1 estimated rating.
Dominant Strategy : Hold
Time series to forecast n: 24 Jan 2023 for (n+4 weeks)
Methodology : Transductive Learning (ML)

## Abstract

MEDALLION METALS LIMITED. prediction model is evaluated with Transductive Learning (ML) and Statistical Hypothesis Testing1,2,3,4 and it is concluded that the MM8 stock is predictable in the short/long term. According to price forecasts for (n+4 weeks) period, the dominant strategy among neural network is: Hold

## Key Points

1. Can statistics predict the future?
2. Game Theory
3. Probability Distribution

## MM8 Target Price Prediction Modeling Methodology

We consider MEDALLION METALS LIMITED. Decision Process with Transductive Learning (ML) where A is the set of discrete actions of MM8 stock holders, F is the set of discrete states, P : S × F × S → R is the transition probability distribution, R : S × F → R is the reaction function, and γ ∈ [0, 1] is a move factor for expectation.1,2,3,4

F(Statistical Hypothesis Testing)5,6,7= $\begin{array}{cccc}{p}_{a1}& {p}_{a2}& \dots & {p}_{1n}\\ & ⋮\\ {p}_{j1}& {p}_{j2}& \dots & {p}_{jn}\\ & ⋮\\ {p}_{k1}& {p}_{k2}& \dots & {p}_{kn}\\ & ⋮\\ {p}_{n1}& {p}_{n2}& \dots & {p}_{nn}\end{array}$ X R(Transductive Learning (ML)) X S(n):→ (n+4 weeks) $∑ i = 1 n s i$

n:Time series to forecast

p:Price signals of MM8 stock

j:Nash equilibria (Neural Network)

k:Dominated move

a:Best response for target price

For further technical information as per how our model work we invite you to visit the article below:

How do AC Investment Research machine learning (predictive) algorithms actually work?

## MM8 Stock Forecast (Buy or Sell) for (n+4 weeks)

Sample Set: Neural Network
Stock/Index: MM8 MEDALLION METALS LIMITED.
Time series to forecast n: 24 Jan 2023 for (n+4 weeks)

According to price forecasts for (n+4 weeks) period, the dominant strategy among neural network is: Hold

X axis: *Likelihood% (The higher the percentage value, the more likely the event will occur.)

Y axis: *Potential Impact% (The higher the percentage value, the more likely the price will deviate.)

Z axis (Grey to Black): *Technical Analysis%

## IFRS Reconciliation Adjustments for MEDALLION METALS LIMITED.

1. Alternatively, the entity may base the assessment on both types of information, ie qualitative factors that are not captured through the internal ratings process and a specific internal rating category at the reporting date, taking into consideration the credit risk characteristics at initial recognition, if both types of information are relevant.
2. Despite the requirement in paragraph 7.2.1, an entity that adopts the classification and measurement requirements of this Standard (which include the requirements related to amortised cost measurement for financial assets and impairment in Sections 5.4 and 5.5) shall provide the disclosures set out in paragraphs 42L–42O of IFRS 7 but need not restate prior periods. The entity may restate prior periods if, and only if, it is possible without the use of hindsight. If an entity does not restate prior periods, the entity shall recognise any difference between the previous carrying amount and the carrying amount at the beginning of the annual reporting period that includes the date of initial application in the opening retained earnings (or other component of equity, as appropriate) of the annual reporting period that includes the date of initial application. However, if an entity restates prior periods, the restated financial statements must reflect all of the requirements in this Standard. If an entity's chosen approach to applying IFRS 9 results in more than one date of initial application for different requirements, this paragraph applies at each date of initial application (see paragraph 7.2.2). This would be the case, for example, if an entity elects to early apply only the requirements for the presentation of gains and losses on financial liabilities designated as at fair value through profit or loss in accordance with paragraph 7.1.2 before applying the other requirements in this Standard.
3. Interest Rate Benchmark Reform, which amended IFRS 9, IAS 39 and IFRS 7, issued in September 2019, added Section 6.8 and amended paragraph 7.2.26. An entity shall apply these amendments for annual periods beginning on or after 1 January 2020. Earlier application is permitted. If an entity applies these amendments for an earlier period, it shall disclose that fact.
4. When a group of items that constitute a net position is designated as a hedged item, an entity shall designate the overall group of items that includes the items that can make up the net position. An entity is not permitted to designate a non-specific abstract amount of a net position. For example, an entity has a group of firm sale commitments in nine months' time for FC100 and a group of firm purchase commitments in 18 months' time for FC120. The entity cannot designate an abstract amount of a net position up to FC20. Instead, it must designate a gross amount of purchases and a gross amount of sales that together give rise to the hedged net position. An entity shall designate gross positions that give rise to the net position so that the entity is able to comply with the requirements for the accounting for qualifying hedging relationships.

*International Financial Reporting Standards (IFRS) adjustment process involves reviewing the company's financial statements and identifying any differences between the company's current accounting practices and the requirements of the IFRS. If there are any such differences, neural network makes adjustments to financial statements to bring them into compliance with the IFRS.

## Conclusions

MEDALLION METALS LIMITED. is assigned short-term Ba1 & long-term Ba1 estimated rating. MEDALLION METALS LIMITED. prediction model is evaluated with Transductive Learning (ML) and Statistical Hypothesis Testing1,2,3,4 and it is concluded that the MM8 stock is predictable in the short/long term. According to price forecasts for (n+4 weeks) period, the dominant strategy among neural network is: Hold

### MM8 MEDALLION METALS LIMITED. Financial Analysis*

Rating Short-Term Long-Term Senior
Outlook*Ba1Ba1
Income StatementCaa2Caa2
Balance SheetBaa2B1
Leverage RatiosBaa2B3
Cash FlowB2C
Rates of Return and ProfitabilityCaa2Caa2

*Financial analysis is the process of evaluating a company's financial performance and position by neural network. It involves reviewing the company's financial statements, including the balance sheet, income statement, and cash flow statement, as well as other financial reports and documents.
How does neural network examine financial reports and understand financial state of the company?

### Prediction Confidence Score

Trust metric by Neural Network: 88 out of 100 with 880 signals.

## References

1. Cortes C, Vapnik V. 1995. Support-vector networks. Mach. Learn. 20:273–97
2. Dudik M, Langford J, Li L. 2011. Doubly robust policy evaluation and learning. In Proceedings of the 28th International Conference on Machine Learning, pp. 1097–104. La Jolla, CA: Int. Mach. Learn. Soc.
3. Chamberlain G. 2000. Econometrics and decision theory. J. Econom. 95:255–83
4. M. Ono, M. Pavone, Y. Kuwata, and J. Balaram. Chance-constrained dynamic programming with application to risk-aware robotic space exploration. Autonomous Robots, 39(4):555–571, 2015
5. R. Howard and J. Matheson. Risk sensitive Markov decision processes. Management Science, 18(7):356– 369, 1972
6. D. Bertsekas. Dynamic programming and optimal control. Athena Scientific, 1995.
7. K. Tumer and D. Wolpert. A survey of collectives. In K. Tumer and D. Wolpert, editors, Collectives and the Design of Complex Systems, pages 1–42. Springer, 2004.
Frequently Asked QuestionsQ: What is the prediction methodology for MM8 stock?
A: MM8 stock prediction methodology: We evaluate the prediction models Transductive Learning (ML) and Statistical Hypothesis Testing
Q: Is MM8 stock a buy or sell?
A: The dominant strategy among neural network is to Hold MM8 Stock.
Q: Is MEDALLION METALS LIMITED. stock a good investment?
A: The consensus rating for MEDALLION METALS LIMITED. is Hold and is assigned short-term Ba1 & long-term Ba1 estimated rating.
Q: What is the consensus rating of MM8 stock?
A: The consensus rating for MM8 is Hold.
Q: What is the prediction period for MM8 stock?
A: The prediction period for MM8 is (n+4 weeks)

## People also ask

What are the top stocks to invest in right now?


text:
# Same strings in different contexts

Seems the string $__count$ days is used for days count at least in 2 different contexts:

In Russian the language needs to distinguish these two grammar cases.

Perhaps there are another use cases where identical strings are used in different contexts, so need to use different strings for localization purpose.

• To possible close voters: although this seems to only pertain to a specific site, any changes made to the localization impact all sites network wide. In that sense it is not off-topic here on MSE. – rene Dec 25 '16 at 21:35
• @AdamLear why you replaced bug to feature-request? I think in terms of localization my post is about bug, not a feature request. – αλεχολυτ Dec 26 '16 at 15:00
• @alexolut The difference is minor, but this isn't a bug in the strictest sense. This is literally a feature that's missing from our localization engine, not just a matter of fixing up how strings are expressed in code or something on a similarly smaller scale. – Adam Lear Dec 26 '16 at 23:53
• @AdamLear: I'd argue that the difference it not minor for native speakers. It's like seeing "22 day" instead of "days". If this were in English localization, would you perceive it as a missing feature or a bug? – Vlad Dec 2 '17 at 15:19
• @Vlad Adam meant the difference between bug and feature-request was minor, not the wording itself. i.e, this question is asking to add a feature that doesn’t exist, rather than asking to fix something that isn’t working as intended. – Cai Dec 2 '17 at 16:03
• @Cai according to the good localization for already supported languages it is a bug. Like plurals issues in English, as Vlad said. – αλεχολυτ Dec 2 '17 at 16:08

format: plain


text:
# binary I/O

This topic is 3225 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a structure called an Anibox. It just plays cartoons. All it contains is the number of images (int isize), the type of Anibox (int itype), where to start looping (int iloop), and an array of integers which are the names of images loaded into OpenGL (int ipics[isize]). That's it. Just those four things. Three ints and one array of ints. (oh and also it contains the string name which is the name of itself and the file it will write to) I want to write the Anibox to a file and be able to retrieve it later. I want to write the names of the images though, not the OpenGL number which of course will be useless later. I have a separate class that holds the names of all the images loaded into OpenGL and the int that OpenGL named it. In this case, it's *picbox. picbox has a function called: string NameGrab2(int); which will return the name of the image if you send it the OpenGL name (int). So I did this:
void Anibox::Writebox()
{
ofstream outfile;
int ix;
int length;
string saver;
char *copy;

outfile.open(name.c_str(),ios::out|ios::binary);
outfile.write(reinterpret_cast<char *>(&itype),sizeof(int));
outfile.write(reinterpret_cast<char *>(&isize),sizeof(int));
outfile.write(reinterpret_cast<char *>(&iloop),sizeof(int));
for(ix=0;ix<isize;ix++)
{
saver=picbox->NameGrab2(ipics[ix]);
length=saver.length();
copy=new char[length+1];
strcpy(copy,saver.c_str());
outfile.write(reinterpret_cast<char *>(&length),sizeof(int));
outfile.write(copy,length);
delete[] copy;
}
outfile.close();
}

It works! It does exactly what I want it to do. (I think) But isn't there a better way to do it? Is there no way I can just use string.length() and the string itself directly in outfile.write? Dynamically allocating a char array just seems kind of silly.

##### Share on other sites
You can just pass c_str() to write().

##### Share on other sites
...oh yeah. I guess that is a char*. What am I smoking. I don't remember why I made a separate int to record length() either. Man.

Oh wait. I have to record string.length() into an int because write() wants everything cast as a char*. I mean this doesn't make any sense does it?:
outfile.write(reinterpret_cast<char *>(&picbox->NameGrab2(ipics[ix]).length()),sizeof(int));

I don't think you can reference a return value.

##### Share on other sites
Alright, here it is, new and improved. I don't see any way to get around copying length() into int length.

void Anibox::Writebox(){   ofstream outfile;   int ix;   int length;   outfile.open(name.c_str(),ios::out|ios::binary);   outfile.write(reinterpret_cast<char *>(&itype),sizeof(int));   outfile.write(reinterpret_cast<char *>(&isize),sizeof(int));   outfile.write(reinterpret_cast<char *>(&iloop),sizeof(int));   for(ix=0;ix<isize;ix++)   {      length=picbox->NameGrab2(ipics[ix]).length();      outfile.write(reinterpret_cast<char *>(&length),sizeof(int));      outfile.write(picbox->NameGrab2(ipics[ix]).c_str(),length);   }   outfile.close();}

##### Share on other sites
Okay I wrote this as the opposite of above. It reads from one of the files I outputted with the function above and recontructs the Anibox:
bool Anibox::Spawnbox(string anifile, ImageVault *picbox){   ifstream infile;   int ix;   string strtemp;   int length;   char *temp;   bool breturn=true;   infile.open(anifile.c_str(),ios::in|ios::binary);   if(infile.fail()==false)   {      if(ipics!=NULL)         delete[] ipics;      name=anifile;      infile.read(reinterpret_cast<char *>(&itype),sizeof(int));      infile.read(reinterpret_cast<char *>(&isize),sizeof(int));      infile.read(reinterpret_cast<char *>(&iloop),sizeof(int));      ipics=new GLuint[isize];            for(ix=0;ix<isize;ix++)      {         infile.read(reinterpret_cast<char *>(&length),sizeof(int));         temp=new char[length+1];         temp[length]='\0';         infile.read(temp,length);         strtemp="Data/Images/";         strtemp+=temp;         picbox->ImageLoader(strtemp,ipics[ix]);         delete[] temp;      }   }   else   {      breturn=false;   }   return breturn;}

Again, it works perfectly. But I don't like it. Is there a way to avoid the dynamic char array again? I'm gonna read about strings but I don't know if there's a c_str() trick for reading into strings.

##### Share on other sites
You're really terribly misusing stream objects here.

For your serialization (writing class to a sequence of bytes):

void Anibox::Writebox(){   ofstream outfile(name.c_str(), ios::out | ios::binary);   outfile << itype << L"\n";   outfile << isize << L"\n";   outfile << iloop << L"\n";   for(int i = 0; i < isize; ++i)   {      std::string thename = picbox->NameGrab2(ipics);      outfile << thename << L"\n";   }}

And to deserialize:

bool Anibox::Spawnbox(string anifile, ImageVault *picbox){   ifstream infile(anifile.c_str(), ios::in | ios::binary);      if(infile.fail())      return false;   delete[] ipics;   name=anifile;   infile >> itype;   infile >> isize;   infile >> iloop;   ipics = new GLuint[isize];   for(int i = 0; i < isize; ++i)   {      std::string temp;      getline(infile, temp);      temp = L"Data/Images/" + temp;      picbox->ImageLoader(temp, ipics);   }   return true;}

Note that we have no need to store the name string's length anymore. Also observe that we need no temporary buffers; in general if you are writing C++ and you start using char* for anything, you are probably making a huge mistake. std::string is incredibly well supported in the C++ standard library, and chances are you can use it directly for better performance and better safety.

You may also want to think of a way to avoid hard coding that "Data/Images/" path into your Anibox code. Maybe ImageLoader() should add it internally?

##### Share on other sites
What are all those capital L's before your string literals? I've never seen those before.

I read that when doing binary I/O I was supposed to use read() and write()

I don't think there's any way for string to use read(). I guess I'll try your way.

##### Share on other sites
Here's a sample of what your write function created. I thought I tried using the << >> operators with ints but I guess I didn't. So I guess it works this way.

00x80628c4100x80628c400x80628c4water1.jpg0x80628c4water2.jpg0x80628c4water3.jpg
0x80628c4water4.jpg0x80628c4water5.jpg0x80628c4water6.jpg0x80628c4water7.jpg
0x80628c4water8.jpg0x80628c4water9.jpg0x80628c4water10.jpg0x80628c4

So is this THE WAY to do it? Serialize. ios::binary. << >> operators. '\n' as delimiter and use getline()? And every other way is the dumb way? Just making sure this is the last time I have to rewrite this.

Does anybody know what that capital L is?

##### Share on other sites
I can't make it work Apoch's way. It seems like the serializing part is working. But when I try to deserialize it doesn't work. It opens the infile okay. But then it runs these three:

infile >> itype;
infile >> isize;
infile >> iloop;

And afterwards all three are still zero. It's not reading anything in. I don't get it.

*******

I tried just declaring a string and reading >> the entire file into a string and that worked. So it's reading the file. It's just not reading the serial info into ints for some reason.

##### Share on other sites
This page seems pretty sure that << and >> are for text format and read() write() are for binary format but it doesn't say why:

http://www.parashift.com/c++-faq-lite/serialization.html#faq-36.3

I'm starting to wonder if maybe I should go with text format, anyway. I just realized all I have to do is put spaces between ints and then I can use << >>. ...I didn't know that. Spaces. That's so easy. Yeah I'll probably be going with text format. This isn't a massive project and every struct makes it's own little files. I can probably master serialization some other day.

That still bugs me why I couldn't deserialize those ints. I can't figure it out.

##### Share on other sites
I can't find a flag for opening an fstream in text mode. I guess if you don't do ios::binary then it's automatically text mode.

##### Share on other sites
Quote:
 Original post by icecubeflowerDoes anybody know what that capital L is?

It is the prefix for wide characters string literals.

"foo" is a const char[4].
L"foo" is a const wchar_t[4].

Quote:
 This page seems pretty sure that << and >> are for text format and read() write() are for binary format but it doesn't say why

On a stream, the 'text' or 'binary' flag only controls whether end-of-line character translation should be performed (text) or not (binary) when performing formatted I/O. For example, on Win32 systems, when you write a '\n' onto a "text" file stream, it really writes "\r\n" into the file. When you read back, the "\r\n" sequence is translated back into a single '\n'. Opening a file in "binary" mode disables that translation. When you write a '\n', it'll go as a '\n' into the file.

Formatted I/O is what you do when you use << and >>. The stream framework takes the value you pass it, formats it in a human-readable format (e.g. the integer 42 becomes the character sequence '4' and '2') and writes it to the stream. Conversely, when reading, it does the inverse transformation. If you have written things without delimiters (such as '\n'), when you read back, you'll get a mess (write a 4 and then a 2 and you'll read back a 42). Robustly reading formatted data is a complicated (and sometimes complex) endeavor.

Unformatted I/O (read() and write()) takes the chunk of memory you pass it and writes it 'as is' into the stream, or takes a chunk of stream and copies it back into memory. This is what you really mean by 'binary'. The piece of data are fixed-size (e.g. an int is always sizeof(int) bytes) so there are no overruns from one chunk into the next. The downside is, obviously, that the data is not human-readable. It is unformatted.

##### Share on other sites
Quote:
 Original post by icecubeflowerWhat are all those capital L's before your string literals? I've never seen those before.

I'll answer this question as it's harder to find it out if you don't know what you are looking for.

The L is a literal that means the current string or character is "wide" (most commonly associated with Unicode).

For example, if your current project is set to a "Multi-Byte Character Set", which you can change in the Visual Studio project properties under the General Tab's Character Set entry, all strings and characters are interpreted as non-wide. You will notice this when trying to use Win32 functions and if you do not have the correct strings, then you will get compiler errors. For a simple example MessageBoxA(0, L"", L"", 0) 0) will always fail to compile, where as MessageBoxW(0, "", "", 0); will only fail to compile on a Multi-Byte Character Set project.

If you execute the code: std::cout << "Hi"; you will see "Hi" printed out. If you were to execute the code: std::cout << L"Hi";, then you would not see "Hi", you would see the address of the string since cout will only output non-wide characters and strings.

If you were to execute the code: std::wcout << L"Hi";, then you would see "Hi" since wcout is "wide cout" and since you are passing in a wide string, it works properly. Likewise, you can also use std::wcout << "Hi"; and you will see "Hi" due to how the C++ operator << coupled with the special object wcout is used. You shouldn't get errors here like you would previously.

Ninja'ed by Fruny, I so didn't see that one coming [grin]

##### Share on other sites
Quote:
 Original post by icecubeflowerDoes anybody know what that capital L is?
Wide strings. Each character will be two bytes instead of one.

##### Share on other sites
Quote:
 Original post by icecubeflowerHere's a sample of what your write function created. I thought I tried using the << >> operators with ints but I guess I didn't. So I guess it works this way.00x80628c4100x80628c400x80628c4water1.jpg0x80628c4water2.jpg0x80628c4water3.jpg0x80628c4water4.jpg0x80628c4water5.jpg0x80628c4water6.jpg0x80628c4water7.jpg0x80628c4water8.jpg0x80628c4water9.jpg0x80628c4water10.jpg0x80628c4So is this THE WAY to do it? Serialize. ios::binary. << >> operators. '\n' as delimiter and use getline()? And every other way is the dumb way? Just making sure this is the last time I have to rewrite this.Does anybody know what that capital L is?

My mistake - I'm used to working with wide strings so I just added the L prefixes out of habit [smile]

Removing them in your code should get the serialization half to format more nicely, and in turn should get the deserialization code to work correctly. (Just make sure that if you use something like the std::hex formatter that you use it on both ends.)

##### Share on other sites
Quote:
Original post by iMalc
Quote:
 Original post by icecubeflowerDoes anybody know what that capital L is?
Wide strings. Each character will be two bytes instead of one.

wchar_t's actual size is implementation-defined. It could be one (same as a char), just as it could be four. You can only portably rely on it being sizeof(wchar_t).

##### Share on other sites
Quote:
 On a stream, the 'text' or 'binary' flag only controls whether end-of-line character translation should be performed

That's it? That's all it does? That doesn't make any sense to me. Wait, hold on.
Augh! That's all it does! I took out the capital L's and did Apoch's write function and got this:
02919cartoon1.jpgcartoon2.jpgcartoon3.jpgcartoon4.jpgcartoon5.jpgcartoon6.jpgcartoon7.jpgcartoon8.jpgcartoon9.jpgcartoon10.jpgcartoon11.jpgcartoon12.jpgcartoon13.jpgcartoon14.jpgcartoon15.jpgcartoon16.jpgcartoon17.jpgcartoon18.jpgcartoon19.jpgcartoon20.jpgcartoon21.jpgcartoon22.jpgcartoon23.jpgcartoon24.jpgcartoon25.jpgcartoon26.jpgcartoon27.jpgcartoon28.jpgcartoon29.jpg

I thought binary was what was making all those 00xAADFD things. Man.

That's funny. I went and redid everything in text mode and then I realized the functions I wrote were the same as Apochs.

Except getline() wasn't working for me. The very first getline() read an empty string. And then after that it read cartoon1, cartoon2, etc. So then I switched to the >> operator and that worked. I wonder if I did it Apoch's way now in binary if getline() will work. It basically worked before, it's just in text mode somewhere between the 19, the '\n' and cartoon1 it goofed up and read an empty string.

##### Share on other sites
Quote:
Original post by icecubeflower
Quote:
 On a stream, the 'text' or 'binary' flag only controls whether end-of-line character translation should be performed

That's it? That's all it does? That doesn't make any sense to me.

It's ... historical.

Quote:
 I thought binary was what was making all those 00xAADFD things. Man.

If you open a text editor and read "0xAADF", it is still text. You just formatted it as hexadecimal rather than decimal. If you open a hex editor and read AA DF, then it really is unformatted binary.

The result depends on the functions you use to write the data, not on the mode you used to open the file -- though if you open the file in text mode and try to do unformatted I/O, you are asking for trouble. :)

##### Share on other sites
Apoch's deserialization still doesn't work for me. I can do it exactly the way he does it but getline() always reads an empty string on i==0. I just changed it to the >> operator and then it works fine.

bool Anibox::Spawnbox(string anifile, ImageVault *picbox){   ifstream infile(anifile.c_str(), ios::in | ios::binary);      if(infile.fail())      return false;   delete[] ipics;   name=anifile;   infile >> itype;   infile >> isize;   infile >> iloop;   ipics = new GLuint[isize];   for(int i = 0; i < isize; ++i)   {      std::string temp;      //getline(infile, temp);      infile>>temp;      temp = "Data/Images/" + temp;      picbox->ImageLoader(temp, ipics);   }   return true;}

##### Share on other sites
Yeah, another oversight on my part - when you read the last integer, it only skips past the numerals themselves in the input stream. When the next read comes along (the getline call), the next data available to be read is the \n immediately following the integer. So that gets read (which results in an empty read) and then you proceed on to the next few strings as normal.

As long as you don't have spaces in your filenames, using the >> operator should work fine.

##### Share on other sites
So if I wanted to use getline() I guess I'd have to eat that '\n' somehow or seekg forward one byte or something.

##### Share on other sites
Hey Apoch, you said this:
Quote:
 You may also want to think of a way to avoid hard coding that "Data/Images/" path into your Anibox code. Maybe ImageLoader() should add it internally?

So what's the professional way to handle file I/O? The way I have it right now I assume there's a directory called "Data" in the same directory as the executable. And in the Data directory there are other directories like "Images" and "Sounds".

project5/project5 (executable)
project5/Data/Sounds
project5/Data/Images
project5/Data/Maps
porject5/Data/Anibox

But now in my code there's lots of places where I hard code "Data/Images" or whatever and load it into a string. It's a little sporadic where I do it at. Is it better form to put all that directory info into one place? Like ImageLoader ALWAYS looks for files in "Data/Images" and if it's not there then it says it can't find it? And the map loader always loads and writes to "Data/Maps" so it never needs to be passed directory info?

And then would it be even better to have a separate .h file where I #define all the directory names like

#define IMAGEDIR "Data/Images"
#define MAPDIR "Data/Maps"

##### Share on other sites
Using #defines is not really a great idea. If anything you should just use constant strings.

If you want to keep things flexible, store your directory names in a config file and read that prior to doing any other file IO.

Note that there's nothing wrong with hardcoding your paths per se; but you should centralize that information instead of scattering it all across your code.

I'd suggest just a simple solution like this:

namespace FileLocations{   const char* PathToImages = "path/to/images/";   const char* PathToAudio = "path/to/audio/";   // etc.}

Then you can access the path definition with a simple FileLocations::PathToFoo, which is clear, self-explanatory, and avoids needless repetition of the path information.

Sounds good.

##### Share on other sites
Quote:
Original post by icecubeflower
Quote:
 On a stream, the 'text' or 'binary' flag only controls whether end-of-line character translation should be performed

That's it? That's all it does? That doesn't make any sense to me.

Like Fruny says, it's "historical". There actually is one more difference: in text mode, there will typically be a specific byte that is interpreted as an "end of file" marker. Under Windows, this is the byte with value 26; under Linux, the byte with value 4. You can, incidentally, trigger "end of file" on std::cin by supplying those characters; they're typed with control-Z and control-D respectively. (The control key plus A through Z are mapped to characters 1 through 26, oddly enough. And if you want to annoy people (including yourself), try writing character 7 to std::cout multiple times.)

Quote:
 I thought binary was what was making all those 00xAADFD things. Man.

All files are composed of bytes. They do not "contain" text nor numbers nor anything else. That is an interpretation we impose upon them. Each byte, if you're on a sufficiently "normal" computer and are not using Unicode, is an 8-bit integral value that is interpreted as a character of text using the 'ASCII' mapping.

Consider the abstract concept of the number sixty-five. This is a small enough number to represent in 8 bits, so there is a single byte with that value. A file could well contain a byte with that value, and if you looked at it with a text editor, you would see the character 'A'. If you looked at it in a hex editor, you would see the value 41, which is sixty-five written in hexadecimal (base sixteen) - hence "hex". The hex editor would display the character for the digit symbol '4' and the character for the digit symbol '1', because that's how it's programmed.

That file could be meant to represent the text "A". But it could also be meant to represent the number sixty-five. The interpretation is up to whatever program is reading the file.

You could also, however, have a file which contains the two bytes that represent the text "65", which would then be interpreted by a person reading the file as the number sixty-five. If you open this file in a text editor, you see the character '6' followed by the character '5', making the text "65" (which happens to be something we interpret as a number) on screen. If you open it in a hex editor, you see the characters '3635', where '36' represent the first byte (54 in hex) and '35' represent the second byte (53 in hex).

Now, when you read in from a file using operator>>, with an integer type variable as the destination (short, int, long, or the unsigned variations of those), the resulting code attempts to read several bytes from the current file position "as a human would". That is, it would read the byte '6' (with value 54) and the byte '5' (with value 53) from the second file, and interpret those as digits 6 and 5 of a base ten number, and store the value 65 in the variable. It would fail on the first file, because the symbol 'A' is not used for writing numbers in base ten.

The behaviour of operator>> depends on the type of the destination variable. This is a deliberate design decision made so that the operator can "do the right thing" and interpret "human-readable" (a term often confused with "text") data. However, for all primitive types (and you'll need to remember this for later), the operator will skip past any "leading" whitespace at the current position in the stream, but leave any "trailing" whitespace behind, if a value is successfully read.

if you read into a 'char', for example, the stream will skip any whitespace, and then (assuming there is any data left in the source at all) read the first non-whitespace byte of the file into the variable. (Remember, a char is a byte, even when a char is not 8 bits - i.e. a byte is not necessarily 8 bits in C++! That is only a minimum value; bytes are allowed to be larger. But "on sufficiently normal systems", they are not larger.)

Quote:
 Except getline() wasn't working for me. The very first getline() read an empty string. And then after that it read cartoon1, cartoon2, etc.

std::getline() reads up to the first delimiter ('\n', by default) that it finds in the file. An empty string is a perfectly valid line of text - an empty line. Thus, if the stream is at a point where the very next character is '\n', then an empty line is read.

Now, consider what happens if your file contains a human-readable number, immediately followed by '\n', and then you use operator>> to read the human-readable number. The trailing whitespace is left alone, and '\n' is a kind of whitespace, so the stream is now at a point where the very next character is '\n'. :)

Quote:
 So then I switched to the >> operator and that worked.

The operator>>, when told to read into a string (either char* or std::string), will only read up to the next whitespace. If you want to read multiple words, it will not work.

Quote:
 I wonder if I did it Apoch's way now in binary if getline() will work.

Whether the file is binary or not has almost no bearing on what will happen when you call std::getline(). The only thing that happens is that in text mode, \r\n sequences in the file data will be interpreted as if the file actually contained \n (so the lines that you read in will not contain \r).

Quote:
 It basically worked before, it's just in text mode somewhere between the 19, the '\n' and cartoon1 it goofed up and read an empty string.

I still don't think you were understanding this properly (streams don't spontaneously change mode, which is what it sounds like you're saying), but hopefully the above has cleared things up.

If you want to avoid the problem with mixing operator>> and std::getline(), the standard recommendation is to:

1) Always use std::getline() for initial reads from the file; and then
2) If you need to extract human-readable numbers (or other stuff) out of a line, construct a std::stringstream object from the read-in line, and call operator>> on the stringstream.

This also gains you some robustness in the face of corrupt data. (Axiom: input is always harder to do than output. Of course, the part in between is usually even harder. :) ) If a line is supposed to contain a number but doesn't, the std::stringstream will "fail", but the file stream is unaffected.

Of course, that doesn't work so well if you have an operator>> overload for a class that expects to read multiple lines ;) In general, you have to Think(TM). Sorry! :)


text:
# Introduction

The clmplus package provides practitioners with a fast and user friendly implementation of the modeling framework we derived in our paper Pittarello G., Hiabu M., and Villegas A., Chain ladder Plus: a versatile approach for claims reserving, (pre-print, 2022).

We were able to connect the well-known hazard models developed in life insurance to non-life run-off triangles claims development. The flexibility of this approach goes beyond the methodological novelty: we hope to provide a user-friendly set of tools based on the point of contact between non-life insurance and life insurance in the actuarial science.

This vignette is organized as follows:

• We show the connection between the age-period representation and run-off triangles.

• We replicate the chain-ladder model with an age-model. As shown in the paper, by using the clmplus approach the resulting model is saving some parameters with respect to the standard GLM approach.

• We show an example where adding a cohort effect can lead to an improvement on the model fit.

In this tutorial, we show an example on the AutoBIPaid run-off triangle from the ChainLadder package.

## One discipline, one language

Consider the data set we chose for this tutorial.

The run-off triangle representation is displayed below:

library(ChainLadder)

data("AutoBI")
dataset=AutoBI$AutoBIPaid dataset #> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] #> [1,] 1904 5398 7496 8882 9712 10071 10199 10256 #> [2,] 2235 6261 8691 10443 11346 11754 12031 NA #> [3,] 2441 7348 10662 12655 13748 14235 NA NA #> [4,] 2503 8173 11810 14176 15383 NA NA NA #> [5,] 2838 8712 12728 15278 NA NA NA NA #> [6,] 2405 7858 11771 NA NA NA NA NA #> [7,] 2759 9182 NA NA NA NA NA NA #> [8,] 2801 NA NA NA NA NA NA NA colnames(dataset)=c(0:(dim(dataset)[1]-1)) rownames(dataset)=c(0:(dim(dataset)[1]-1)) Practitioners in general insurance refer to the x axis of this representation as development years. Similarly, the y axis is called accident years. The third dimension that matters is the diagonals: the calendar years. There is a one-to-one correspondence between the age-period representation and run-off triangles. In notional terms, life insurance actuaries use the following terminology: • ages are development years. • cohorts are accident years. • periods is calendar years. Indeed, the age-period representation of the run-off triangle is the following: #> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] #> [1,] 1904 2235 2441 2503 2838 2405 2759 2801 #> [2,] NA 5398 6261 7348 8173 8712 7858 9182 #> [3,] NA NA 7496 8691 10662 11810 12728 11771 #> [4,] NA NA NA 8882 10443 12655 14176 15278 #> [5,] NA NA NA NA 9712 11346 13748 15383 #> [6,] NA NA NA NA NA 10071 11754 14235 #> [7,] NA NA NA NA NA NA 10199 12031 #> [8,] NA NA NA NA NA NA NA 10256 Observe that the y axis is now the development years (or age) component. Calendar years (or periods) are displayed on the x axis. Accident years (or cohorts) are on the diagonals. # Replicate the chain-ladder with the clmplus package clmplus is an out-of-the box set of tools to compute the claims reserve. We now show how to replicate the chain ladder model. Observe the run-off triangle data structure first needs to be initialized to a RtTriangle object. Starting from the results in the paper we showed how to replicate the chain ladder with an age model. The computation on the RtTriangle object is computed with the method clmplus specifying an hazard model. a.model=clmplus(RtTriangle = rtt, hazard.model = "a") #> StMoMo: The following ages have been zero weighted: 1 #> StMoMo: The following years have been zero weighted: 1 #> StMoMo: The following cohorts have been zero weighted: -7 -6 -5 -4 -3 -2 -1 7 #> StMoMo: Start fitting with gnm #> StMoMo: Finish fitting with gnm We show the consistency of our approach by comparing our estimates with those obtained with the Mack chain ladder method as implemented in the ChainLadder package. mck.chl <- MackChainLadder(dataset) ultimate.chl=mck.chl$FullTriangle[,dim(mck.chl$FullTriangle)[2]] diagonal=rev(t2c(mck.chl$FullTriangle)[,dim(mck.chl$FullTriangle)[2]]) Estimates are gathered in a data.frame to ease the understanding. data.frame(ultimate.cost.mack=ultimate.chl, ultimate.cost.clmplus=a.model$ultimate.cost,
reserve.mack=ultimate.chl-diagonal,
reserve.clmplus=a.model$reserve ) #> ultimate.cost.mack ultimate.cost.clmplus reserve.mack reserve.clmplus #> 0 10256.00 10256.00 0.00000 0.00000 #> 1 12098.24 12098.24 67.23865 67.23865 #> 2 14580.19 14580.19 345.18727 345.18727 #> 3 16323.69 16323.69 940.68770 940.68770 #> 4 17628.86 17628.86 2350.85562 2350.85562 #> 5 16237.77 16237.77 4466.77443 4466.77443 #> 6 18285.24 18285.24 9103.24335 9103.24335 #> 7 17281.44 17281.44 14480.43832 14480.43832 cat('\n Total reserve:', sum(a.model$reserve))
#>
#>  Total reserve: 31754.43

## Claims reserving with GLMs compared to hazard models

We fit the standard GLM model with the apc package. As shown in the paper the chain-ladder model can be replicated by fitting an age-cohort model.

library(apc)

ds.apc = apc.data.list(cum2incr(dataset),
data.format = "CL")

ac.model.apc = apc.fit.model(ds.apc,
model.family = "od.poisson.response",
model.design = "AC")

Inspect the model coefficients derived from the output:

ac.model.apc$coefficients.canonical[,'Estimate'] #> level age slope cohort slope DD_age_3 DD_age_4 DD_age_5 #> 7.41596168 0.74105900 0.16519698 -1.16411707 -0.02909890 -0.17467013 #> DD_age_6 DD_age_7 DD_age_8 DD_cohort_3 DD_cohort_4 DD_cohort_5 #> -0.17533888 0.17408744 -0.55360421 0.02140672 -0.07364998 -0.03603392 #> DD_cohort_6 DD_cohort_7 DD_cohort_8 #> -0.15911660 0.20095088 -0.17521544 ac.fcst.apc = apc.forecast.ac(ac.model.apc) data.frame(reserve.mack=ultimate.chl-diagonal, reserve.apc=c(0,ac.fcst.apc$response.forecast.coh[,'forecast']),
reserve.clmplus=a.model$reserve ) #> reserve.mack reserve.apc reserve.clmplus #> 0 0.00000 0.00000 0.00000 #> 1 67.23865 67.23865 67.23865 #> 2 345.18727 345.18727 345.18727 #> 3 940.68770 940.68770 940.68770 #> 4 2350.85562 2350.85562 2350.85562 #> 5 4466.77443 4466.77443 4466.77443 #> 6 9103.24335 9103.24335 9103.24335 #> 7 14480.43832 14480.43832 14480.43832 Our method is able to replicate the chain-ladder results with no need to add the cohort component. a.model$model.fit\$ax
#>           1           2           3           4           5           6
#>          NA  0.02366899 -1.01313612 -1.72538123 -2.48027780 -3.34130515
#>           7           8
#> -3.99615988 -5.18978418

Further inspection can be performed with the clmplus package, which provides the graphical tools to inspect the fitted effects. Observe we model the rate in continuous time, the choice of a line plot is then consistent.

plot(a.model)

# The benefitial effect of adding the cohort component

It is straightforward to state that from the statistical perspective it is desirable to have a model with less parameters. Nevertheless, our approach goes far beyond that.

By adding the cohort effect we are able to improve our modeling.

We show these results by inspecting the residuals plots.

#make it triangular
plotresiduals(a.model)

Clearly, the red and blue areas suggest some trends that the model wasn’t able to catch. Consider now the age-cohort model and its residuals plot.

ac.model <- clmplus(rtt,
hazard.model="ac",
gk.fc.model='a')
#> StMoMo: The following ages have been zero weighted: 1
#> StMoMo: The following years have been zero weighted: 1
#> StMoMo: The following cohorts have been zero weighted: -7 -6 -5 -4 -3 -2 -1 7
#> StMoMo: Start fitting with gnm
#> StMoMo: Finish fitting with gnm
plotresiduals(ac.model)

With no need of extrapolating a period component, we were able to improve the fit already. Pay attention, the cohort component for the cohort m is extrapolated.

plot(ac.model)

## Extrapolation of a period component

Similarly, it is possible to add a period component and choose an age-period model or an age-period-cohort model.

ap.model = clmplus(rtt,
hazard.model = "ap",
ckj.fc.model='a',
ckj.order = c(0,1,0))
#> StMoMo: The following ages have been zero weighted: 1
#> StMoMo: The following years have been zero weighted: 1
#> StMoMo: The following cohorts have been zero weighted: -7 -6 -5 -4 -3 -2 -1 7
#> StMoMo: Start fitting with gnm
#> StMoMo: Finish fitting with gnm

apc.model = clmplus(rtt,hazard.model = "apc",
gk.fc.model='a',
ckj.fc.model='a',
gk.order = c(1,1,0),
ckj.order = c(0,1,0))
#> StMoMo: The following ages have been zero weighted: 1
#> StMoMo: The following years have been zero weighted: 1
#> StMoMo: The following cohorts have been zero weighted: -7 -6 -5 -4 -3 -2 -1 7
#> StMoMo: Start fitting with gnm
#> StMoMo: Finish fitting with gnm
plotresiduals(ap.model)

It can be seen that the age-period model does not suggest any serious improvement from the age-cohort model. It is worth noticing one more time that the age-cohort model does not require any extrapolation. In a similar fashion, we plot the age-period-cohort model below, which seems to lead us to a small improvement.

plotresiduals(apc.model)

Below, the effects of the age-period-cohort model.

plot(apc.model)

# Conclusions

In this vignette we wanted to show the flexibility of our modeling approach with respect to the well-known chain-ladder model.

• By modeling the hazard rate we are able to replicate the chain-ladder results with less parameters. Indeed, we model the age component directly and add a cohort effect if needed.

• Going from an age model to an age-cohort model may lead to a serious improvement in the model results.


text:
# Analytic Functions on Upper Half Plane Satisfying Inequality

Original Problem. Let $\mathbb{H}=\left\{z\in\mathbb{C} : \Im(z)>0\right\}$ be the open upper half plane. Determine all analytic functions $f:\mathbb{H}\rightarrow\mathbb{C}$ that satisfy the inequality

$$\left|f(z)\right|\leq\Im(z) \tag{1}$$

This is an old qual problem which I at first found deceptively simple and asked for a fresh set of eyes. The solution is straightforward. The inequality implies $f$ has a continuous extension $\tilde{f}:\overline{\mathbb{H}}\rightarrow\mathbb{C}$ to the closed upper half plane by setting $\tilde{f}(x):=0$ for all $x\in\mathbb{R}$. By Schwarz reflection, we obtain an entire function $\tilde{f}:\mathbb{C}\rightarrow\mathbb{C}$ which vanishes on the real axis. By the identity theorem, $\tilde{f}\equiv 0$, implying $f\equiv 0$.

I tried coming up with another solution, for example using maximum modulus principle, but didn't get anywhere. So if anyone has a different proof, I would be interested in seeing it.

At the suggestion of David C. Ullrich, we consider the problem of determining harmonic functions in the upper half plane satisfying the same inequality.

Problem. With $\mathbb{H}$ as above, determine all harmonic functions $f:\mathbb{H}\rightarrow\mathbb{C}$ (i.e. $\Delta f=0$) that satisfy the inequality in (1).

An answer to this problem has been posted below.

• It is that simple. – Daniel Fischer Jul 6 '15 at 19:03
• Ok, that's too easy, now find all the real-valued harmonic functions in the upper half-plane satisfying the same inequality... – David C. Ullrich Jul 6 '15 at 19:51

Your solution is fine. (Answered to keep the question off the unanswered list.)

Any harmonic function $u$ in the upper half space $\mathbb{H}^{+}\simeq\mathbb{R}_{+}^{2}$ which extends to a continuous function on $\overline{H^{+}}$, vanishing on the real line, extends to a harmonic function on the whole plane by Schwarz reflection. If such $u$ grows at most polynomially in bounded, then it defines a tempered distribution in $\mathcal{S}'(\mathbb{R}^{2})$.

We make use of the following two results. A proof of the first one can be found in [L. Grafakos, Classical Fourier Analysis, Third Edition, Proposition 2.4.1], and the second is elementary.

Theorem. Let $u\in\mathcal{S}'(\mathbb{R}^{n})$ be a tempered distribution. If $u$ is supported in the set $\left\{x\right\}$, then \begin{align*} u=\sum_{\left|\alpha\right|\leq k}c_{\alpha}\partial^{\alpha}\delta_{x} \end{align*} for some nonnegative integer $k$, where $c_{\alpha}\in\mathbb{C}$.

and under the Fourier transform convention

$$\widehat{\phi}(\xi)=\int_{\mathbb{R}^{n}}\phi(x)e^{-2\pi i x\cdot \xi}\mathrm{d}x, \qquad\forall \xi\in\mathbb{R}^{n}$$

Lemma. If $u=(-2\pi i x)^{\alpha}$, then $\widehat{u}=(-1)^{\left|\alpha\right|}\partial^{\alpha}\delta$.

Taking inverse Fourier transforms, we conclude that the harmonic function $u$ must be of the form \begin{align*} u(x,y)=\sum_{\left|\alpha\right|\leq k}c_{\alpha}(2\pi i xy)^{\alpha} \end{align*} for some integer $k$. The condition that $\left|u(x,y)\right|\leq\left|y\right|$ forces $c_{\alpha}=0\Leftrightarrow \alpha=(0,1)$ and for such $\alpha$, $\left|c_{\alpha}(2\pi i )\right|=1$. We conclude that $u(x,y)=e^{i\theta}y$, for some fixed $\theta\in [0,2\pi)$. If we require $u$ to be real-valued, then $u(x,y)=y$.


text:
# Hill sphere

642pages on
this wiki

A Hill sphere approximates the gravitational sphere of influence of one astronomical body in the face of perturbations from another heavier body around which it orbits. It was defined by the American astronomer George William Hill. It is also called the Roche sphere because the French astronomer Édouard Roche independently described it.

Considering a central body and a second body in orbit around it (for example the Sun and Jupiter), the Hill sphere is derived from consideration of the following three vector fields:

• gravity due to the central body
• gravity due to the second body
• the centrifugal force in a frame of reference rotating about the central body with the same angular frequency as the second body

The Hill sphere is the largest sphere, centered at the second body, within which the sum of the three fields is directed towards the second body. A small third body can orbit the second within the Hill sphere, with this resultant force as centripetal force.

The Hill sphere extends between the Lagrangian points L1 and L2, which lie along the line of centers of the two bodies. The region of influence of the second body is shortest in that direction, and so it acts as the limiting factor for the size of the Hill sphere. Beyond that distance, a third object in orbit around the second (Jupiter) would spend at least part of its orbit outside the Hill sphere, and would be progressively perturbed by the tidal forces of the central body (the Sun) and would end up orbiting the latter.

The Roche sphere is not to be confused with the Roche lobe and Roche limit which were also described by Roche. The Roche limit which is the distance at which an object held together only by gravity begins to break up due to tidal forces. The Roche lobe describes the limits at which an object which is in orbit around two other objects will be captured by one or the other.

## Formula and examples

If the mass of the smaller body is m, and it orbits a heavier body of mass M with a semi-major axis a and an eccentricity of e, then the radius r of the Hill sphere for the smaller body is [1]

$r \approx a (1-e) \sqrt[3]{\frac{m}{3 M}}$

When eccentricity is negligible (the most favourable case for orbital stability), this becomes

$r \approx a \sqrt[3]{\frac{m}{3 M}}$

For example, the Earth (5.97×1024 kg) orbits the Sun (1.99×1030 kg) at a distance of 149.6 Gm. The Hill sphere for Earth thus extends out to about 1.5 Gm (0.01 AU). The Moon's orbit, at a distance of 0.370 Gm from Earth, is comfortably within the gravitational sphere of influence of Earth and is therefore not at risk of being pulled into an independent orbit around the Sun. In terms of orbital period: the Moon has to be within the sphere where the orbital period is not more than 7 months.

The formula can be re-stated as follows:

$3\frac{r^3}{a^3} \approx \frac{m}{M}$

This expresses the relation in terms of the volume of the Hill sphere compared with the volume of the second body's orbit around the first; specifically, the ratio of the masses is three times the ratio of these two spheres.

A quick way of estimating the radius of the Hill sphere comes from replacing mass with density in the above equation:

$\frac{r}{R_{secondary}} \approx \frac{a}{R_{primary}} \sqrt[3]{\frac{\rho_{secondary}}{3 \rho_{primary}}} \approx \frac{a}{R_{primary}}$

where $\rho_{second}$ and $\rho_{primary}$ are the densities of the primary and secondary bodies, and $\frac{r}{R_{secondary}}$ and $\frac{r}{R_{primary}}$ are their radii. The second approximation is justified by the fact that, for most cases in the solar system, $\sqrt[3]{\frac{\rho_{secondary}}{3 \rho_{primary}}}$ happens to be close to one. (The Earth-Moon system is the largest exception, and this approximation is within 20% for most of Saturn's satellites.) This is also convenient, since many planetary astronomers work in and remember distances in units of planetary radii.

An astronaut could not orbit the Space Shuttle (mass = 104 tonnes), if the orbit is 300 km above the Earth, since the Hill sphere is only 120 cm in radius, much smaller than the shuttle itself. In fact, in any low Earth orbit, a spherical body must be 800 times denser than lead in order to fit inside its own Hill sphere, or else it will be incapable of supporting an orbit. A spherical geostationary satellite would need to be more than 5 times denser than lead to support satellites of its own; such a satellite would be 2.5 times denser than iridium, the densest naturally-occurring material on Earth. Only at twice the geostationary distance could a lead sphere possibly support its own satellite; the moon itself must be at least 3 times the geostationary distance, or 2/7 its present distance, to make lunar orbits possible.

The Hill sphere is but an approximation, and other forces (such as radiation pressure) can make an object deviate from within the sphere. The third object must also be of small enough mass that it introduces no additional complications through its own gravity. Orbits at or just within the Hill sphere are not stable in the long term; from numerical methods it appears that stable satellite orbits are inside 1/2 to 1/3 of the Hill radius (with retrograde orbits being more stable than prograde orbits).

Within the solar system, the planet with the largest Hill sphere is Neptune, with 116 Gm, or 0.775 AU; its great distance from the Sun amply compensates for its small mass relative to Jupiter (whose own Hill sphere measures 53 Gm). An asteroid from the main belt will have a Hill sphere that can reach 220 Mm (for 1 Ceres), diminishing rapidly with its mass. In the case of (66391) 1999 KW₄, a Mercury-crosser asteroid which has a moon (S/2001 (66391) 1), the Hill sphere varies between 120 and 22 km in radius depending on whether the asteroid is at its aphelion or perihelion!


text:
# Norm of linear functional; can we take supremum over dense subset?

If $V \subset H$ are Hilbert spaces and $V$ is dense in $H$, is it true that for $f \in H^*$, $$\lVert f \rVert_{H^*} = \sup_{v \in V} \frac{|f(v)|}{\lVert v \rVert_V}?$$ So I mean can we just take the supremum in the definition of the norm of $f$ over the dense subset?

-
A complete subspace is a closed subspace. A dense closed subset is the whole space. You should require only that $V$ is a subspace. – JSchlather Nov 29 '12 at 19:25

Yes: let $v_n$ of norm $1$ such that $f(v_n)\geqslant \lVert f\rVert_{H^*}-n^{-1}$. Then let $v'_n\in V$ such that $\lVert v_n-v'_n\rVert\leqslant n^{-1}$. Then $$|f(v'_n)|=|f(v_n)-f(v_n-v'_n)|\geqslant |f(v_n)|-|f(v_n-v'_n)|\geqslant\lVert f\rVert_{H^*}-n^{-1}-\lVert f\rVert_{H^*}n^{-1},$$ which gives $$\lVert f\rVert(1-n^{-1})^{-1}\geqslant\left|f\left(\frac 1{\lVert v'_n\rVert}v'_n\right)\right|\geqslant (1+n^{-1})^{-1}\left(\lVert f\rVert_{H^*}-n^{-1}(1+\lVert f\rVert_{H^*})\right).$$ The result follows.
In what I did, I don't think I used the property of subspace of $V$. – Davide Giraudo Dec 1 '12 at 12:02
what if the norms of $V$ and $H$ are different? – maximumtag Mar 7 '13 at 18:03


text:
# Introduction

This is an R notebook document. It allows you to mix R code, notes and outputs with nice formatting and is a nice way to record and present R analyses. You can create one of these documents in newer versions of R studio by going to File > New File > R Notebook.

I’ll use this notebook to provide worked answers to all of the exercises we did in the course.

# Introduction to R

## Exercise 1

• Use R to calculate

• 31 * 78

• 697/41

These are just simple mathematical expressions entered on the console.

31 * 78
## [1] 2418
697 / 41
## [1] 17
• Assign the value of 39 to x
• Assign the value of 22 to y
• Make z the value of x-y
• Display z in the console

Here we use the arrow symbols to make the assignments. They can point left or right but they must point from the data towards the variable name in which you want to store them.

You can retrieve the data stored in a variable by just entering the varible name.

39 -> x
y <- 22
x-y -> z
z
## [1] 17
• Calculate the square root of 2345 and perform a log2 transformation on the result

Both of these operations require the use of functions. The ideal solution is to nest the two function calls together so that the call to sqrt is inside the arguments to log2.

log2(sqrt(2345))
## [1] 5.597686

## Exercise 2

• Create a vector called vec1 containing the number 2 5 8 12 16

There is no mathematical relationship between these numbers so we need to manually create the vector using the ‘c’ function.

c(2,5,8,12,16) -> vec1
• Use x:y notation to make a second vector called vec2 containing the numbers 5 to 9

Because this is a series we can take a shortcut to make it using the language shortcut which makes integer series between two values.

5:9 -> vec2
• Subtract vec2 from vec1 and look at the result
vec1 - vec2
## [1] -3 -1  1  4  7

Because we have the same number of values in both vec1 and vec2 the equivalent positions will be paired up and we will see the subtraction results from the same positions, ie 2-5, 5-6, 8-7 etc.

• Use seq() to make a vector of 100 values starting at 2 and increasing by 3 each time.

We need to supply the from, by and length.out parameters to seq to create this series. As we’re using this in the next exercise we will save it into a new variable.

seq(from=2,by=3,length.out=100) -> number.series

number.series
##   [1]   2   5   8  11  14  17  20  23  26  29  32  35  38  41  44  47  50
##  [18]  53  56  59  62  65  68  71  74  77  80  83  86  89  92  95  98 101
##  [35] 104 107 110 113 116 119 122 125 128 131 134 137 140 143 146 149 152
##  [52] 155 158 161 164 167 170 173 176 179 182 185 188 191 194 197 200 203
##  [69] 206 209 212 215 218 221 224 227 230 233 236 239 242 245 248 251 254
##  [86] 257 260 263 266 269 272 275 278 281 284 287 290 293 296 299
• Extract the values at positions 5,10,15 and 20 in the vector of values you just created.
• Extract the values at positions 10 to 30

Both of these require making a selection in the vector using the [ ] notation. Inside the square brackets you put a vector of index positions, so the problem here is to create the vector of index positions.

The first one is small enough that you could make it manually with c() or as it’s a series you could use seq() to make it. It doesn’t matter which.

The second one is an integer series so we can use the 10:30 notation to make this quickly.

number.series[c(5,10,15,20)]
## [1] 14 29 44 59
number.series[seq(from=5,to=20,by=5)]
## [1] 14 29 44 59
number.series[10:30]
##  [1] 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89

## Exercise 3

• Enter a list of colours (supplied in the question) into a vector called mouse.colour

We will use the c() function to manually make this vector. Because the data we are entering is text we need to surround each name with quotes so that R doesn’t try to treat it as a variable name.

c("purple","red","yellow","brown") -> mouse.colour
• Display the second element in the vector.

This is a simple selection with a single index position.

mouse.colour[2]
## [1] "red"

Enter some numerical weight data (supplied in the question) into a vector called mouse.weight

c(23,21,18,26) -> mouse.weight
• Join the two vectors into a data frame called mouse.info containing 2 columns and 4 rows. Call the first column colour and the second one weight.

We will use the data.frame() function to do this. We don’t need to specify the number of rows / columns as these are defined by the data we use to create the data frame. The number of columns is the number of vectors we provide and the number of rows is the number of data points in each of those vectors.

If we pass the vectors to the data.frame() function as name=vector pairs then we can set the names for the columns when we create the data frame.

Remember that data.frame() will not save the result - you still need to use an arrow at the end to give it a name. You will see that the notebook formats the data frame we get as a nice looking table.

data.frame(colour=mouse.colour, weight=mouse.weight) -> mouse.info

mouse.info
##   colour weight
## 1 purple     23
## 2    red     21
## 3 yellow     18
## 4  brown     26
• Display just row 3
• Display just column 1
• Display row 4 column 1

All of these use 2 dimensional selections on the data frame. You again use the [ ] notation but this time you need to pass two vectors, the first for the rows and the second for the columns.

When we are pulling out a single column we can also use the [[ ]] notation, or ideally use dataframe$column notation as we have a named column. mouse.info[3,] ## colour weight ## 3 yellow 18 mouse.info[,1] ## [1] purple red yellow brown ## Levels: brown purple red yellow mouse.info[[1]] ## [1] purple red yellow brown ## Levels: brown purple red yellow mouse.info$colour
## [1] purple red    yellow brown
## Levels: brown purple red yellow
mouse.info[4,1]
## [1] brown
## Levels: brown purple red yellow

The reason you see the text saying “Levels:…” after each line is because R converts character vectors to factor vectors when you create a data frame. A factor vector stores all of the different values it can store as a separate property, and this is what is shown in the levels value.

## Exercise 4

We could do this through the R studio interface using Session -> Set Working Directory -> Choose directory but in this script I will have to call setwd() directly. Because of the way notebooks work I’ll have to re-do this in every section which loads data.

setwd("O:/Training/Introduction to R/R_intro_data_files")
• Read the file “small_file.txt” into a new structure

This is a tab delimited file so we can use read.delim for this.

setwd("O:/Training/Introduction to R/R_intro_data_files")
small.file
##    Sample Length Category
## 1     x_1     45        A
## 2     x_2     82        B
## 3     x_3     81        C
## 4     x_4     56        D
## 5     x_5     96        A
## 6     x_6     85        B
## 7     x_7     65        C
## 8     x_8     96        D
## 9     x_9     60        A
## 10   x_10     62        B
## 11   x_11     80        C
## 12   x_12     63        D
## 13   x_13     50        A
## 14    y_1     64        B
## 15    y_2     43        C
## 16    y_3     98        D
## 17    y_4     78        A
## 18    y_5     53        B
## 19    y_6    100        C
## 20    y_7     79        D
## 21    y_8     84        A
## 22    y_9     68        B
## 23   y_10     99        C
## 24   y_11     65        D
## 25   y_12     55        A
## 26   y_13     98        B
## 27    z_1     56        C
## 28    z_2     83        D
## 29    z_3     81        A
## 30    z_4     69        B
## 31    z_5     50        C
## 32    z_6     72        D
## 33    z_7     54        A
## 34    z_8     56        B
## 35    z_9     87        C
## 36   z_10     84        D
## 37   z_11     80        A
## 38   z_12     68        B
## 39   z_13     95        C
## 40   z_14     93        D
• Read the file “Child_Variants.csv” into a new data structure.
setwd("O:/Training/Introduction to R/R_intro_data_files")
head(child.variants)
##   CHR    POS      dbSNP REF ALT QUAL FILTER   GENE                  HGVS
## 1   1  69270          .   A   G   16   PASS  OR4F5         c.180A>G(p.=)
## 2   1  69511 rs75062661   A   G  200   PASS  OR4F5  c.421A>G_p.Thr141Ala
## 3   1  69761          .   A   T  200   PASS  OR4F5  c.671A>T_p.Asp224Val
## 4   1  69897 rs75758884   T   C   59   PASS  OR4F5         c.807T>C(p.=)
## 5   1 877831  rs6672356   T   C  200   PASS SAMD11 c.1027T>C_p.Trp343Arg
## 6   1 881627  rs2272757   G   A  200   PASS  NOC2L        c.1843C>T(p.=)
## 1   1/1 ENST00000335137           3        4                75    SC   0
## 2   1/1 ENST00000335137          24       27                88   NSC   0
## 3   1/1 ENST00000335137           8        8               100   NSC   0
## 4   1/1 ENST00000335137           3        3               100    SC   0
## 5 10/14 ENST00000342066          10       11                90   NSC   0
## 6 16/19 ENST00000327044          52       56                92    SC   0
##   SAMPLE  FAMILY
## 1 D88849 COG0215
## 2 D88849 COG0215
## 3 D88849 COG0215
## 4 D88849 COG0215
## 5 D88849 COG0215
## 6 D88849 COG0215
• Display row 11

This is a simple selection. Becuase it’s a row we’re selecting there is no shortcut so we need to specify both rows and columns (even though the column selection is blank)

child.variants[11,]
##    CHR    POS      dbSNP REF ALT QUAL FILTER  GENE       HGVS EXON
## 11   1 889159 rs13302945   A   C  200   PASS NOC2L c.888+3T>G    .
## 11 ENST00000327044          26       29                89    SS   0 D88849
##     FAMILY
## 11 COG0215
• Calculate the mean of the column named MutantReadPercent.

Think about this in two steps. First we need to get at the data in that column. We can do that using $as we know the name of the column. Then we can pass that into the mean function. mean(child.variants$MutantReadPercent)
## [1] 59.88219

## Exercise 5

• Find out how many rows in small_file have a length which is < 65.

For all filtering think of the problem in a structured way.

1. Extract the vector of values you want to filter against (in this case small_file$Length) 2. Apply the logical test (in this case < 65) 3. Either use the logical vector produced to filter the data using a selction, or use sum() to get the count of the hits. small.file$Length
##  [1]  45  82  81  56  96  85  65  96  60  62  80  63  50  64  43  98  78
## [18]  53 100  79  84  68  99  65  55  98  56  83  81  69  50  72  54  56
## [35]  87  84  80  68  95  93
small.file$Length < 65 ## [1] TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE ## [12] TRUE TRUE TRUE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE ## [23] FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE TRUE FALSE TRUE ## [34] TRUE FALSE FALSE FALSE FALSE FALSE FALSE sum(small.file$Length < 65)
## [1] 14
• Create a filtered version of the child.variants data which includes only rows where MutantReadPercent >= 70.

This is the same 3 step problem.

1. Extract the MutantReadPercent column using the $notation 2. Perform the logical test on this vector (>=70) 3. Use this logical vector to define which rows to keep in a standard 2 dimension selection on the original data frame. To keep the output from the first two commands a sensible length I’m going to put them inside a call to the head() function. I’m increasing the number of values shown from the default (which is only 6) so you get a better feeling for what the data looks like. head(child.variants$MutantReadPercent, n=100)
##   [1]  75  88 100 100  90  92  97  95  80  89  89  81  33  90 100  90 100
##  [18] 100 100  89  82 100  90 100 100  92  93  90  85  93  94  57  31  90
##  [35]  34  51  39  44  42  56  90  26  28  93  93  95  89  77 100  54  37
##  [52]  50  38  30  42  76  47  42  27  50  45  22  35  36  38  45  34  47
##  [69]  54  59  28  91  22  66  57 100  35  34  46 100  26  60 100  44  33
##  [86]  82  25  21  83 100  85  36  84  75  52  94  88  78  83  86
head(child.variants$MutantReadPercent >= 70, n=100) ## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE ## [12] TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE ## [23] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE ## [34] TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE ## [45] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE ## [56] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE ## [67] FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE ## [78] FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE ## [89] TRUE TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE TRUE ## [100] TRUE child.variants[child.variants$MutantReadPercent >= 70,] -> child.variants.filtered

nrow(child.variants)
## [1] 25822
nrow(child.variants.filtered)
## [1] 9976
• From the filtered data frame we want to know the frequency with which G, A, T and C bases were mutated.

This filtration is going to use the REF column in the child.variants.filtered dataset. We’re going to need to do an equality (==) test to compare this to G, A, T and C. In this instance we only care about how many of the values are true so we can use a sum() on the logical vector to get that value.

head(child.variants.filtered$REF, n=100) ## [1] A A A T T G A T T G A G G A C G T T A A C T A T G A G T T C A A C C G ## [36] T T G T C A C T C T A T G T T A C T G T C T T C A C T T T G A A A C C ## [71] C C G A G C A A T G T C A C T T T G C G G C G C C G A T A G ## 268 Levels: A AAAAAC AAAAT AAAATAAATAAATAAATAAATAAAT AAAG ... TTTTTTTGTC head(child.variants.filtered$REF == "G", n=100)
##   [1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
##  [12]  TRUE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
##  [23] FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
##  [34] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
##  [45] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
##  [56] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
##  [67] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE
##  [78] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
##  [89] FALSE  TRUE  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE
## [100]  TRUE
sum(child.variants.filtered$REF == "G") ## [1] 2347 We can now repeat this with A, T and C. We can also store the values in a vector by putting the code inside the c() function. We’ll also name the slots in the vector with the letter they represent. c( sum(child.variants.filtered$REF == "G"),
sum(child.variants.filtered$REF == "A"), sum(child.variants.filtered$REF == "T"),
sum(child.variants.filtered$REF == "C") ) -> mutation.counts names(mutation.counts) <- c('G','A','T','C') mutation.counts ## G A T C ## 2347 2584 2616 2288 In the advanced course we will show you how you could have achieved this exercise in a single operation rather than using multiple filters by using the tapply function. ## Exercise 6 • In the original child variants dataset draw a histogram of the MutantReadPercent column, try increasing the number of categories (breaks) to 50. For this we pass the vector of MutantReadPercent values to the hist() function, which draws histograms. hist(child.variants$MutantReadPercent,breaks=50)

• Plot a boxplot of the MutantReadPercent values from both the original child variants and the same column from the filtered dataset you made in Exercise 5 (MutantReadPercent>=70). Check that the distributions look different.

The boxplot function can take multiple vectors as input so we can simply pass the two vectors separtately. If we do this however the datasets will not be named (since the function doesn’t know what they are called). To fix this we would have to either explicitly set the names using the ‘names=’ parameter to the function. Alternatively we could put the two vectors into a list which would allow us to set the slot names for the list, and these will be picked up by boxplot automatically. Here we’ll do it both ways so you can see the options for how to do this.

boxplot(child.variants$MutantReadPercent, child.variants.filtered$MutantReadPercent, names=c("Original","Filtered"))

boxplot(
list(
Original=child.variants$MutantReadPercent, Filtered=child.variants.filtered$MutantReadPercent
)
)

• Plot the results of the vector created in Exercise 5 (‘mutation.counts’) as a barplot. Use the names.arg function to show which mutation is which and use the rainbow() function to give the bars different colours

In our case, because we put slot names onto our mutation.counts vector we don’t need to use names.arg as barplot will use the slot names by default. We’ll change the names later to show how you would do this anyway.

The rainbow() function needs to know how many colours to generate. We could just hard-code this since we know there are 4 values, but it’s generally nicer to calculate the value we need from the data. That way if we later want to change the number of mutatations we counted the code will still work.

barplot(mutation.counts, col=rainbow(length(mutation.counts)))

If we did want to explicitly set the names then we could do that.

barplot(
mutation.counts,
col=rainbow(length(mutation.counts)),
)

## Exercise 7

• Read in the file’neutrophils.csv’. This is a comma-delimited file so use read.csv().
setwd("O:/Training/Introduction to R/R_intro_data_files")

head(neutrophils)
##        DMSO   TGX.221    PI103     Akt1
## 1 144.43930  99.61073 41.95241 111.8013
## 2 135.71670 115.35760 57.46430 124.1805
## 3  57.88828 106.44840 41.01954 126.7738
## 4  66.71269 115.89830 63.12587 130.9577
## 5  73.36981  75.96729       NA  88.6273
## 6  83.43180        NA       NA 147.8813
• Create a boxplot of the 4 samples and put a suitable title on the plot.

Since our data frame contains only the data we want to plot, and boxplot can take a list (which a data frame is) as input, we ca just pass the whole thing to the boxplot function.

boxplot(neutrophils, main="Range of values for different samples")

• Use the colMeans() function to calculate the mean of each dataset. Plot the means as a barplot

If we try this on the data as it stands then we won’t get the answer we want, since there are missing (NA) values in our dataset.

colMeans(neutrophils)
##     DMSO  TGX.221    PI103     Akt1
## 100.8013       NA       NA       NA

To get colMeans to ignore the NA values when calculating the mean we can pass the na.rm=TRUE option.

colMeans(neutrophils, na.rm = TRUE) -> mean.values

mean.values
##      DMSO   TGX.221     PI103      Akt1
## 100.80126 102.65646  50.89053 103.91649

Finally we can plot these.

barplot(mean.values)

• Read in the ‘brain_bodyweight.txt’ file. The first column contains species names, not data, so use row.names=1 to set these up correctly for your data frame.

This is a tab-delimited text file, so we’re using read.delim to read this in. In addition to the row.names parameter I’m also going to set check.names=FALSE so R doesn’t modify the column names (to remove spaces).

setwd("O:/Training/Introduction to R/R_intro_data_files")
read.delim("brain_bodyweight.txt", row.names=1, check.names = FALSE) -> brain.bodyweight

head(brain.bodyweight)
##                 Body weight (kg) Brain weight (g)
## Cow                       465.00            423.0
## Grey Wolf                  36.33            119.5
## Goat                       27.66            115.0
## Guinea Pig                  1.04              5.5
## Diplodocus              11700.00             50.0
## Asian Elephant           2547.00           4603.0

You can see that the species names have been correctly set as row names and that the column names are in tact.

• Log transform the data (base2)

Since all of the data frame is data we can simply pass the whole structure to the log2 function. Since we’re not going to use the untransformed data again we’ll overwrite the original data frame.

log2(brain.bodyweight) -> brain.bodyweight

head(brain.bodyweight)
##                 Body weight (kg) Brain weight (g)
## Cow                   8.86108691         8.724514
## Grey Wolf             5.18308946         6.900867
## Goat                  4.78972925         6.845490
## Guinea Pig            0.05658353         2.459432
## Diplodocus           13.51422091         5.643856
## Asian Elephant       11.31458324        12.168359
• Create a scatterplot with default parameters with the log transformed data.

We create a scatterplot with the plot() function. We need to pass the two vectors as the x and y values. Since they are in the correct order in our data frame we can, in this case, just pass the whole dataframe. This also has the advantage of setting the correct labels for the axes as they will be taken from the column names.

plot(brain.bodyweight)

• Create the same scatterplot but experiment with some parameters.
plot(
brain.bodyweight,
pch=19,
col="red",
cex=1.5,
main="Brainweight vs Bodyweight",
xlab="Bodyweight (log2 kg)",
ylab="Brainweight (log2 kg)"
)

• Read in the file chr_data.txt
setwd("O:/Training/Introduction to R/R_intro_data_files")

head(chr.data)
##   chr position GM06990_ABL1 GM06990_MLLT3
## 1   8        1  -0.04661052    -0.1816292
## 2   8   100001   0.25605089     0.4625507
## 3   8   200001   0.25605089    -0.1816292
## 4   8   300001   0.86137348    -0.5037192
## 5   8   400001   0.86137348    -0.5037192
## 6   8   500001   0.86137348    -0.5037192
• Remove the first column

This will involve a selection for the columns we want to keep, and then overwriting the original data with the selected subset. We could simply do a selection for columns 2,3 and 4.

head(chr.data[,2:4])
##   position GM06990_ABL1 GM06990_MLLT3
## 1        1  -0.04661052    -0.1816292
## 2   100001   0.25605089     0.4625507
## 3   200001   0.25605089    -0.1816292
## 4   300001   0.86137348    -0.5037192
## 5   400001   0.86137348    -0.5037192
## 6   500001   0.86137348    -0.5037192

We also also use a little trick, which is that if you use negative values for the index positions, you can say which positions you don’t want, instead of which ones you do want.

chr.data[,-1] -> chr.data
head(chr.data)
##   position GM06990_ABL1 GM06990_MLLT3
## 1        1  -0.04661052    -0.1816292
## 2   100001   0.25605089     0.4625507
## 3   200001   0.25605089    -0.1816292
## 4   300001   0.86137348    -0.5037192
## 5   400001   0.86137348    -0.5037192
## 6   500001   0.86137348    -0.5037192
• Draw a line graph of the position against the ABL1 dataset

For this we can use the plot() function with type=“l” (thats a the letter l rather than the number 1).

plot(
chr.data$position, chr.data$GM06990_ABL1,
type="l",
col="blue",
xlab="Chromosome Position (bp)",
ylab="z-score",
main="Z scores vs Genomic Position",
lwd=2
)

legend(
"topright",
"ABL1",
fill="blue"
)


text:
# Illogical failures of symbolic integration over Boole

Is there a way to work around integration over Boole being mysteriously flaky like examples show below? Is there a meaningful explanation for this behaviour?

First, rather obvious integral stays unevaluated:

Integrate[Boole[u^2 + v^2 < 1], {u,-1,1}, {v,-1,x}, Assumptions -> -1 < x < 1]

(* Integrate[Boole[u^2 + v^2 < 1], {u,-1,1}, {v,-1,x}, Assumptions -> -1 < x < 1] *)

While the following succeeds to produce a meaningful result:

Integrate[Boole[u^2 + v^2 < 1], {u,-1,1}, {v,-1,x}, Assumptions -> -1 < x < 0]

(* Pi + x Sqrt[1 - x^2] - ArcCos[x] *)

Why this succeeds particularly puzzles me, when the first one fails:

Integrate[Boole[u^2 + v^2 < 1], {u,-1,1}, {v,-1,x},
Assumptions -> -1 < x < Infinity] // FullSimplify

(* Pi + x Sqrt[1 - x^2] - ArcCos[x]             x <= 0
Pi                                           x >= 1
x Sqrt[1 - x^2] + ArcCos[x] + 2 ArcSin[x]    True *)

-
Whenever integration fails over a domain, I always do something like this: FullSimplify@ Integrate[Boole[u^2 + v^2 < 1], {u, -1, 1}, {v, -1, EulerGamma}] /. EulerGamma -> x –  Chip Hurst Sep 17 '13 at 17:11

Integrate[Integrate[Boole[u^2 + v^2 < 1], {u, -1, 1}], {v, -1, x},

It would also appear that swapping order to Integrate[Boole[u^2 + v^2 < 1], {v,-1,x}, {u,-1,1}, Assumptions -> -1 < x < 1] does the trick. Can someone explain why these tricks work? –  kirma Sep 17 '13 at 16:36


text:
mersenneforum.org > News Ruminations about comparisons of "sizes of kits", conveniently rehashed once again (from Lucky13)
 User Name Remember Me? Password
 Register FAQ Search Today's Posts Mark Forums Read

2018-12-09, 19:54   #1
petrw1
1976 Toyota Corona years forever!

"Wayne"
Nov 2006

2·5·439 Posts
Ruminations about comparisons of "sizes of kits", conveniently rehashed once again (from Lucky13)

Quote:
 Originally Posted by Prime95 On Dec 7th, a new Mersenne prime was reported. I emailed the discoverer, obtained the last save file, and reran the last 100,000 iterations. Sure enough, we have a new prime! Aaron has started a full test using prime95, but that doesn't count as an official double-check. We need a volunteer to run CudaLucas and/or mlucas. As usual, the automatic email notification to myself and past Mersenne prime discoverers failed. Yes, the automatic email was debugged and tested after its last failure. Apparently bit rot set in. Fortunately the backup notification plan worked.
I just installed cudaLucas … just because.

I have a RTX-2080Ti. Is that good for cudaLucas or are other cards better?
Unless a good config file is important it was not NOT impressive.

Code:
>CUDALucas-2.03-cuda4.2-sm_30-x86-64.exe -t 86243

Warning: No ini file detected. Using defaults for non-specified options.
Starting M86243 fft length = 4608
Iteration 10000 M( 86243 )C, 0x23992ccd735a03d9, n = 4608, CUDALucas v2.03 err = 0.0131 (0:04 real, 0.4476 ms/iter, ETA 0:31)
Iteration 20000 M( 86243 )C, 0x89c58d63ebee7ad1, n = 4608, CUDALucas v2.03 err = 0.0144 (0:05 real, 0.4472 ms/iter, ETA 0:26)
Iteration 30000 M( 86243 )C, 0x8ad9ad7af5b51d09, n = 4608, CUDALucas v2.03 err = 0.0144 (0:04 real, 0.4472 ms/iter, ETA 0:22)
Iteration 40000 M( 86243 )C, 0xeed70124ff3b4f5a, n = 4608, CUDALucas v2.03 err = 0.0144 (0:05 real, 0.4482 ms/iter, ETA 0:17)
Iteration 50000 M( 86243 )C, 0x6ef44d2b23c538e1, n = 4608, CUDALucas v2.03 err = 0.0144 (0:04 real, 0.4410 ms/iter, ETA 0:13)
Iteration 60000 M( 86243 )C, 0x76f20516c9858691, n = 4608, CUDALucas v2.03 err = 0.0149 (0:04 real, 0.4298 ms/iter, ETA 0:08)
Iteration 70000 M( 86243 )C, 0x1c98576ef37a22df, n = 4608, CUDALucas v2.03 err = 0.0149 (0:05 real, 0.4433 ms/iter, ETA 0:04)
Iteration 80000 M( 86243 )C, 0x6809f7b9c9f1e33d, n = 4608, CUDALucas v2.03 err = 0.0149 (0:04 real, 0.4352 ms/iter, ETA 0:00)
M( 86243 )P, n = 4608, CUDALucas v2.03
Took 31 seconds...my CPU well under 1 second.

I'm willing to try is this COULD BE a good card for this.

2018-12-11, 00:02   #2
petrw1
1976 Toyota Corona years forever!

"Wayne"
Nov 2006

2·5·439 Posts

Quote:
 Originally Posted by kriesel If it still matters, you have my standing offer from some time ago. Current fastest hardware is GTX1080Ti ready with CUDALucas v2.06 May 5 2017 beta, capable of knocking out a ~82M exponent in about 3 days, backed up by a GTX1080, and a 16-core e5-2670 system with prime95 V29.4b8. The GTX1080Ti at 84+GhzD/day for 85M is ~10% faster than a 2080 Ti for LL per https://www.mersenne.ca/cudalucas.php (14th fastest model in the list, and that includes combined throughputs of some duals and a quad; 10th fastest single). And no, that 82M or 85M is not a clue to the nature of Mp51; it's just what I checked the 1080Ti's run time on recently. It would take me some time to put up mlucas on the system.
Any idea why the 2080Ti would be 3 times faster than the 1080Ti at TF but slower at LL/DC?

2018-12-11, 00:16   #3
chalsall
If I May

"Chris Halsall"
Sep 2002

100100011000102 Posts

Quote:
 Originally Posted by petrw1 Any idea why the 2080Ti would be 3 times faster than the 1080Ti at TF but slower at LL/DC?
You're joking. Correct?

2018-12-11, 00:36   #4
petrw1
1976 Toyota Corona years forever!

"Wayne"
Nov 2006

10001001001102 Posts

Quote:
 Originally Posted by chalsall You're joking. Correct?
No, really.

2018-12-11, 00:51   #5
kriesel

"TF79LL86GIMPS96gpu17"
Mar 2017
US midwest

22·3·7·53 Posts

Quote:
 Originally Posted by petrw1 Any idea why the 2080Ti would be 3 times faster than the 1080Ti at TF but slower at LL/DC?
Basic design differences, described somewhere in the RTX2080 thread https://www.mersenneforum.org/showthread.php?t=23592 far better than I could manage from memory

2018-12-11, 01:44   #6

"Kieren"
Jul 2011
In My Own Galaxy!

23·32·139 Posts

Quote:
 Originally Posted by petrw1 Any idea why the 2080Ti would be 3 times faster than the 1080Ti at TF but slower at LL/DC?
Look at the ratios of DP floating point performance. I would guess that the 2080Ti has stunning integer performance, but much more throttled DP than the 1080Ti.

2018-12-11, 02:54   #7
Serpentine Vermin Jar

Jul 2014

CCA16 Posts

Quote:
 Originally Posted by kladner Look at the ratios of DP floating point performance. I would guess that the 2080Ti has stunning integer performance, but much more throttled DP than the 1080Ti.
All I know is, if you want top-notch LL speed, that Tesla V100 is amazing. When ATH completed the verification run in an amazingly short time, my lust for a V100 was pretty high. I think (correct me if I'm mistaken) he used one on an Amazon EC2 instance, so that's definitely more reasonable for short term projects like testing a single exponent...

On my i7-7700K running Prime95 I think the estimate (running a single worker on all 4 cores) was about 6.5 days although I'm probably off by a couple hours one way or another... I don't remember the estimate it showed when it started. I still have over 3 days to go, and although it's been verified once already, I figure I'll finish it off, just to say I did.

2018-12-11, 04:04   #8
kriesel

"TF79LL86GIMPS96gpu17"
Mar 2017
US midwest

22×3×7×53 Posts

Quote:
 Originally Posted by Madpoo On my i7-7700K running Prime95 I think the estimate (running a single worker on all 4 cores) was about 6.5 days although I'm probably off by a couple hours one way or another... I don't remember the estimate it showed when it started. I still have over 3 days to go, and although it's been verified once already, I figure I'll finish it off, just to say I did.
For comparison, CUDALucas 2.06 LL on GTX1080Ti is 3 days at 82m exponent; gpuowl V5 PRP on an RX480 is an estimated 5.6+ days on 85m exponent.

Last fiddled with by kriesel on 2018-12-11 at 04:05

2018-12-11, 05:45   #9
ATH
Einyen

Dec 2003
Denmark

22·3·5·72 Posts

Quote:
 Originally Posted by Madpoo All I know is, if you want top-notch LL speed, that Tesla V100 is amazing. When ATH completed the verification run in an amazingly short time, my lust for a V100 was pretty high. I think (correct me if I'm mistaken) he used one on an Amazon EC2 instance, so that's definitely more reasonable for short term projects like testing a single exponent...
Yes, the Tesla V100 is the fastest benchmarks we have seen for single exponents and yes it was running on EC2. Remember this is a $10K card and not for mere mortals, and the throughput per dollar sucks compared to "George's dream build" I do not think we have seen benchmarks from the latest generation(s) of crazy Xeon Platinum processors with 6-channel RAM. They probably beat a single V100 in total throughput on all cores, but not sure if they beat it on a single exponent. But those are way more expensive than$10K, those are in the "World Domination" territory.

Not far behind the Tesla V100 is the most expensive "consumer" card the $3K Titan V with 6900 GFLOPS FP64 performance vs Tesla V100 7450 GFLOPS. I'm do not think we have seen a Titan V benchmark here on the forum. Regarding trial factoring the Tesla V100 is doing 4200-5000 Ghz-d/day depending on exponent size and bit depth, it has ~ 14,000 GFLOPS FP32 performance vs Titan V 13,800 GFLOPS vs 2080Ti 11,750 GFLOPS. Trial factoring just got its own "Titan V" card with the$2.5K "Titan RTX". It has 16,300 GFLOPS FP32 so it should beat even the Tesla V100 in trial factoring (but NOT in LL speed, only 510 GFLOPS FP64).

Last fiddled with by ATH on 2018-12-11 at 05:57

2018-12-11, 06:12   #10
ATH
Einyen

Dec 2003
Denmark

22·3·5·72 Posts

Quote:
 Originally Posted by petrw1 Any idea why the 2080Ti would be 3 times faster than the 1080Ti at TF but slower at LL/DC?
According to these benchmarks the 2080Ti is faster:
https://mersenneforum.org/showpost.p...postcount=2690
https://mersenneforum.org/showpost.p...postcount=2572

For example at 4608K: 2.6288 ms/iter for 2080Ti vs 3.1588 ms/iter for 1080Ti Founders edition.

What surprises me (and saddens me a bit) is that they are both faster than my 8 core Haswell-E and faster than my old Titan Black even though they are so limited in DP performance.

I do not really understand it, the specs say they are supposed to be ~440 GFLOPS and ~350 GFLOPS of DP performance, and my old Titan Black is supposed to be ~1700 GFLOPS:
https://www.anandtech.com/show/13668...500-top-turing
https://en.wikipedia.org/wiki/GeForce_10_series
https://en.wikipedia.org/wiki/GeForce_700_series

Last fiddled with by ATH on 2018-12-11 at 06:22

2018-12-11, 07:30   #11
axn

Jun 2003

469810 Posts

Quote:
 Originally Posted by ATH I do not really understand it, the specs say they are supposed to be ~440 GFLOPS and ~350 GFLOPS of DP performance, and my old Titan Black is supposed to be ~1700 GFLOPS: https://www.anandtech.com/show/13668...500-top-turing https://en.wikipedia.org/wiki/GeForce_10_series https://en.wikipedia.org/wiki/GeForce_700_series
Memory bandwidth limited. 2080 Ti 616 GB/s, 1080 Ti 484 GB/s, Titan black 336 GB/s

 Similar Threads Thread Thread Starter Forum Replies Last Post MooMoo2 Other Chess Games 5 2016-10-22 01:55 wildrabbitt Miscellaneous Math 11 2015-03-06 08:17 nitai1999 Software 7 2004-08-26 18:12

All times are UTC. The time now is 05:31.

Tue Sep 29 05:31:34 UTC 2020 up 19 days, 2:42, 0 users, load averages: 1.37, 1.46, 1.45


text:
5

# EtMgBr; etherMe Me22. HzOMe Me MeHO Me MeMeHO Me Me MeMeHOMeMe...

## Question

###### EtMgBr; etherMe Me22. HzOMe Me MeHO Me MeMeHO Me Me MeMeHOMeMe

EtMgBr; ether Me Me 2 2. HzO Me Me Me HO Me Me Me HO Me Me Me Me HO Me Me

#### Similar Solved Questions

##### How nany milliqtansIduri rernainNeed Holp?Submu Aswer Save PropussSMoCactUlicobloni UUgedrradloHcve substarce docay" ((t) @,JCHmcWd * roMalntiq aftet"etungicxhere u(c) Musuedkilogtams FIrnd the Mnss 17ta(6) How muchWeeftauAaeidavs 'Kouno Yli antwcrdeclnaNeed Help?AlredaldValchbpointy GPrCalci025 Mu 0/100 Submis:ions UsedType hcre Cala
How nany milliqtans Iduri rernain Need Holp? Submu Aswer Save Propuss SMoCact Ulico bloni UUged rradloHcve substarce docay" ((t) @,JC Hmc Wd * roMalntiq aftet "et ungic xhere u(c) Musued kilogtams FIrnd the Mnss 17ta (6) How much WeeftauAaei davs 'Kouno Yli antwcr declna Need Help? Al...
##### For the x +y _ 2' =18, P(3,5,-4} please find the equations of the Tangent plane;Normal line _
For the x +y _ 2' =18, P(3,5,-4} please find the equations of the Tangent plane; Normal line _...
##### Foresters are interested in determining the mean timber volume per acre for 520 one-acre plots (N 520). A [-in-25 systematic sample is conducted. Using the data presented in the accompanying table, estimate / the average timber volume per plot; and place bound on the error of estimationPlot sampledVolumePlot sampledVolume(in board feet)(in board feet)7030 6720 6850 7210 7150 7370 70 6930 6570 6910 7380279 304 329 354 379 404 429 454 479 5047540 6720 6900 7200 7100 6860 6800 7050 7420 70902979 10
Foresters are interested in determining the mean timber volume per acre for 520 one-acre plots (N 520). A [-in-25 systematic sample is conducted. Using the data presented in the accompanying table, estimate / the average timber volume per plot; and place bound on the error of estimation Plot sampled...
##### For the second-order equation 5y" (2 + Zi)y' 2y = 0,= > show that 9(v) F2[ solution; find linearly indepeudeut solution yz(r) usiug the method of reduction of order.
For the second-order equation 5y" (2 + Zi)y' 2y = 0,= > show that 9(v) F2[ solution; find linearly indepeudeut solution yz(r) usiug the method of reduction of order....
##### Jelp?Read ItWatchItMaster ItJalkto a TutorPrevious Answers LarsonETS 3.6.015er the followingFunctionPoint f(x) = arcsin 4x 4:) (a) Find an equation of the tangent line to the graph of f at the given po'graphing utility to graph the function and its tangent line at the (b) Use 3eeseud ?
Jelp? Read It WatchIt Master It Jalkto a Tutor Previous Answers LarsonETS 3.6.015 er the following Function Point f(x) = arcsin 4x 4:) (a) Find an equation of the tangent line to the graph of f at the given po' graphing utility to graph the function and its tangent line at the (b) Use 3 eeseud ...
##### Transform the vector as described. (4, 5) Reflect acrossy =x
Transform the vector as described. (4, 5) Reflect acrossy =x...
##### Write the given system of equations as & matrix equation and solve by using inverses 2x1 + X2 = k1 XtH X2 k2b-What are X1 and X2 when k14 and kz =72What are X, and *2 when k1 = 8 and kz = 102
Write the given system of equations as & matrix equation and solve by using inverses 2x1 + X2 = k1 XtH X2 k2 b-What are X1 and X2 when k1 4 and kz =72 What are X, and *2 when k1 = 8 and kz = 102...
##### Tha rndam varinble X follows Polaton procoas with tha givon maen. Aseuming (a) P(8} (D} P(X<6} (c) P(z6) (d) P(asxs5)compula tha folowing(0) P(6) = 0.1221 (Do not round unti the final answer Then round faur decimal Places as neuded )(b) P(X<6) = 0.1912 (Do not round unti tho final answer: Then round four decimal plocos neaded }(c) P(X26) ~ 0.8088 (Do not round until the final answer: Then round Ia (our docimal places nooded )(d) P(3sXs5) = (Do not round until Ihe final answer: Then round t
Tha rndam varinble X follows Polaton procoas with tha givon maen. Aseuming (a) P(8} (D} P(X<6} (c) P(z6) (d) P(asxs5) compula tha folowing (0) P(6) = 0.1221 (Do not round unti the final answer Then round faur decimal Places as neuded ) (b) P(X<6) = 0.1912 (Do not round unti tho final answer: T...
##### P (atm)Isothermal processBV(liters) 5010
P (atm) Isothermal process B V(liters) 50 10...
##### Tolal Woman | Sex Non-drnker 322 135 Keqular 1 1 Drinker 205 Fooo
Tolal Woman | Sex Non-drnker 322 135 Keqular 1 1 Drinker 205 Fooo...
##### Glven_the following Quantity Dkcount Schadule Dkscount Number Dlscount quantty Dlscount Oto 199 200 to 499 500 to 999 1000 or more 4.57Dhceuntcot (S]Io be completed To be completed Jobe completedthe normal cost per unlt Is 55, the orduring cost per order 582= the unnual dumand Is 4000 units, and the holding cost Is 55% of the cost per unlt; What order quantity will minimize the total Inventory cost? Please show work Please show you calculations mranually.
Glven_the following Quantity Dkcount Schadule Dkscount Number Dlscount quantty Dlscount Oto 199 200 to 499 500 to 999 1000 or more 4.57 Dhceuntcot (S] Io be completed To be completed Jobe completed the normal cost per unlt Is 55, the orduring cost per order 582= the unnual dumand Is 4000 units, and ...
##### Tony has hot dog stand on the campus of a large university. He has noticed the number of hot dogs sold, Y, tends to decrease as the temperature (in CF ), X; goes up. He took a random sample of 16 days from the past academic year and observed his sales for each of those days_ After running simple linear regression analysis on his data; Tony found the following information. y 96.29 0.62xSUMMARY OUTPUTRegression Statistics Multiple R 0.9764 R Square 9534 Adjusted R 0.9501 Square Standard 2.7874 Err
Tony has hot dog stand on the campus of a large university. He has noticed the number of hot dogs sold, Y, tends to decrease as the temperature (in CF ), X; goes up. He took a random sample of 16 days from the past academic year and observed his sales for each of those days_ After running simple lin...
##### An unstable particle called the pion has a mean lifetime of $25 \mathrm{ns}$ in its own rest frame. A beam of pions travels through the laboratory at a speed of $0.60 c .$ (a) What is the mean lifetime of the pions as measured in the laboratory frame? (b) How far does a pion travel (as measured by laboratory observers) during this time?
An unstable particle called the pion has a mean lifetime of $25 \mathrm{ns}$ in its own rest frame. A beam of pions travels through the laboratory at a speed of $0.60 c .$ (a) What is the mean lifetime of the pions as measured in the laboratory frame? (b) How far does a pion travel (as measured by l...
##### In the following categorical propositions identify the quantifier, subject term, copula, and predicate term.No stressful jobs are occupations conducive to a healthy lifestyle
In the following categorical propositions identify the quantifier, subject term, copula, and predicate term. No stressful jobs are occupations conducive to a healthy lifestyle...
##### Balsamic vinegar contains $5 \%$ acetic acid, so a 32 -oz bottle of balsamic vinegar contains ____ ounces of acetic acid.
Balsamic vinegar contains $5 \%$ acetic acid, so a 32 -oz bottle of balsamic vinegar contains ____ ounces of acetic acid....
##### Point launched horizontally away trom wall and a(t) represents Point A*s distance fiOm the wall (in meters) in tems of the number ecconds since the point was launched Point B is also launched from the wall, but travels L, times as fast as Point .Clickhcne Iaunch thc points.Suppose b(t) represents Point B"s distanee from the wall (in meters) terms of the number of seconds Since the points wcre launched. Write function fonula for using the functionb(t)prcucuThe gruph of' functionshown b
Point launched horizontally away trom wall and a(t) represents Point A*s distance fiOm the wall (in meters) in tems of the number ecconds since the point was launched Point B is also launched from the wall, but travels L, times as fast as Point . Clickhcne Iaunch thc points. Suppose b(t) represents ...
##### My favorite shirt has finally reached the “spin” cycle of itstime in the washing machine. The barrel of the washing machine isrotating at a speed of 11.1 m/s and my shirt is measured to be 45cm from the center of the barrel.a. What is the period of my shirt’s rotation in seconds? 2a answer __________________b. What is the frequency of my shirt’s rotation in proper SIunits?2b answer __________________c. The spin cycle lasts for 6 min. How many times will my shirtgo around-and-around?2c answer ___
My favorite shirt has finally reached the “spin” cycle of its time in the washing machine. The barrel of the washing machine is rotating at a speed of 11.1 m/s and my shirt is measured to be 45 cm from the center of the barrel. a. What is the period of my shirt’s rotation in seconds? 2a answe...
##### Dx using n = 6 1+233 (15 pts) In this problem; we want to approximate the integral intervals. Do all calculations to 5 decimal place accuracy:Find the values of yo;96 .Use the Trapezoid Rule to approximate this integral_(c) Use Simpson's Rule to approximate this integral.
dx using n = 6 1+23 3 (15 pts) In this problem; we want to approximate the integral intervals. Do all calculations to 5 decimal place accuracy: Find the values of yo; 96 . Use the Trapezoid Rule to approximate this integral_ (c) Use Simpson's Rule to approximate this integral....
##### Which of the following points lies on the line R = (0,3,1) +t(2,1,1): P(2,4,2) Q6-2,2,1) R(4,5,2) S(6,6,2)
Which of the following points lies on the line R = (0,3,1) +t(2,1,1): P(2,4,2) Q6-2,2,1) R(4,5,2) S(6,6,2)...
##### Find the value of y:638 652_ (Ay I)" 3*2
Find the value of y: 63 8 652_ (Ay I)" 3*2...

-- 0.023469--