metadata
dict | text
stringlengths 0
40.6M
| id
stringlengths 14
255
|
|---|---|---|
{
"filename": "analytic_pulse.py",
"repo_name": "nu-radio/NuRadioMC",
"repo_path": "NuRadioMC_extracted/NuRadioMC-master/NuRadioReco/utilities/analytic_pulse.py",
"type": "Python"
}
|
import numpy as np
import scipy.signal
from NuRadioReco.utilities import fft
from NuRadioReco.utilities import trace_utilities
def amp_from_energy(energy):
"""
energy is defined as the integral of squared voltage normalized to a time window of 128 ns
Parameters
----------
energy:
"""
return 0.5 * np.log10(energy) + 0.12876705
def get_analytic_pulse_freq(amp_p0, amp_p1, phase_p0, n_samples_time, sampling_rate,
phase_p1=0, bandpass=None, quadratic_term=0, quadratic_term_offset=0):
"""
Analytic pulse as described in PhD thesis Glaser and NuRadioReco paper in the frequency domain
Parameters
----------
amp_p0: float
amplitude parameter of analytic pulse
amp_p1:
slope parameter of analytic pulse
phase_p0:
phase parameter of analytic pulse
n_samples_time:
numer of samples in time-domain
sampling_rate:
sampling rate of trace
phase_p1:
default 0
bandpass:
default None
quadratic_term:
default 0
quadratic_term_offset:
default 0
"""
amp_p0 /= trace_utilities.conversion_factor_integrated_signal # input variable is energy in eV/m^2
dt = 1. / sampling_rate
frequencies = np.fft.rfftfreq(n_samples_time, dt)
df = frequencies[1] - frequencies[0]
A = np.sign(amp_p0) * (np.abs(amp_p0)) ** 0.5
amps = A * 10 ** (frequencies * amp_p1 + quadratic_term * (frequencies - quadratic_term_offset)**2)
if(bandpass is None):
norm = -1. / (2 * amp_p1 * np.log(10))
else:
if(amp_p1 == 0):
norm = bandpass[1] - bandpass[0]
else:
norm = (100 ** (amp_p1 * bandpass[1]) - 100 ** (amp_p1 * bandpass[0])) / (2 * amp_p1 * np.log(10))
phases = phase_p0 + frequencies * phase_p1
xx = amps * np.exp(phases * 1j) / norm ** 0.5 / dt ** 0.5 * df ** 0.5
if(bandpass is not None):
b, a = scipy.signal.butter(10, bandpass, 'bandpass', analog=True)
w, h = scipy.signal.freqs(b, a, frequencies)
xx *= h
return xx
def get_analytic_pulse(amp_p0, amp_p1, phase_p0, n_samples_time,
sampling_rate,
phase_p1=0, bandpass=None,
quadratic_term=0, quadratic_term_offset=0):
"""
Analytic pulse as described in PhD thesis Glaser and NuRadioReco paper in the time domain
Parameters
----------
amp_p0: float
amplitude parameter of analytic pulse
amp_p1:
slope parameter of analytic pulse
phase_p0:
phase parameter of analytic pulse
n_samples_time:
numer of samples in time-domain
sampling_rate:
sampling rate of trace
phase_p1:
default 0
bandpass:
default None
quadratic_term:
default 0
quadratic_term_offset:
default 0
"""
xx = get_analytic_pulse_freq(amp_p0, amp_p1, phase_p0, n_samples_time,
sampling_rate, phase_p1=phase_p1,
bandpass=bandpass,
quadratic_term=quadratic_term,
quadratic_term_offset=quadratic_term_offset)
return fft.freq2time(xx, sampling_rate)
|
nu-radioREPO_NAMENuRadioMCPATH_START.@NuRadioMC_extracted@NuRadioMC-master@NuRadioReco@utilities@analytic_pulse.py@.PATH_END.py
|
{
"filename": "_lineposition.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scatter/hoverlabel/font/_lineposition.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class LinepositionValidator(_plotly_utils.basevalidators.FlaglistValidator):
def __init__(
self,
plotly_name="lineposition",
parent_name="scatter.hoverlabel.font",
**kwargs,
):
super(LinepositionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "none"),
extras=kwargs.pop("extras", ["none"]),
flags=kwargs.pop("flags", ["under", "over", "through"]),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scatter@hoverlabel@font@_lineposition.py@.PATH_END.py
|
{
"filename": "core.py",
"repo_name": "davidharvey1986/pyRRG",
"repo_path": "pyRRG_extracted/pyRRG-master/unittests/bugFixPyRRG/lib/python3.7/site-packages/pip/_vendor/certifi/core.py",
"type": "Python"
}
|
# -*- coding: utf-8 -*-
"""
certifi.py
~~~~~~~~~~
This module returns the installation location of cacert.pem or its contents.
"""
import os
try:
from importlib.resources import read_text
except ImportError:
# This fallback will work for Python versions prior to 3.7 that lack the
# importlib.resources module but relies on the existing `where` function
# so won't address issues with environments like PyOxidizer that don't set
# __file__ on modules.
def read_text(_module, _path, encoding="ascii"):
with open(where(), "r", encoding=encoding) as data:
return data.read()
def where():
f = os.path.dirname(__file__)
return os.path.join(f, "cacert.pem")
def contents():
return read_text("certifi", "cacert.pem", encoding="ascii")
|
davidharvey1986REPO_NAMEpyRRGPATH_START.@pyRRG_extracted@pyRRG-master@unittests@bugFixPyRRG@lib@python3.7@site-packages@pip@_vendor@certifi@core.py@.PATH_END.py
|
{
"filename": "main.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/catboost/spark/catboost4j-spark/core/src/test/generate_canonical_results/main.py",
"type": "Python"
}
|
import catboost_classifier_test
import catboost_regressor_test
import feature_importance_test
if __name__ == '__main__':
catboost_classifier_test.main()
catboost_regressor_test.main()
feature_importance_test.main()
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@catboost@spark@catboost4j-spark@core@src@test@generate_canonical_results@main.py@.PATH_END.py
|
{
"filename": "routing.ipynb",
"repo_name": "langchain-ai/langchain",
"repo_path": "langchain_extracted/langchain-master/docs/docs/how_to/routing.ipynb",
"type": "Jupyter Notebook"
}
|
---
sidebar_position: 3
keywords: [RunnableBranch, LCEL]
---
# How to route between sub-chains
:::info Prerequisites
This guide assumes familiarity with the following concepts:
- [LangChain Expression Language (LCEL)](/docs/concepts/lcel)
- [Chaining runnables](/docs/how_to/sequence/)
- [Configuring chain parameters at runtime](/docs/how_to/configure)
- [Prompt templates](/docs/concepts/prompt_templates)
- [Chat Messages](/docs/concepts/messages)
:::
Routing allows you to create non-deterministic chains where the output of a previous step defines the next step. Routing can help provide structure and consistency around interactions with models by allowing you to define states and use information related to those states as context to model calls.
There are two ways to perform routing:
1. Conditionally return runnables from a [`RunnableLambda`](/docs/how_to/functions) (recommended)
2. Using a `RunnableBranch` (legacy)
We'll illustrate both methods using a two step sequence where the first step classifies an input question as being about `LangChain`, `Anthropic`, or `Other`, then routes to a corresponding prompt chain.
## Example Setup
First, let's create a chain that will identify incoming questions as being about `LangChain`, `Anthropic`, or `Other`:
```python
from langchain_anthropic import ChatAnthropic
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
chain = (
PromptTemplate.from_template(
"""Given the user question below, classify it as either being about `LangChain`, `Anthropic`, or `Other`.
Do not respond with more than one word.
<question>
{question}
</question>
Classification:"""
)
| ChatAnthropic(model_name="claude-3-haiku-20240307")
| StrOutputParser()
)
chain.invoke({"question": "how do I call Anthropic?"})
```
'Anthropic'
Now, let's create three sub chains:
```python
langchain_chain = PromptTemplate.from_template(
"""You are an expert in langchain. \
Always answer questions starting with "As Harrison Chase told me". \
Respond to the following question:
Question: {question}
Answer:"""
) | ChatAnthropic(model_name="claude-3-haiku-20240307")
anthropic_chain = PromptTemplate.from_template(
"""You are an expert in anthropic. \
Always answer questions starting with "As Dario Amodei told me". \
Respond to the following question:
Question: {question}
Answer:"""
) | ChatAnthropic(model_name="claude-3-haiku-20240307")
general_chain = PromptTemplate.from_template(
"""Respond to the following question:
Question: {question}
Answer:"""
) | ChatAnthropic(model_name="claude-3-haiku-20240307")
```
## Using a custom function (Recommended)
You can also use a custom function to route between different outputs. Here's an example:
```python
def route(info):
if "anthropic" in info["topic"].lower():
return anthropic_chain
elif "langchain" in info["topic"].lower():
return langchain_chain
else:
return general_chain
```
```python
from langchain_core.runnables import RunnableLambda
full_chain = {"topic": chain, "question": lambda x: x["question"]} | RunnableLambda(
route
)
```
```python
full_chain.invoke({"question": "how do I use Anthropic?"})
```
AIMessage(content="As Dario Amodei told me, to use Anthropic, you can start by exploring the company's website and learning about their mission, values, and the different services and products they offer. Anthropic is focused on developing safe and ethical AI systems, so they have a strong emphasis on transparency and responsible AI development. \n\nDepending on your specific needs, you can look into Anthropic's AI research and development services, which cover areas like natural language processing, computer vision, and reinforcement learning. They also offer consulting and advisory services to help organizations navigate the challenges and opportunities of AI integration.\n\nAdditionally, Anthropic has released some open-source AI models and tools that you can explore and experiment with. These can be a great way to get hands-on experience with Anthropic's approach to AI development.\n\nOverall, Anthropic aims to be a reliable and trustworthy partner in the AI space, so I'd encourage you to reach out to them directly to discuss how they can best support your specific requirements.", response_metadata={'id': 'msg_01CtLFgFSwvTaJomrihE87Ra', 'content': [ContentBlock(text="As Dario Amodei told me, to use Anthropic, you can start by exploring the company's website and learning about their mission, values, and the different services and products they offer. Anthropic is focused on developing safe and ethical AI systems, so they have a strong emphasis on transparency and responsible AI development. \n\nDepending on your specific needs, you can look into Anthropic's AI research and development services, which cover areas like natural language processing, computer vision, and reinforcement learning. They also offer consulting and advisory services to help organizations navigate the challenges and opportunities of AI integration.\n\nAdditionally, Anthropic has released some open-source AI models and tools that you can explore and experiment with. These can be a great way to get hands-on experience with Anthropic's approach to AI development.\n\nOverall, Anthropic aims to be a reliable and trustworthy partner in the AI space, so I'd encourage you to reach out to them directly to discuss how they can best support your specific requirements.", type='text')], 'model': 'claude-3-haiku-20240307', 'role': 'assistant', 'stop_reason': 'end_turn', 'stop_sequence': None, 'type': 'message', 'usage': Usage(input_tokens=53, output_tokens=219)})
```python
full_chain.invoke({"question": "how do I use LangChain?"})
```
AIMessage(content="As Harrison Chase told me, using LangChain involves a few key steps:\n\n1. **Set up your environment**: Install the necessary Python packages, including the LangChain library itself, as well as any other dependencies your application might require, such as language models or other integrations.\n\n2. **Understand the core concepts**: LangChain revolves around a few core concepts, like Agents, Chains, and Tools. Familiarize yourself with these concepts and how they work together to build powerful language-based applications.\n\n3. **Identify your use case**: Determine what kind of task or application you want to build using LangChain, such as a chatbot, a question-answering system, or a document summarization tool.\n\n4. **Choose the appropriate components**: Based on your use case, select the right LangChain components, such as agents, chains, and tools, to build your application.\n\n5. **Integrate with language models**: LangChain is designed to work seamlessly with various language models, such as OpenAI's GPT-3 or Anthropic's models. Connect your chosen language model to your LangChain application.\n\n6. **Implement your application logic**: Use LangChain's building blocks to implement the specific functionality of your application, such as prompting the language model, processing the response, and integrating with other services or data sources.\n\n7. **Test and iterate**: Thoroughly test your application, gather feedback, and iterate on your design and implementation to improve its performance and user experience.\n\nAs Harrison Chase emphasized, LangChain provides a flexible and powerful framework for building language-based applications, making it easier to leverage the capabilities of modern language models. By following these steps, you can get started with LangChain and create innovative solutions tailored to your specific needs.", response_metadata={'id': 'msg_01H3UXAAHG4TwxJLpxwuuVU7', 'content': [ContentBlock(text="As Harrison Chase told me, using LangChain involves a few key steps:\n\n1. **Set up your environment**: Install the necessary Python packages, including the LangChain library itself, as well as any other dependencies your application might require, such as language models or other integrations.\n\n2. **Understand the core concepts**: LangChain revolves around a few core concepts, like Agents, Chains, and Tools. Familiarize yourself with these concepts and how they work together to build powerful language-based applications.\n\n3. **Identify your use case**: Determine what kind of task or application you want to build using LangChain, such as a chatbot, a question-answering system, or a document summarization tool.\n\n4. **Choose the appropriate components**: Based on your use case, select the right LangChain components, such as agents, chains, and tools, to build your application.\n\n5. **Integrate with language models**: LangChain is designed to work seamlessly with various language models, such as OpenAI's GPT-3 or Anthropic's models. Connect your chosen language model to your LangChain application.\n\n6. **Implement your application logic**: Use LangChain's building blocks to implement the specific functionality of your application, such as prompting the language model, processing the response, and integrating with other services or data sources.\n\n7. **Test and iterate**: Thoroughly test your application, gather feedback, and iterate on your design and implementation to improve its performance and user experience.\n\nAs Harrison Chase emphasized, LangChain provides a flexible and powerful framework for building language-based applications, making it easier to leverage the capabilities of modern language models. By following these steps, you can get started with LangChain and create innovative solutions tailored to your specific needs.", type='text')], 'model': 'claude-3-haiku-20240307', 'role': 'assistant', 'stop_reason': 'end_turn', 'stop_sequence': None, 'type': 'message', 'usage': Usage(input_tokens=50, output_tokens=400)})
```python
full_chain.invoke({"question": "whats 2 + 2"})
```
AIMessage(content='4', response_metadata={'id': 'msg_01UAKP81jTZu9fyiyFYhsbHc', 'content': [ContentBlock(text='4', type='text')], 'model': 'claude-3-haiku-20240307', 'role': 'assistant', 'stop_reason': 'end_turn', 'stop_sequence': None, 'type': 'message', 'usage': Usage(input_tokens=28, output_tokens=5)})
## Using a RunnableBranch
A `RunnableBranch` is a special type of runnable that allows you to define a set of conditions and runnables to execute based on the input. It does **not** offer anything that you can't achieve in a custom function as described above, so we recommend using a custom function instead.
A `RunnableBranch` is initialized with a list of (condition, runnable) pairs and a default runnable. It selects which branch by passing each condition the input it's invoked with. It selects the first condition to evaluate to True, and runs the corresponding runnable to that condition with the input.
If no provided conditions match, it runs the default runnable.
Here's an example of what it looks like in action:
```python
from langchain_core.runnables import RunnableBranch
branch = RunnableBranch(
(lambda x: "anthropic" in x["topic"].lower(), anthropic_chain),
(lambda x: "langchain" in x["topic"].lower(), langchain_chain),
general_chain,
)
full_chain = {"topic": chain, "question": lambda x: x["question"]} | branch
full_chain.invoke({"question": "how do I use Anthropic?"})
```
AIMessage(content="As Dario Amodei told me, to use Anthropic, you should first familiarize yourself with our mission and principles. Anthropic is committed to developing safe and beneficial artificial intelligence that can help solve important problems facing humanity. \n\nTo get started, I recommend exploring the resources on our website, which cover our research, products, and approach to AI development. You can also reach out to our team to learn more about how Anthropic's technology and services can support your specific needs.\n\nThe key is to engage with us in a way that aligns with our values of transparency, ethical AI, and a commitment to the wellbeing of humanity. We're here to collaborate and help you harness the power of advanced AI responsibly.", response_metadata={'id': 'msg_0187BVnpniPDJnVvwf3M1LdY', 'content': [ContentBlock(text="As Dario Amodei told me, to use Anthropic, you should first familiarize yourself with our mission and principles. Anthropic is committed to developing safe and beneficial artificial intelligence that can help solve important problems facing humanity. \n\nTo get started, I recommend exploring the resources on our website, which cover our research, products, and approach to AI development. You can also reach out to our team to learn more about how Anthropic's technology and services can support your specific needs.\n\nThe key is to engage with us in a way that aligns with our values of transparency, ethical AI, and a commitment to the wellbeing of humanity. We're here to collaborate and help you harness the power of advanced AI responsibly.", type='text')], 'model': 'claude-3-haiku-20240307', 'role': 'assistant', 'stop_reason': 'end_turn', 'stop_sequence': None, 'type': 'message', 'usage': Usage(input_tokens=53, output_tokens=160)})
```python
full_chain.invoke({"question": "how do I use LangChain?"})
```
AIMessage(content="As Harrison Chase told me, using LangChain involves several key steps. First, you'll need to install the LangChain library and import the necessary modules. Then, you'll want to define your language model, any data sources you plan to use, and the specific tasks you want to accomplish, such as question answering, text generation, or agent-based reasoning. \n\nLangChain provides a flexible framework for building applications that leverage large language models. It includes abstractions for things like retrievers, prompts, and chains, which allow you to compose different components together to create powerful workflows. \n\nThe documentation on the LangChain website is excellent and covers many common use cases in detail. I'd recommend starting there to get a solid understanding of the core concepts and how to apply them to your specific needs. And of course, feel free to reach out if you have any other questions - I'm always happy to share more insights from my conversations with Harrison.", response_metadata={'id': 'msg_01T1naS99wGPkEAP4LME8iAv', 'content': [ContentBlock(text="As Harrison Chase told me, using LangChain involves several key steps. First, you'll need to install the LangChain library and import the necessary modules. Then, you'll want to define your language model, any data sources you plan to use, and the specific tasks you want to accomplish, such as question answering, text generation, or agent-based reasoning. \n\nLangChain provides a flexible framework for building applications that leverage large language models. It includes abstractions for things like retrievers, prompts, and chains, which allow you to compose different components together to create powerful workflows. \n\nThe documentation on the LangChain website is excellent and covers many common use cases in detail. I'd recommend starting there to get a solid understanding of the core concepts and how to apply them to your specific needs. And of course, feel free to reach out if you have any other questions - I'm always happy to share more insights from my conversations with Harrison.", type='text')], 'model': 'claude-3-haiku-20240307', 'role': 'assistant', 'stop_reason': 'end_turn', 'stop_sequence': None, 'type': 'message', 'usage': Usage(input_tokens=50, output_tokens=205)})
```python
full_chain.invoke({"question": "whats 2 + 2"})
```
AIMessage(content='4', response_metadata={'id': 'msg_01T6T3TS6hRCtU8JayN93QEi', 'content': [ContentBlock(text='4', type='text')], 'model': 'claude-3-haiku-20240307', 'role': 'assistant', 'stop_reason': 'end_turn', 'stop_sequence': None, 'type': 'message', 'usage': Usage(input_tokens=28, output_tokens=5)})
## Routing by semantic similarity
One especially useful technique is to use embeddings to route a query to the most relevant prompt. Here's an example.
```python
from langchain_community.utils.math import cosine_similarity
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from langchain_openai import OpenAIEmbeddings
physics_template = """You are a very smart physics professor. \
You are great at answering questions about physics in a concise and easy to understand manner. \
When you don't know the answer to a question you admit that you don't know.
Here is a question:
{query}"""
math_template = """You are a very good mathematician. You are great at answering math questions. \
You are so good because you are able to break down hard problems into their component parts, \
answer the component parts, and then put them together to answer the broader question.
Here is a question:
{query}"""
embeddings = OpenAIEmbeddings()
prompt_templates = [physics_template, math_template]
prompt_embeddings = embeddings.embed_documents(prompt_templates)
def prompt_router(input):
query_embedding = embeddings.embed_query(input["query"])
similarity = cosine_similarity([query_embedding], prompt_embeddings)[0]
most_similar = prompt_templates[similarity.argmax()]
print("Using MATH" if most_similar == math_template else "Using PHYSICS")
return PromptTemplate.from_template(most_similar)
chain = (
{"query": RunnablePassthrough()}
| RunnableLambda(prompt_router)
| ChatAnthropic(model="claude-3-haiku-20240307")
| StrOutputParser()
)
```
```python
print(chain.invoke("What's a black hole"))
```
Using PHYSICS
As a physics professor, I would be happy to provide a concise and easy-to-understand explanation of what a black hole is.
A black hole is an incredibly dense region of space-time where the gravitational pull is so strong that nothing, not even light, can escape from it. This means that if you were to get too close to a black hole, you would be pulled in and crushed by the intense gravitational forces.
The formation of a black hole occurs when a massive star, much larger than our Sun, reaches the end of its life and collapses in on itself. This collapse causes the matter to become extremely dense, and the gravitational force becomes so strong that it creates a point of no return, known as the event horizon.
Beyond the event horizon, the laws of physics as we know them break down, and the intense gravitational forces create a singularity, which is a point of infinite density and curvature in space-time.
Black holes are fascinating and mysterious objects, and there is still much to be learned about their properties and behavior. If I were unsure about any specific details or aspects of black holes, I would readily admit that I do not have a complete understanding and would encourage further research and investigation.
```python
print(chain.invoke("What's a path integral"))
```
Using MATH
A path integral is a powerful mathematical concept in physics, particularly in the field of quantum mechanics. It was developed by the renowned physicist Richard Feynman as an alternative formulation of quantum mechanics.
In a path integral, instead of considering a single, definite path that a particle might take from one point to another, as in classical mechanics, the particle is considered to take all possible paths simultaneously. Each path is assigned a complex-valued weight, and the total probability amplitude for the particle to go from one point to another is calculated by summing (integrating) over all possible paths.
The key ideas behind the path integral formulation are:
1. Superposition principle: In quantum mechanics, particles can exist in a superposition of multiple states or paths simultaneously.
2. Probability amplitude: The probability amplitude for a particle to go from one point to another is calculated by summing the complex-valued weights of all possible paths.
3. Weighting of paths: Each path is assigned a weight based on the action (the time integral of the Lagrangian) along that path. Paths with lower action have a greater weight.
4. Feynman's approach: Feynman developed the path integral formulation as an alternative to the traditional wave function approach in quantum mechanics, providing a more intuitive and conceptual understanding of quantum phenomena.
The path integral approach is particularly useful in quantum field theory, where it provides a powerful framework for calculating transition probabilities and understanding the behavior of quantum systems. It has also found applications in various areas of physics, such as condensed matter, statistical mechanics, and even in finance (the path integral approach to option pricing).
The mathematical construction of the path integral involves the use of advanced concepts from functional analysis and measure theory, making it a powerful and sophisticated tool in the physicist's arsenal.
## Next steps
You've now learned how to add routing to your composed LCEL chains.
Next, check out the other how-to guides on runnables in this section.
|
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@docs@docs@how_to@routing.ipynb@.PATH_END.py
|
{
"filename": "mightee_inference.py",
"repo_name": "devinamhn/RadioGalaxies-BNNs",
"repo_path": "RadioGalaxies-BNNs_extracted/RadioGalaxies-BNNs-main/radiogalaxies_bnns/eval/mightee/mightee_inference.py",
"type": "Python"
}
|
import torch
import torchvision.transforms as T
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
from cata2data import CataData
from torch.utils.data import DataLoader
from radiogalaxies_bnns.datasets.mightee import MighteeZoo
from radiogalaxies_bnns.inference.utils import Path_Handler
from radiogalaxies_bnns.inference.models import LeNet, LeNetDrop
import radiogalaxies_bnns.inference.nonBayesianCNN.utils as cnn_utils
from radiogalaxies_bnns.eval.uncertainty.uncertainty import entropy_MI, overlapping, GMM_logits, calibration
def credible_interval(samples, credibility):
'''
calculate credible interval - equi-tailed interval instead of highest density interval
samples values and indices
'''
mean_samples = samples.mean()
sorted_samples = np.sort(samples)
lower_bound = 0.5 * (1 - credibility)
upper_bound = 0.5 * (1 + credibility)
index_lower = int(np.round(len(samples) * lower_bound))
index_upper = int(np.round(len(samples) * upper_bound))
# print('lower', index_lower, 'upper', index_upper)
return sorted_samples, index_lower, index_upper, mean_samples
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
transform = T.Compose(
[
T.ToTensor(),
T.Resize(150), # Rescale to adjust for resolution difference between MIGHTEE & RGZ - was 70
T.Normalize((1.59965605788234e-05,), (0.0038063037602458706,)),
]
)
paths = Path_Handler()._dict()
set = 'certain'
data = MighteeZoo(path=paths["mightee"], transform=transform, set="certain")
test_loader = DataLoader(data, batch_size=len(data))
for i, (x_test, y_test) in enumerate(test_loader):
x_test, y_test = x_test.to(device), y_test.to(device)
print(len(data))
print(len(y_test))
model = LeNet(in_channels = 1, output_size = 2).to(device)
# path_out = config_dict['output']['path_out']
path_out = './radiogalaxies_bnns/results/nonBayesianCNNdatashuffle/cnn_'
criterion = torch.nn.CrossEntropyLoss()
n_ensembles = 10
softmax_ensemble, logits_ensemble = cnn_utils.eval_ensemble(model, test_loader, device, n_ensembles, path_out, criterion)
softmax_ensemble = torch.reshape(softmax_ensemble, (len(y_test), n_ensembles, 2))
logits_ensemble = torch.reshape(logits_ensemble, (len(y_test), n_ensembles, 2))
avg_error_mean = []
error_all = []
entropy_all = []
mi_all = []
aleat_all = []
fr1 = 0
fr2 = 0
loss_all = []
color = []
for k in range(len(y_test)):
# print('galaxy', k)
x = [0, 1]
x = np.tile(x, (n_ensembles, 1))
target = y_test[k].cpu().detach().numpy()
if(target == 0):
fr1+= 1
elif(target==1):
fr2+= 1
# logits = pred_list[burn:][:, k:(k+1), :2].detach().numpy()
# softmax_values = F.softmax(pred_list[burn:][:, k:(k+1), :2], dim =-1).detach().numpy()
softmax_values = softmax_ensemble[k:k+1, :, :2].cpu().detach().numpy()
loss = criterion(logits_ensemble[k:k+1, :, :2][0], torch.tile(y_test[k], (n_ensembles, 1)).flatten())
sorted_softmax_values, lower_index, upper_index, mean_samples = credible_interval(softmax_values[:, :, 0].flatten(), 1) #0.64
upper_index = upper_index - 1
# print("90% credible interval for FRI class softmax", sorted_softmax_values[lower_index], sorted_softmax_values[upper_index])
sorted_softmax_values_fr1 = sorted_softmax_values[lower_index:upper_index]
sorted_softmax_values_fr2 = 1 - sorted_softmax_values[lower_index:upper_index]
softmax_mean = np.vstack((mean_samples, 1-mean_samples)).T
softmax_credible = np.vstack((sorted_softmax_values_fr1, sorted_softmax_values_fr2)).T
entropy, mutual_info, entropy_singlepass = entropy_MI(softmax_credible,
samples_iter= len(softmax_credible[:,0]))
pred_mean = np.argmax(softmax_mean, axis = 1)
error_mean = (pred_mean != target)*1
pred = np.argmax(softmax_credible, axis = 1)
y_test_all = np.tile(target, len(softmax_credible[:,0]))
errors = np.mean((pred != y_test_all).astype('uint8'))
avg_error_mean.append(error_mean)
error_all.append(errors)
entropy_all.append(entropy/np.log(2))
mi_all.append(mutual_info/np.log(2))
aleat_all.append(entropy_singlepass/np.log(2))
loss_all.append(loss.item())
print(fr1, fr2)
print("mean and std of error")
# print(error_all)
print("mean", np.round(np.mean(error_all)*100, 3))
print("std", np.round(np.std(error_all), 3 ))
print("Average CE Loss")
# print(loss_all)
print("mean", np.round(np.mean(loss_all), 3))
print("std", np.round(np.std(loss_all), 3 ))
fr1_start = 0 #{0}
# fr1_end = fr1 #{49, 68}
# fr2_start = fr1 #49, 68
# fr2_end = len(y_test) #len(val_indices) #{104, 145}
n_bins = 8
print('BINS', 8)
path = './'
uce = calibration(path, np.array(error_all), np.array(entropy_all), n_bins, x_label = 'predictive entropy')
print("Predictive Entropy")
print("uce = ", np.round(uce, 2))
uce = calibration(path, np.array(error_all), np.array(mi_all), n_bins, x_label = 'mutual information')
print("Mutual Information")
print("uce = ", np.round(uce, 2))
uce = calibration(path, np.array(error_all), np.array(aleat_all), n_bins, x_label = 'average entropy')
print("Average Entropy")
print("uce = ", np.round(uce, 2))
exit()
def fig2img(fig):
"""Convert a Matplotlib figure to a PIL Image and return it"""
import io
buf = io.BytesIO()
fig.savefig(buf, bbox_inches="tight")
buf.seek(0)
img = Image.open(buf)
return img
for b, (im_batch, y_batch) in enumerate(DataLoader(data, batch_size=16)):
fig = plt.figure(figsize=(13.0, 13.0))
fig.subplots_adjust(0, 0, 1, 1)
grid = ImageGrid(fig, 111, nrows_ncols=(4, 4), axes_pad=0)
for i, (ax, im, y) in enumerate(zip(grid, list(im_batch), list(y_batch))):
# im = im_batch[i].squeeze().numpy()
im = im.squeeze().numpy()
ax.axis("off")
text = f"FR{y+1}"
ax.text(1, 66, text, fontsize=23, color="yellow")
# contours
threshold = 1
ax.contour(np.where(im > threshold, 1, 0), cmap="cool", alpha=0.1)
ax.imshow(im, cmap="hot")
plt.axis("off")
pil_img = fig2img(fig)
plt.savefig(f"samples/{set}_{b}highres.png")
plt.close(fig)
|
devinamhnREPO_NAMERadioGalaxies-BNNsPATH_START.@RadioGalaxies-BNNs_extracted@RadioGalaxies-BNNs-main@radiogalaxies_bnns@eval@mightee@mightee_inference.py@.PATH_END.py
|
{
"filename": "test_multiprocessing.py",
"repo_name": "jrenaud90/TidalPy",
"repo_path": "TidalPy_extracted/TidalPy-main/Tests/Test_Old/Test_SetZA_Multiprocessing/test_multiprocessing.py",
"type": "Python"
}
|
import os
import shutil
import pathlib
import numpy as np
import TidalPy
from TidalPy.utilities.multiprocessing import MultiprocessingInput, MultiprocessingOutput, multiprocessing_run
NUM_PROC = os.cpu_count()
if NUM_PROC is None:
NUM_PROC = 1
def func(dir_, x, y, xname, yname):
return {'test': x + y}
i1 = MultiprocessingInput('test_x', 'TestX', 0, 2, 'linear', tuple(), 3)
i2 = MultiprocessingInput('test_y', 'TestY', -3, 3, 'linear', tuple(), 3)
xx, yy = np.meshgrid(np.linspace(0, 2, 3), np.linspace(-3, 3, 3))
def test_multiprocessing():
# Create temp directory
file_path = pathlib.Path(__file__).parent.resolve()
dir_path = os.path.join(file_path, 'tpy_temp')
if not os.path.exists(dir_path):
os.makedirs(dir_path)
try:
# Run multiprocessing test
mp_results = multiprocessing_run(dir_path, 'test', func, (i1, i2), max_procs=NUM_PROC,
allow_low_procs=True, avoid_crashes=False)
assert mp_results is not None
assert type(mp_results) == list
assert isinstance(mp_results[0], MultiprocessingOutput)
# Test results
test_output = list()
for x_ in np.linspace(0, 2, 3):
for y_ in np.linspace(-3, 3, 3):
test_output.append({'test': x_ + y_})
for mp_result, test_result in zip(mp_results, test_output):
assert mp_result.result == test_result
# Test directory structure
log_path = os.path.join(dir_path, 'tpy_mp.log')
xdata_path = os.path.join(dir_path, 'test_x.npy')
ydata_path = os.path.join(dir_path, 'test_y.npy')
with open(log_path) as log_file:
# Log file opened without issue.
pass
with open(xdata_path) as xdata:
# xdata file opened without issue.
pass
with open(ydata_path) as ydata:
# ydata file opened without issue.
pass
# Test a specific case directory structure
case0_path = os.path.join(dir_path, 'index_(0, 0)_run_0')
case0_log_path = os.path.join(case0_path, 'mp_success.log')
with open(case0_log_path) as case0_log:
# Case log file opened without issue.
pass
# Test that case data was saved correctly
case0_data_path = os.path.join(case0_path, 'mp_results.npz')
case0_result = np.load(case0_data_path)
assert case0_result is not None
assert 'test' in case0_result
assert case0_result['test'] == test_output[0]['test']
# Try again with a different case
case5_path = os.path.join(dir_path, 'index_(1, 2)_run_5')
case5_data_path = os.path.join(case5_path, 'mp_results.npz')
case5_result = np.load(case5_data_path)
assert case5_result is not None
assert 'test' in case5_result
assert case5_result['test'] == test_output[5]['test']
# Get rid of references to loaded items so we can delete them
del case0_result, case5_result
finally:
# Delete temp directory
shutil.rmtree(dir_path)
|
jrenaud90REPO_NAMETidalPyPATH_START.@TidalPy_extracted@TidalPy-main@Tests@Test_Old@Test_SetZA_Multiprocessing@test_multiprocessing.py@.PATH_END.py
|
{
"filename": "odepack.py",
"repo_name": "waynebhayes/SpArcFiRe",
"repo_path": "SpArcFiRe_extracted/SpArcFiRe-master/scripts/SpArcFiRe-pyvenv/lib/python2.7/site-packages/scipy/integrate/odepack.py",
"type": "Python"
}
|
# Author: Travis Oliphant
from __future__ import division, print_function, absolute_import
__all__ = ['odeint']
from . import _odepack
from copy import copy
import warnings
class ODEintWarning(Warning):
pass
_msgs = {2: "Integration successful.",
1: "Nothing was done; the integration time was 0.",
-1: "Excess work done on this call (perhaps wrong Dfun type).",
-2: "Excess accuracy requested (tolerances too small).",
-3: "Illegal input detected (internal error).",
-4: "Repeated error test failures (internal error).",
-5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
-6: "Error weight became zero during problem.",
-7: "Internal workspace insufficient to finish (internal error)."
}
def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
mxords=5, printmessg=0):
"""
Integrate a system of ordinary differential equations.
Solve a system of ordinary differential equations using lsoda from the
FORTRAN library odepack.
Solves the initial value problem for stiff or non-stiff systems
of first order ode-s::
dy/dt = func(y, t0, ...)
where y can be a vector.
*Note*: The first two arguments of ``func(y, t0, ...)`` are in the
opposite order of the arguments in the system definition function used
by the `scipy.integrate.ode` class.
Parameters
----------
func : callable(y, t0, ...)
Computes the derivative of y at t0.
y0 : array
Initial condition on y (can be a vector).
t : array
A sequence of time points for which to solve for y. The initial
value point should be the first element of this sequence.
args : tuple, optional
Extra arguments to pass to function.
Dfun : callable(y, t0, ...)
Gradient (Jacobian) of `func`.
col_deriv : bool, optional
True if `Dfun` defines derivatives down columns (faster),
otherwise `Dfun` should define derivatives across rows.
full_output : bool, optional
True if to return a dictionary of optional outputs as the second output
printmessg : bool, optional
Whether to print the convergence message
Returns
-------
y : array, shape (len(t), len(y0))
Array containing the value of y for each desired time in t,
with the initial value `y0` in the first row.
infodict : dict, only returned if full_output == True
Dictionary containing additional output information
======= ============================================================
key meaning
======= ============================================================
'hu' vector of step sizes successfully used for each time step.
'tcur' vector with the value of t reached for each time step.
(will always be at least as large as the input times).
'tolsf' vector of tolerance scale factors, greater than 1.0,
computed when a request for too much accuracy was detected.
'tsw' value of t at the time of the last method switch
(given for each time step)
'nst' cumulative number of time steps
'nfe' cumulative number of function evaluations for each time step
'nje' cumulative number of jacobian evaluations for each time step
'nqu' a vector of method orders for each successful step.
'imxer' index of the component of largest magnitude in the
weighted local error vector (e / ewt) on an error return, -1
otherwise.
'lenrw' the length of the double work array required.
'leniw' the length of integer work array required.
'mused' a vector of method indicators for each successful time step:
1: adams (nonstiff), 2: bdf (stiff)
======= ============================================================
Other Parameters
----------------
ml, mu : int, optional
If either of these are not None or non-negative, then the
Jacobian is assumed to be banded. These give the number of
lower and upper non-zero diagonals in this banded matrix.
For the banded case, `Dfun` should return a matrix whose
rows contain the non-zero bands (starting with the lowest diagonal).
Thus, the return matrix `jac` from `Dfun` should have shape
``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
The data in `jac` must be stored such that ``jac[i - j + mu, j]``
holds the derivative of the `i`th equation with respect to the `j`th
state variable. If `col_deriv` is True, the transpose of this
`jac` must be returned.
rtol, atol : float, optional
The input parameters `rtol` and `atol` determine the error
control performed by the solver. The solver will control the
vector, e, of estimated local errors in y, according to an
inequality of the form ``max-norm of (e / ewt) <= 1``,
where ewt is a vector of positive error weights computed as
``ewt = rtol * abs(y) + atol``.
rtol and atol can be either vectors the same length as y or scalars.
Defaults to 1.49012e-8.
tcrit : ndarray, optional
Vector of critical points (e.g. singularities) where integration
care should be taken.
h0 : float, (0: solver-determined), optional
The step size to be attempted on the first step.
hmax : float, (0: solver-determined), optional
The maximum absolute step size allowed.
hmin : float, (0: solver-determined), optional
The minimum absolute step size allowed.
ixpr : bool, optional
Whether to generate extra printing at method switches.
mxstep : int, (0: solver-determined), optional
Maximum number of (internally defined) steps allowed for each
integration point in t.
mxhnil : int, (0: solver-determined), optional
Maximum number of messages printed.
mxordn : int, (0: solver-determined), optional
Maximum order to be allowed for the non-stiff (Adams) method.
mxords : int, (0: solver-determined), optional
Maximum order to be allowed for the stiff (BDF) method.
See Also
--------
ode : a more object-oriented integrator based on VODE.
quad : for finding the area under a curve.
Examples
--------
The second order differential equation for the angle `theta` of a
pendulum acted on by gravity with friction can be written::
theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
where `b` and `c` are positive constants, and a prime (') denotes a
derivative. To solve this equation with `odeint`, we must first convert
it to a system of first order equations. By defining the angular
velocity ``omega(t) = theta'(t)``, we obtain the system::
theta'(t) = omega(t)
omega'(t) = -b*omega(t) - c*sin(theta(t))
Let `y` be the vector [`theta`, `omega`]. We implement this system
in python as:
>>> def pend(y, t, b, c):
... theta, omega = y
... dydt = [omega, -b*omega - c*np.sin(theta)]
... return dydt
...
We assume the constants are `b` = 0.25 and `c` = 5.0:
>>> b = 0.25
>>> c = 5.0
For initial conditions, we assume the pendulum is nearly vertical
with `theta(0)` = `pi` - 0.1, and it initially at rest, so
`omega(0)` = 0. Then the vector of initial conditions is
>>> y0 = [np.pi - 0.1, 0.0]
We generate a solution 101 evenly spaced samples in the interval
0 <= `t` <= 10. So our array of times is:
>>> t = np.linspace(0, 10, 101)
Call `odeint` to generate the solution. To pass the parameters
`b` and `c` to `pend`, we give them to `odeint` using the `args`
argument.
>>> from scipy.integrate import odeint
>>> sol = odeint(pend, y0, t, args=(b, c))
The solution is an array with shape (101, 2). The first column
is `theta(t)`, and the second is `omega(t)`. The following code
plots both components.
>>> import matplotlib.pyplot as plt
>>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
>>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
>>> plt.legend(loc='best')
>>> plt.xlabel('t')
>>> plt.grid()
>>> plt.show()
"""
if ml is None:
ml = -1 # changed to zero inside function call
if mu is None:
mu = -1 # changed to zero inside function call
t = copy(t)
y0 = copy(y0)
output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
full_output, rtol, atol, tcrit, h0, hmax, hmin,
ixpr, mxstep, mxhnil, mxordn, mxords)
if output[-1] < 0:
warning_msg = _msgs[output[-1]] + " Run with full_output = 1 to get quantitative information."
warnings.warn(warning_msg, ODEintWarning)
elif printmessg:
warning_msg = _msgs[output[-1]]
warnings.warn(warning_msg, ODEintWarning)
if full_output:
output[1]['message'] = _msgs[output[-1]]
output = output[:-1]
if len(output) == 1:
return output[0]
else:
return output
|
waynebhayesREPO_NAMESpArcFiRePATH_START.@SpArcFiRe_extracted@SpArcFiRe-master@scripts@SpArcFiRe-pyvenv@lib@python2.7@site-packages@scipy@integrate@odepack.py@.PATH_END.py
|
{
"filename": "_color.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scattergeo/marker/_color.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(self, plotly_name="color", parent_name="scattergeo.marker", **kwargs):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "calc"),
colorscale_path=kwargs.pop(
"colorscale_path", "scattergeo.marker.colorscale"
),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scattergeo@marker@_color.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "plotly/plotly.py",
"repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/layout/mapbox/domain/__init__.py",
"type": "Python"
}
|
import sys
from typing import TYPE_CHECKING
if sys.version_info < (3, 7) or TYPE_CHECKING:
from ._y import YValidator
from ._x import XValidator
from ._row import RowValidator
from ._column import ColumnValidator
else:
from _plotly_utils.importers import relative_import
__all__, __getattr__, __dir__ = relative_import(
__name__,
[],
[
"._y.YValidator",
"._x.XValidator",
"._row.RowValidator",
"._column.ColumnValidator",
],
)
|
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@layout@mapbox@domain@__init__.py@.PATH_END.py
|
{
"filename": "StayingPositive.ipynb",
"repo_name": "rodluger/starry",
"repo_path": "starry_extracted/starry-master/notebooks/StayingPositive.ipynb",
"type": "Jupyter Notebook"
}
|
# Staying Positive
```python
%matplotlib inline
```
```python
%run notebook_setup.py
```
Unfortunately, there's no trivial way of setting the spherical harmonic coefficients to ensure the map intensity is non-negative everywhere. One helpful thing to keep in mind is that the average intensity across the surface does not change when you modify the spherical harmonic coefficients. That's because all spherical harmonics other than $Y_{0,0}$ are perfectly anti-symmetric: for every bright region on the surface, there's an equally dark region on the other side that cancels its contribution to the surface-integrated intensity. What this means is that the magnitude of the spherical harmonic coefficients controls the departure of the intensity from this mean value (which is equal to the intensity of the $Y_{0,0}$ harmonic, $\frac{1}{\pi}$). One way to ensure the map is non-negative everywhere is therefore simply to limit the amplitude of all spherical harmonic coefficients to a small value.
## Spherical harmonic maps
However, in some cases it might be useful to check in the general case whether or not a map is positive semi-definite. This entails running a nonlinear minimization on the intensity across the surface. For spherical harmonic maps, this is implemented in the `minimize()` method. Let's import `starry`, instantiate a map, and take a look.
```python
import numpy as np
import matplotlib.pyplot as plt
import starry
starry.config.lazy = False
starry.config.quiet = True
```
Let's set the coefficients randomly...
```python
map = starry.Map(ydeg=5)
np.random.seed(0)
map[1:, :] = 0.1 * np.random.randn(map.Ny - 1)
```
... and plot the map on a lat-lon grid:
```python
image = map.render(projection="rect")
plt.imshow(image, origin="lower", cmap="plasma", extent=(-180, 180, -90, 90))
plt.xlabel("longitude [deg]")
plt.ylabel("latitude [deg]")
plt.colorbar();
```
```python
# Pre-run this to ensure it's compiled
map.minimize();
```
The map clearly goes negative in certain regions. If we call `minimize()`, we can get the latitude, longitude, and value of the intensity at the minimum:
```python
%%time
lat, lon, value = map.minimize()
```
```python
print(lat, lon, value)
```
```python
plt.imshow(image, origin="lower", cmap="plasma", extent=(-180, 180, -90, 90))
plt.xlabel("longitude [deg]")
plt.ylabel("latitude [deg]")
plt.axvline(lon, color="k", ls="--")
plt.axhline(lat, color="k", ls="--")
plt.title("minimum: {0:.3f}".format(value))
plt.colorbar();
```
The method is *fairly* fast, so it could be used, for example, as a penalty when doing inference.
## Limb-darkened maps
For limb-darkened maps, it's a little easier to check whether the map is positive everywhere. Because the limb darkening profile is one-dimensional, we can use [Sturm's theorem](https://en.wikipedia.org/wiki/Sturm%27s_theorem) to verify that
* The intensity is non-negative everywhere
* The intensity is monotonically decreasing toward the limb
Limb-darkened maps (or spherical harmonic maps with a limb darkening filter) implement the `limbdark_is_physical` method, which checks whether both points are true. Note, importantly, that the second point is specific to limb *darkening*. In principle the specific intensity could get brighter toward the limb (as is the case at certain wavelengths for the Sun), so you wouldn't want to use in those cases.
```python
map = starry.Map(udeg=4)
```
Let's try this on a few limb-darkened maps:
```python
map[1:] = [0.5, 0.25, 0.5, 0.25]
```
```python
map.show()
```
Is it physical?
```python
map.limbdark_is_physical()
```
No! Let's plot the intensity as a function of $\mu$ to see why:
```python
mu = np.linspace(0, 1, 1000)
plt.plot(mu, map.intensity(mu=mu))
plt.axhline(0, color="k", ls="--")
plt.gca().invert_xaxis()
plt.xlabel(r"$\mu$")
plt.ylabel("relative intensity");
```
The intensity is negative close to the limb.
Let's try a different coefficient vector:
```python
map[1:] = [0.1, -2.0, 2.25, 0.5]
```
```python
map.show()
```
Is it physical?
```python
map.limbdark_is_physical()
```
```python
mu = np.linspace(0, 1, 1000)
plt.plot(mu, map.intensity(mu=mu))
plt.axhline(0, color="k", ls="--")
plt.gca().invert_xaxis()
plt.xlabel(r"$\mu$")
plt.ylabel("relative intensity");
```
Even though it's positive everywhere, it's not monotonic!
One last example:
```python
map[1:] = [0.5, -0.1, 0.25, 0.25]
```
```python
map.show()
```
Is it physical?
```python
map.limbdark_is_physical()
```
```python
mu = np.linspace(0, 1, 1000)
plt.plot(mu, map.intensity(mu=mu))
plt.axhline(0, color="k", ls="--")
plt.gca().invert_xaxis()
plt.xlabel(r"$\mu$")
plt.ylabel("relative intensity");
```
This one is both non-negative everywhere *and* monotonic, so it's a physical limb darkening model.
|
rodlugerREPO_NAMEstarryPATH_START.@starry_extracted@starry-master@notebooks@StayingPositive.ipynb@.PATH_END.py
|
{
"filename": "distrans.py",
"repo_name": "itseez/opencv",
"repo_path": "opencv_extracted/opencv-master/samples/python/distrans.py",
"type": "Python"
}
|
#!/usr/bin/env python
'''
Distance transform sample.
Usage:
distrans.py [<image>]
Keys:
ESC - exit
v - toggle voronoi mode
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
from common import make_cmap
def main():
import sys
try:
fn = sys.argv[1]
except:
fn = 'fruits.jpg'
fn = cv.samples.findFile(fn)
img = cv.imread(fn, cv.IMREAD_GRAYSCALE)
if img is None:
print('Failed to load fn:', fn)
sys.exit(1)
cm = make_cmap('jet')
need_update = True
voronoi = False
def update(dummy=None):
global need_update
need_update = False
thrs = cv.getTrackbarPos('threshold', 'distrans')
mark = cv.Canny(img, thrs, 3*thrs)
dist, labels = cv.distanceTransformWithLabels(~mark, cv.DIST_L2, 5)
if voronoi:
vis = cm[np.uint8(labels)]
else:
vis = cm[np.uint8(dist*2)]
vis[mark != 0] = 255
cv.imshow('distrans', vis)
def invalidate(dummy=None):
global need_update
need_update = True
cv.namedWindow('distrans')
cv.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
update()
while True:
ch = cv.waitKey(50)
if ch == 27:
break
if ch == ord('v'):
voronoi = not voronoi
print('showing', ['distance', 'voronoi'][voronoi])
update()
if need_update:
update()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
|
itseezREPO_NAMEopencvPATH_START.@opencv_extracted@opencv-master@samples@python@distrans.py@.PATH_END.py
|
{
"filename": "tree.py",
"repo_name": "ArjunS07/PUExtraTrees",
"repo_path": "PUExtraTrees_extracted/PUExtraTrees-main/src/PUExtraTrees_ArjunS07_pip/tree.py",
"type": "Python"
}
|
# PU ExtraTree - A DT Classifier for PU Learning
import numpy as np
import scipy.stats
import scipy.sparse
class PUExtraTree:
def __init__(self, risk_estimator = "nnPU",
loss = "quadratic",
max_depth = None,
min_samples_leaf = 1,
max_features = "sqrt",
max_candidates = 1):
"""
Parameters
----------
risk_estimator : {"PN", "uPU", "nnPU"}, default='nnPU'
PU data based risk estimator. Supports supervised (PN) learning, unbiased PU (uPU) learning and nonnegative PU (nnPU) learning.
loss : {"quadratic", "logistic"}, default='quadratic'
The function to measure the cost of making an incorrect prediction. Supported loss functions are:
"quadratic" l(v,y) = (1-vy)^2 and
"logistic" l(v,y) = ln(1+exp(-vy)).
max_depth : int or None, default=None
The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_leaf samples.
min_samples_leaf : int, default=1
The minimum number of samples required to be at a leaf node. The default is 1.
max_features : int or {"sqrt", "all"}, default="sqrt"
The number of features to consider when looking for the best split. If "sqrt", then max_features = ceil(sqrt(n_features)). If "all", then max_features = n_features.
max_candidates : int, default=1
Number of randomly chosen split points to consider for each candidate feature.
Returns
-------
None.
"""
self.risk_estimator = risk_estimator
self.loss = loss
self.max_depth = max_depth
self.min_samples_leaf = min_samples_leaf
self.max_features = max_features
self.max_candidates = max_candidates
self.is_trained = False # indicate if tree empty/trained
self.leaf_count = 0
self.current_max_depth = 0
self.nodes = {(0,0): {'data': None, 'j': None, 'xi': None, 'g': None,
'is_leaf': None, 'risk_reduction': None}}
def create_successor(self, node, side):
"""
Create an empty child node (either T or F) in the tree.
Parameters
----------
node : tuple of length 2.
The parent node. First element is the depth in the tree, second element is the position at that depth.
side : {"T", "F"} or {"L", "R"}
Whether the node corresponds to a True or False split.
Returns
-------
None.
"""
row, column = node
if side in ['T','L']:
self.nodes[(row+1, 2*column)] = {'data': None, 'j': None,
'xi': None, 'g': None,
'is_leaf': None, 'loss': None,
'risk_reduction': None}
elif side in ['F','R']:
self.nodes[(row+1, 2*column+1)] = {'data': None, 'j': None,
'xi': None, 'g': None,
'is_leaf': None, 'loss': None,
'risk_reduction': None}
elif side not in ['T','F','L','R']:
print('choose valid position of child node: \'L\', \'R\', \'T\', \'F\'')
def get_parent(self, node, return_truth_val):
"""
Return parent node, and optionally the relationship to child node (T/F).
Parameters
----------
node : tuple of length 2
The child node.
return_truth_val : bool
Indicate whether the truth value should also be returned, that is, whether the child node corresponds to a true or false split.
Returns
-------
tuple of length 2 or (tuple of length 2, bool)
The parent node, optionally the relationships to the parent nodes.
"""
parent = (node[0] - 1, node[1] // 2)
if return_truth_val:
if node[1] % 2 == 0:
return parent, True
else:
return parent, False
else:
return parent
def get_ancestory(self, node):
"""
Get parent nodes and relationship to the child nodes all the way to the root.
Parameters
----------
node : tuple of length 2
Child node.
Returns
-------
list
List of nodes.
bools : list
List of bools with the relationships to the parents.
"""
chain = [node]
bools = []
while chain[-1] != (0,0):
parent, relationship = self.get_parent(chain[-1], True)
chain += [parent]
bools += [relationship]
return chain[1:], bools
def load_tree(self, nodes):
"""
Load saved tree.
Parameters
----------
nodes : dictionary
Dictionary describing the trained decision tree. Tyalphacally output from self.nodes.
Returns
-------
None.
"""
self.nodes = nodes
self.is_trained = True
def fit(self, alpha, P = None, U = None, N = None):
"""
Fit the decision tree.
Parameters
----------
alpha : float
Prior probability that an example belongs to the positive class.
P : array-like of shape (n_p, n_features), default=None
Training samples from the positive class.
U : array-like of shape (n_u, n_features), default=None
Unlabeled training samples.
N : array-like of shape (n_n, n_features), default=None
Training samples from the negative class if performing PN learning.
Returns
-------
self
Returns instance of self.
"""
if self.risk_estimator in ['uPU', 'nnPU']:
X = np.concatenate((P, U), axis = 0)
y = np.concatenate((np.ones(len(P)), np.zeros(len(U))))
elif self.risk_estimator in ['PN']:
X = np.concatenate((P, N), axis = 0)
y = np.concatenate((np.ones(len(P)), -np.ones(len(N))))
# X = X.astype(np.float32)
y = y.astype(np.int8).flatten()
n, self.d = X.shape
n_p = (y == 1).sum()
n_u = (y == 0).sum()
n_n = (y == -1).sum()
self.alpha = alpha
if self.alpha is None:
print('please specify alpha')
if self.max_features == 'sqrt':
self.max_features = int(np.ceil(np.sqrt(X.shape[1])))
elif self.max_features == 'all':
self.max_features = X.shape[1]
elif self.max_features in [i for i in range(1, self.d+1)]:
None
else:
print('select valid number of max features to consider splitting on.')
return None
self.nodes[(0,0)]['data'] = scipy.sparse.coo_matrix(np.ones(n).astype(bool))
def data_at_node(node):
# return subset of training data in partition specified by certain node
if self.nodes[node]['data'] is not None:
return self.nodes[node]['data'].toarray()[0]
else:
# get indices of data at parent
parent_node, relationship = self.get_parent(node, True)
ind_parent = self.nodes[parent_node]['data'].toarray()[0].copy()
checks = (X[ind_parent, self.nodes[parent_node]['j']] <= self.nodes[parent_node]['xi']) == relationship
ind_parent[ind_parent] = checks.flatten()
self.nodes[node]['data'] = scipy.sparse.coo_matrix(ind_parent)
return ind_parent
def impurity_node(y_sigma):
# impurity of single node
if self.risk_estimator in ["uPU", "nnPU"]:
Wp = (y_sigma == 1).sum() * self.alpha/n_p
Wn = (y_sigma == 0).sum()/n_u - Wp
if Wp + Wn == 0:
vstar = float('inf')
else:
vstar = Wp/(Wp + Wn)
elif self.risk_estimator in ['PN']:
Wp = (y_sigma == 1).sum() * self.alpha/n_p
Wn = (y_sigma == -1).sum() * (1-self.alpha)/n_n
if Wp + Wn == 0:
vstar = float('inf')
else:
vstar = Wp/(Wp + Wn)
if self.loss == "quadratic":
if self.risk_estimator == "uPU" and vstar == float('inf'):
return -float('inf')
elif self.risk_estimator == "nnPU" and vstar > 1:
return 0
else:
return 4 * (Wp + Wn) * vstar * (1 - vstar)
elif self.loss == "logistic":
if self.risk_estimator == "uPU" and vstar > 1:
return -float('inf')
elif self.risk_estimator in ["uPU", "nnPU", "PN"] and vstar in [0,1]:
return 0
elif self.risk_estimator == "nnPU" and vstar > 1:
return 0
else:
return (Wp + Wn) * (-vstar*np.log(vstar) - (1-vstar)*np.log(1-vstar))
def impurity_split(sigma, j, xi):
mask = (X[sigma, j] <= xi).flatten()
imT = impurity_node(y[sigma][mask])
imF = impurity_node(y[sigma][~mask])
return imT + imF
def regional_prediction_function(y_sigma):
if self.risk_estimator in ["uPU", "nnPU"]:
Wp = (y_sigma == 1).sum() * self.alpha/n_p
Wn = (y_sigma == 0).sum()/n_u - Wp
if Wp + Wn == 0:
vstar = float('inf')
else:
vstar = Wp/(Wp + Wn)
elif self.risk_estimator in ["PN"]:
Wp = (y_sigma == 1).sum() * self.alpha/n_p
Wn = (y_sigma == -1).sum() * (1-self.alpha)/n_n
if Wp + Wn == 0:
vstar = float('inf')
else:
vstar = Wp/(Wp + Wn)
if vstar > 0.5:
return 1
elif vstar < 0.5:
return -1
elif vstar == 0.5:
return 2*np.random.binomial(1,0.5)-1
def construct_subtree(node, sigma):
# first check stopalphang criteria
impurity = impurity_node(y[sigma])
# check node pure
if self.risk_estimator in ['nnPU', 'PN']:
c1 = impurity > 0
elif self.risk_estimator == 'uPU':
if y[sigma].sum() == 0:
c1 = impurity > 0
else:
c1 = impurity > -float('inf')
# check max depth reached
if self.max_depth is None:
c2 = True
else:
c2 = node[0] < self.max_depth # max depth reached
c3 = self.min_samples_leaf < sigma.sum() # minimum samples in node reached
att_ptp = np.ptp(X[sigma], axis = 0)
c4 = att_ptp.sum() > 0 # check if there is any variability in features
# c4 = np.unique(X[sigma], axis = 0).shape[0] > 1
# check if any of the criteria satisfied
# if so, turn into a leaf node
if c1*c2*c3*c4 == 0:
self.nodes[node]['is_leaf'] = True
lab = regional_prediction_function(y[sigma])
self.nodes[node]['g'] = lab
self.nodes[node]['risk_reduction'] = 0
self.leaf_count += 1
else:
self.nodes[node]['is_leaf'] = False
# find valid nodes that can be used for a split
atts = []
for i in range(self.d):
if att_ptp[i] > 0:
atts += [i]
# ranomly alphack candiates attributes
attributes = np.random.choice(atts, size = min(self.max_features, len(atts)), replace = False)
candidates = []
candidate_attributes = []
candidate_cut_points = []
for i in range(len(attributes)):
for j in range(self.max_candidates):
# need to guard against errors caused by finite precision
a_,b_,c_,d_ = np.unique(X[sigma, attributes[i]])[[0,1,-2,-1]]
cut_point = np.random.uniform(a_ + 2*(b_-a_)/5, c_ + 3*(d_-c_)/5)
candidates += [[attributes[i], cut_point]]
candidate_attributes += [attributes[i]]
candidate_cut_points += [cut_point]
impurities = []
for i in range(len(candidates)):
impurities += [impurity_split(sigma, candidate_attributes[i], candidate_cut_points[i])]
minimiser = np.argmin(impurities)
best_attribute = candidate_attributes[minimiser]
best_cut_point = candidate_cut_points[minimiser]
self.nodes[node]['j'] = int(best_attribute)
self.nodes[node]['xi'] = best_cut_point
self.nodes[node]['risk_reduction'] = impurity - impurities[minimiser]
# create successors of current node
self.create_successor(node, 'T')
self.create_successor(node, 'F')
# get set of data in these successors
succs = ((node[0]+1, 2*node[1]), (node[0]+1, 2*node[1]+1))
sigma_T = data_at_node(succs[0])
sigma_F = data_at_node(succs[1])
#keep tabs on how training is going
# if node[0] > self.current_max_depth:
# self.current_max_depth = node[0]
# if self.current_max_depth % 30 == 0:
# if self.current_max_depth > 1:
# print('current max depth', self.current_max_depth)
# print('current max depth', self.current_max_depth)
# construct_subtree on the sucessors
construct_subtree(succs[0], sigma_T)
construct_subtree(succs[1], sigma_F)
# train the dt
construct_subtree((0,0), np.ones(n).astype(bool))
self.is_trained = True
return self
def predict(self, X):
"""
Predict classes for examples in X.
The predicted class of an input sample is the majority vote by the trees in the forest.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The test samples.
Returns
-------
preds : array of shape (n_samples,)
The predicted classes.
"""
# first check to see if the tree is empty/trained
if self.is_trained:
preds = np.zeros(len(X)).astype(np.int8)
for i in range(len(X)):
X_ = X[i]
a,b = 0,0
tnode = self.nodes[(a,b)]
while not tnode['is_leaf']:
check = X_[tnode['j']] <= tnode['xi']
if check:
b = 2*b
else:
b = 2*b + 1
a += 1
tnode = self.nodes[(a,b)]
if tnode['is_leaf']:
preds[i] = tnode['g']
return preds
else:
print('tree not finished training!')
def n_leaves(self):
"""
Get the number of leaf nodes in a tree (number of regions created in feature space).
Returns
-------
temp : int
Number of leaf nodes in the classifier.
"""
return self.leaf_count
def get_depth(self):
"""
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf.
Returns
-------
max_depth : int
The maximum depth of the tree.
"""
max_depth = -1
for node in self.nodes.keys():
if node[0] > max_depth:
max_depth = node[0]
return max_depth
def feature_importances(self):
"""
Compute the risk reduction feature importances.
Returns
-------
impurities : array-like of shape (n_features,)
Risk reduction feature importances.
"""
impurities = np.zeros([self.d])
for node in self.nodes:
if self.nodes[node]['j'] is not None:
impurities[self.nodes[node]['j']] += self.nodes[node]['risk_reduction']
return impurities
|
ArjunS07REPO_NAMEPUExtraTreesPATH_START.@PUExtraTrees_extracted@PUExtraTrees-main@src@PUExtraTrees_ArjunS07_pip@tree.py@.PATH_END.py
|
{
"filename": "hist3d.py",
"repo_name": "matplotlib/matplotlib",
"repo_path": "matplotlib_extracted/matplotlib-main/galleries/examples/mplot3d/hist3d.py",
"type": "Python"
}
|
"""
==============================
Create 3D histogram of 2D data
==============================
Demo of a histogram for 2D data as a bar graph in 3D.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])
# Construct arrays for the anchor positions of the 16 bars.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij")
xpos = xpos.ravel()
ypos = ypos.ravel()
zpos = 0
# Construct arrays with the dimensions for the 16 bars.
dx = dy = 0.5 * np.ones_like(zpos)
dz = hist.ravel()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average')
plt.show()
# %%
# .. tags::
# plot-type: 3D, plot-type: histogram,
# level: beginner
|
matplotlibREPO_NAMEmatplotlibPATH_START.@matplotlib_extracted@matplotlib-main@galleries@examples@mplot3d@hist3d.py@.PATH_END.py
|
{
"filename": "download_jp2_set.py",
"repo_name": "Helioviewer-Project/jp2gen",
"repo_path": "jp2gen_extracted/jp2gen-master/py/download_jp2_set.py",
"type": "Python"
}
|
#
# Download a set of jp2 files from helioviewer
#
import os
import datetime
import astropy.units as u
from sunpy.time import parse_time
from sunpy.net.helioviewer import HelioviewerClient
cadence = 28 * u.day
start_time = parse_time('2010/10/01')
end_time = parse_time('2017/02/01')
hv = HelioviewerClient()
observatory = 'SDO'
instrument = 'AIA'
detector = 'AIA'
measurements = ['94', '131', '171', '193', '211', '304', '335', '1600', '1700', '4500']
#measurements = ['193', '211', '335', '1600', '1700', '4500']
storage = os.path.expanduser('~/Data/hvp/aia_color_correction')
if not os.path.isdir(storage):
os.makedirs(storage)
for measurement in measurements:
# Make the storage directory
storage_measurement = os.path.join(storage, measurement)
if not os.path.isdir(storage_measurement):
os.makedirs(storage_measurement)
today = start_time
while today <= end_time:
# Get the next file
filepath = hv.download_jp2(today, observatory=observatory,
instrument=instrument, detector=detector,
measurement=measurement)
# Move the file to the storage location
_dummy, filename = os.path.split(filepath)
os.rename(filepath, os.path.join(storage_measurement, filename))
today += datetime.timedelta(seconds=cadence.to(u.s).value)
|
Helioviewer-ProjectREPO_NAMEjp2genPATH_START.@jp2gen_extracted@jp2gen-master@py@download_jp2_set.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "statsmodels/statsmodels",
"repo_path": "statsmodels_extracted/statsmodels-main/statsmodels/tsa/statespace/_filters/__init__.py",
"type": "Python"
}
|
statsmodelsREPO_NAMEstatsmodelsPATH_START.@statsmodels_extracted@statsmodels-main@statsmodels@tsa@statespace@_filters@__init__.py@.PATH_END.py
|
|
{
"filename": "_colorsrc.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/bar/hoverlabel/font/_colorsrc.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="colorsrc", parent_name="bar.hoverlabel.font", **kwargs
):
super(ColorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@bar@hoverlabel@font@_colorsrc.py@.PATH_END.py
|
{
"filename": "velocity.py",
"repo_name": "ConorMacBride/mcalf",
"repo_path": "mcalf_extracted/mcalf-main/src/mcalf/visualisation/velocity.py",
"type": "Python"
}
|
import copy
import astropy.units
import numpy as np
from matplotlib import pyplot as plt
from mcalf.utils.plot import _get_mpl_cmap, calculate_extent
__all__ = ['plot_map']
def plot_map(arr, mask=None, umbra_mask=None, resolution=None, offset=(0, 0), vmin=None, vmax=None,
lw=None, show_colorbar=True, unit="km/s", ax=None):
"""Plot a velocity map array.
Parameters
----------
arr : numpy.ndarray[float] or astropy.units.quantity.Quantity, ndim=2
Two-dimensional array of velocities.
mask : numpy.ndarray[bool], ndim=2, shape=arr, optional, default=None
Mask showing the region where velocities were found for. True is outside the
velocity region and False is where valid velocities should be found. Specifying
a mask allows for errors in the velocity calculation to be black and points
outside the region to be gray. If omitted, all invalid points will be gray.
umbra_mask : numpy.ndarray[bool], ndim=2, shape=arr, optional, default=None
A mask of the umbra, True outside, False inside. If given, a contour will
outline the umbra, or other feature the mask represents.
resolution : tuple[float] or astropy.units.quantity.Quantity, optional, default=None
A 2-tuple (x, y) containing the length of each pixel in the x and y direction respectively.
If a value has type :class:`astropy.units.quantity.Quantity`, its axis label will
include its attached unit, otherwise the unit will default to Mm.
If `resolution` is None, both axes will be ticked with the default pixel value
with no axis labels.
offset : tuple[float] or int, length=2, optional, default=(0, 0)
Two offset values (x, y) for the x and y axis respectively.
Number of pixels from the 0 pixel to the first pixel. Defaults to the first
pixel being at 0 length units. For example, in a 1000 pixel wide dataset,
setting offset to -500 would place the 0 Mm location at the centre.
vmin : float, optional, default= ``-max(|arr|)``
Minimum velocity to plot. If not given, will be -vmax, for vmax not None.
vmax : float, optional, default= ``max(|arr|)``
Maximum velocity to plot. If not given, will be -vmin, for vmin not None.
lw : float, optional, default=None
The line width of the contour line plotted for `umbra_mask`.
Passed as `linewidths` to :func:`matplotlib.axes.Axes.contour`.
show_colorbar : bool, optional, default=True
Whether to draw a colorbar.
unit : str or astropy.units.UnitBase or astropy.units.quantity.Quantity, optional, default='km/s'
The units of `arr` data. Printed on colorbar.
ax : matplotlib.axes.Axes, optional, default=None
Axes into which the velocity map will be plotted.
Defaults to the current axis of the current figure.
Returns
-------
im : matplotlib.image.AxesImage
The object returned by :func:`matplotlib.axes.Axes.imshow` after plotting `arr`.
See Also
--------
mcalf.models.FitResults.velocities : Calculate the Doppler velocities for an array of fits.
Examples
--------
.. minigallery:: mcalf.visualisation.plot_map
"""
if ax is None:
ax = plt.gca()
# Validate `arr`
if not isinstance(arr, np.ndarray) or arr.ndim != 2:
raise TypeError('`arr` must be a numpy.ndarray with 2 dimensions.')
arr = arr.copy() # Edit a copy of `arr`
# Validate `mask` and `umbra_mask`
for n, v in (('mask', mask), ('umbra_mask', umbra_mask)):
if v is not None:
if not isinstance(v, np.ndarray) or v.ndim != 2:
raise TypeError(f'`{n}` must be a numpy.ndarray with 2 dimensions.')
if v.shape != arr.shape:
raise ValueError(f'`{n}` must be the same shape as `arr`')
# Update default unit if unit present in `arr`
if isinstance(arr[0, 0], astropy.units.quantity.Quantity):
unit = arr.unit.to_string(astropy.units.format.LatexInline)
arr = arr.value # Remove unit
# Convert a `unit` parameter that was provided as an astropy unit
if isinstance(unit, (astropy.units.UnitBase, astropy.units.quantity.Quantity)):
unit = unit.to_string(astropy.units.format.LatexInline)
# Calculate a specific extent if a resolution is specified
# TODO: Allow the `dimension` to be set by the user.
extent = calculate_extent(arr.shape, resolution, offset,
ax=ax, dimension='distance')
# Configure default colormap
cmap = copy.copy(_get_mpl_cmap('bwr'))
cmap.set_bad(color='#999999', alpha=1)
# Show invalid pixels outside the mask as black, inside as gray
if mask is not None:
# Create image from mask
mask = mask.astype(bool)
unmasked_section = np.empty_like(mask, dtype=float)
unmasked_section[mask] = np.nan # Outside mask
unmasked_section[~mask] = 1 # Inside mask
# Configure colormap of mask
cmap_mask = copy.copy(_get_mpl_cmap('gray'))
cmap_mask.set_bad(color='#999999', alpha=1)
# Show the masked region
ax.imshow(unmasked_section, cmap=cmap_mask, origin='lower',
extent=extent, interpolation='nearest')
arr[mask] = np.nan # Remove values from `arr` that are outside mask
cmap.set_bad(color='#000000', alpha=0) # Update default colormap
# Calculate range for symmetric colormap
if vmin is None and vmax is None:
vmax = np.nanmax(np.abs(arr))
vmin = -vmax
elif vmin is None:
vmin = -vmax
elif vmax is None:
vmax = -vmin
# Show the velocities
im = ax.imshow(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin='lower',
extent=extent, interpolation='nearest')
# Outline the umbra
if umbra_mask is not None:
umbra_mask = umbra_mask.astype(bool)
ax.contour(umbra_mask, [0.5], colors='k', origin='lower',
extent=extent, linewidths=lw)
if show_colorbar:
ax.get_figure().colorbar(im, ax=[ax], label=f'Doppler velocity ({unit})')
return im
|
ConorMacBrideREPO_NAMEmcalfPATH_START.@mcalf_extracted@mcalf-main@src@mcalf@visualisation@velocity.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/sunburst/marker/colorbar/tickfont/__init__.py",
"type": "Python"
}
|
import sys
from typing import TYPE_CHECKING
if sys.version_info < (3, 7) or TYPE_CHECKING:
from ._weight import WeightValidator
from ._variant import VariantValidator
from ._textcase import TextcaseValidator
from ._style import StyleValidator
from ._size import SizeValidator
from ._shadow import ShadowValidator
from ._lineposition import LinepositionValidator
from ._family import FamilyValidator
from ._color import ColorValidator
else:
from _plotly_utils.importers import relative_import
__all__, __getattr__, __dir__ = relative_import(
__name__,
[],
[
"._weight.WeightValidator",
"._variant.VariantValidator",
"._textcase.TextcaseValidator",
"._style.StyleValidator",
"._size.SizeValidator",
"._shadow.ShadowValidator",
"._lineposition.LinepositionValidator",
"._family.FamilyValidator",
"._color.ColorValidator",
],
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@sunburst@marker@colorbar@tickfont@__init__.py@.PATH_END.py
|
{
"filename": "test_rst.py",
"repo_name": "brandon-rhodes/pyephem",
"repo_path": "pyephem_extracted/pyephem-master/ephem/tests/test_rst.py",
"type": "Python"
}
|
#!/usr/bin/env python
import datetime
import doctest
import unittest
import os.path
import sys
import time
from glob import glob
class FakeDatetime(datetime.datetime):
@classmethod
def utcnow(cls):
return cls(2015, 12, 14, 15, 42, 14)
FakeDatetime.__name__ = 'datetime.datetime'
def load_tests(loader, tests, pattern):
# Since tzset does not work under Windows, just give up.
if os.name == 'nt':
return unittest.TestSuite(tests)
# Force time zone to EST/EDT to make localtime tests work.
os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
time.tzset()
# The different floating-point formatting rules in 2.6 and prior
# ruin our doctests.
tests = []
datetime.datetime = FakeDatetime
if sys.version_info >= (3, 9):
tests.extend([
doctest.DocFileSuite('../doc/%s' % os.path.basename(path))
for path in glob(os.path.dirname(__file__) + '/../doc/*.rst')
if os.path.split(path)[-1] != 'index.rst'
# skips time-dependent doctest in index.rst
])
return unittest.TestSuite(tests)
|
brandon-rhodesREPO_NAMEpyephemPATH_START.@pyephem_extracted@pyephem-master@ephem@tests@test_rst.py@.PATH_END.py
|
{
"filename": "datafunc.py",
"repo_name": "scipy/scipy",
"repo_path": "scipy_extracted/scipy-main/scipy/special/utils/datafunc.py",
"type": "Python"
}
|
import csv
import numpy as np
def parse_txt_data(filename):
f = open(filename)
try:
reader = csv.reader(f, delimiter=',')
data = [list(map(float, row)) for row in reader]
nc = len(data[0])
for i in data:
if not nc == len(i):
raise ValueError(i)
## guess number of columns/rows
#row0 = f.readline()
#nc = len(row0.split(',')) - 1
#nlines = len(f.readlines()) + 1
#f.seek(0)
#data = np.fromfile(f, sep=',')
#if not data.size == nc * nlines:
# raise ValueError("Inconsistency between array (%d items) and "
# "guessed data size %dx%d" % (data.size, nlines, nc))
#data = data.reshape((nlines, nc))
#return data
finally:
f.close()
return np.array(data)
def run_test(filename, funcs, args=[0]): # noqa: B006
nargs = len(args)
if len(funcs) > 1 and nargs > 1:
raise ValueError("nargs > 1 and len(funcs) > 1 not supported")
data = parse_txt_data(filename)
if data.shape[1] != len(funcs) + nargs:
raise ValueError("data has %d items / row, but len(funcs) = %d and "
"nargs = %d" % (data.shape[1], len(funcs), nargs))
if nargs > 1:
f = funcs[0]
x = [data[args[i]] for i in nargs]
return f(*x)
else:
y = [f(data[:, 0]) - data[:, idx + 1] for idx, f in enumerate(funcs)]
return data[:, 0], y
if __name__ == '__main__':
from convert import DATA_DIR
import os
data = []
for root, dirs, files in os.walk(DATA_DIR):
for f in files:
name = os.path.join(root, f)
print(name)
data.append(parse_txt_data(name))
|
scipyREPO_NAMEscipyPATH_START.@scipy_extracted@scipy-main@scipy@special@utils@datafunc.py@.PATH_END.py
|
{
"filename": "utils.py",
"repo_name": "plotly/plotly.py",
"repo_path": "plotly.py_extracted/plotly.py-master/packages/python/chart-studio/chart_studio/tests/utils.py",
"type": "Python"
}
|
import copy
from unittest import TestCase
from chart_studio import session, files, utils
from plotly.files import ensure_writable_plotly_dir
class PlotlyTestCase(TestCase):
# parent test case to assist with clean up of local credentials/config
def __init__(self, *args, **kwargs):
self._credentials = None
self._config = None
self._graph_reference = None
self._session = None
super(PlotlyTestCase, self).__init__(*args, **kwargs)
@classmethod
def setUpClass(cls):
session._session = {"credentials": {}, "config": {}, "plot_options": {}}
def setUp(self):
self.stash_session()
self.stash_files()
defaults = dict(
files.FILE_CONTENT[files.CREDENTIALS_FILE],
**files.FILE_CONTENT[files.CONFIG_FILE],
)
session.sign_in(**defaults)
def tearDown(self):
self.restore_files()
self.restore_session()
def stash_files(self):
self._credentials = utils.load_json_dict(files.CREDENTIALS_FILE)
self._config = utils.load_json_dict(files.CONFIG_FILE)
def restore_files(self):
if self._credentials and ensure_writable_plotly_dir():
utils.save_json_dict(files.CREDENTIALS_FILE, self._credentials)
if self._config and ensure_writable_plotly_dir():
utils.save_json_dict(files.CONFIG_FILE, self._config)
def stash_session(self):
self._session = copy.deepcopy(session._session)
def restore_session(self):
session._session.clear() # clear and update to preserve references.
session._session.update(self._session)
|
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@chart-studio@chart_studio@tests@utils.py@.PATH_END.py
|
{
"filename": "make_stub.py",
"repo_name": "tensorflow/tensorflow",
"repo_path": "tensorflow_extracted/tensorflow-master/third_party/xla/third_party/tsl/third_party/implib_so/make_stub.py",
"type": "Python"
}
|
"""Given a list of symbols, generates a stub."""
import argparse
import configparser
import os
import string
from bazel_tools.tools.python.runfiles import runfiles
r = runfiles.Create()
def main():
parser = argparse.ArgumentParser(
description='Generates stubs for CUDA libraries.'
)
parser.add_argument('symbols', help='File containing a list of symbols.')
parser.add_argument(
'--outdir', '-o', help='Path to create wrapper at', default='.'
)
parser.add_argument(
'--target',
help='Target platform name, e.g. x86_64, aarch64.',
required=True,
)
args = parser.parse_args()
config_path = r.Rlocation(f'implib_so/arch/{args.target}/config.ini')
table_path = r.Rlocation(f'implib_so/arch/{args.target}/table.S.tpl')
trampoline_path = r.Rlocation(
f'implib_so/arch/{args.target}/trampoline.S.tpl'
)
cfg = configparser.ConfigParser(inline_comment_prefixes=';')
cfg.read(config_path)
ptr_size = int(cfg['Arch']['PointerSize'])
with open(args.symbols, 'r') as f:
funs = [s.strip() for s in f.readlines()]
# Generate assembly code, containing a table for the resolved symbols and the
# trampolines.
lib_name, _ = os.path.splitext(os.path.basename(args.symbols))
with open(os.path.join(args.outdir, f'{lib_name}.tramp.S'), 'w') as f:
with open(table_path, 'r') as t:
table_text = string.Template(t.read()).substitute(
lib_suffix=lib_name, table_size=ptr_size * (len(funs) + 1)
)
f.write(table_text)
with open(trampoline_path, 'r') as t:
tramp_tpl = string.Template(t.read())
for i, name in enumerate(funs):
tramp_text = tramp_tpl.substitute(
lib_suffix=lib_name, sym=name, offset=i * ptr_size, number=i
)
f.write(tramp_text)
# Generates a list of symbols, formatted as a list of C++ strings.
with open(os.path.join(args.outdir, f'{lib_name}.inc'), 'w') as f:
sym_names = ''.join(f' "{name}",\n' for name in funs)
f.write(sym_names)
if __name__ == '__main__':
main()
|
tensorflowREPO_NAMEtensorflowPATH_START.@tensorflow_extracted@tensorflow-master@third_party@xla@third_party@tsl@third_party@implib_so@make_stub.py@.PATH_END.py
|
{
"filename": "test_astro_ui_fluxes.py",
"repo_name": "sherpa/sherpa",
"repo_path": "sherpa_extracted/sherpa-main/sherpa/astro/ui/tests/test_astro_ui_fluxes.py",
"type": "Python"
}
|
#
# Copyright (C) 2020, 2021, 2022, 2023
# Smithsonian Astrophysical Observatory
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Flux-related tests of the sherpa.astro.ui module.
"""
import logging
import numpy as np
import pytest
from sherpa.astro import ui
from sherpa.utils.logging import SherpaVerbosity
from sherpa.utils.testing import requires_data, requires_fits, \
requires_group, requires_xspec
from sherpa.utils.err import ArgumentErr, ArgumentTypeErr, FitErr, \
IdentifierErr, IOErr, ModelErr
import sherpa.astro.utils
from sherpa.astro import hc, charge_e
def fail(*arg):
return pytest.param(*arg, marks=pytest.mark.xfail)
# TODO: use wavelength and channels analysis
@pytest.mark.parametrize("id", [None, 1, "foo"])
@pytest.mark.parametrize("func", [ui.calc_photon_flux, ui.calc_energy_flux])
def test_calc_flux_pha_invalid_range(id, func, clean_astro_ui):
"""Ensure an error is raised if lo > hi"""
x = np.arange(3, 6)
y = np.ones(x.size - 1)
ui.load_arrays(id, x[:-1], x[1:], y, ui.Data1DInt)
mdl = ui.create_model_component('const1d', 'm')
if id is None:
ui.set_source(mdl)
else:
ui.set_source(id, mdl)
# Note: really the error message should not include energy since in
# this case (Data1DInt) there's no energy, and if this were
# a DataPHA case the message says energy even if analysis=wave
# or channel.
#
emsg = 'the energy range is not consistent, 12 !< 5'
with pytest.raises(IOErr, match=emsg):
if id is None:
func(12, 5)
else:
func(12, 5, id=id)
@requires_data
@requires_fits
@pytest.mark.parametrize("func", [ui.calc_photon_flux, ui.calc_energy_flux])
def test_calc_flux_pha_invalid_model(func, make_data_path, clean_astro_ui):
"""Don't allow strings for model parameter"""
infile = make_data_path('3c273.pi')
ui.load_pha(infile)
ui.set_source('powerlaw.pl')
emsg = "'model' must be a model object"
with pytest.raises(ArgumentTypeErr, match=emsg):
func(0.5, 7, model='pl')
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.calc_energy_flux,
ui.calc_photon_flux])
def test_calc_foo_flux_no_bkg(method, make_data_path, clean_astro_ui):
"""No background model.
"""
setup_sample(1, make_data_path, fit=False)
with pytest.raises(ModelErr) as exc:
method(lo=0.5, hi=7, bkg_id=1)
assert str(exc.value) == 'background model 1 for data set 1 has not been set'
def test_calc_flux_pha_bin_edges(clean_astro_ui):
"""What happens when filter edges partially overlap bins?
Later tests may also cover this condition, but here we use
faked data that is made to make the behavior "obvious".
"""
chans = np.arange(1, 11, 1, dtype=int)
counts = np.zeros(chans.size, dtype=int)
# "perfect" response
energies = np.arange(1, 12, 1)
elo, ehi = energies[:-1], energies[1:]
flat = np.ones(chans.size, dtype=int)
d = ui.DataPHA('example', chans, counts)
arf = ui.create_arf(elo, ehi, flat)
rmf = ui.create_rmf(elo, ehi, e_min=elo, e_max=elo, startchan=1,
fname=None)
d.set_arf(arf)
d.set_rmf(rmf)
ui.set_data(1, d)
ui.set_source(ui.powlaw1d.pl)
pl.ampl = 1e-4
pl.gamma = 1.7
# Evaluate the model on the energy grid
ymdl = pl(elo, ehi)
pflux = ui.calc_photon_flux(2.6, 7.8)
eflux = ui.calc_energy_flux(2.6, 7.8)
# Left in as notes:
#
# This are the true values. Given that the edge bins (should be)
# using linear interpolation, how close do we get to this?
#
# gterm1 = 1.0 - 1.7
# gterm2 = 2.0 - 1.7
# true_pflux = 1e-4 * (7.8**gterm1 - 2.6**gterm1) / gterm1
# true_eflux = enscale * 1e-4 * (7.8**gterm2 - 2.6**gterm2) / gterm2
#
# Comparing the linear interpolation scheme to that used by
# Sherpa prior to fixing #619, I find
#
# Photon fluxes:
# linear_interp / true_pflux = 1.042251
# sherpa / true_pflux = 0.837522
#
# Energy fluxes:
# linear_interp / true_eflux = 1.017872
# sherpa / true_eflux = 0.920759
#
scale = np.asarray([0.0, 0.4, 1.0, 1.0, 1.0, 1.0, 0.8, 0, 0.0, 0.0])
expected_pflux = (ymdl * scale).sum()
emid = charge_e * (elo + ehi) / 2
expected_eflux = (emid * ymdl * scale).sum()
assert pflux == pytest.approx(expected_pflux)
# check against log as values ~ 3e-13
eflux = np.log10(eflux)
expected_eflux = np.log10(expected_eflux)
assert eflux == pytest.approx(expected_eflux)
def test_calc_flux_pha_density_bin_edges(clean_astro_ui):
"""What happens when filter edges partially overlap bins? flux density
Later tests may also cover this condition, but here we use
faked data that is made to make the behavior "obvious".
"""
chans = np.arange(1, 11, 1, dtype=int)
counts = np.zeros(chans.size, dtype=int)
# "perfect" response
energies = np.arange(1, 12, 1)
elo, ehi = energies[:-1], energies[1:]
flat = np.ones(chans.size, dtype=int)
d = ui.DataPHA('example', chans, counts)
arf = ui.create_arf(elo, ehi, flat)
rmf = ui.create_rmf(elo, ehi, e_min=elo, e_max=elo, startchan=1,
fname=None)
d.set_arf(arf)
d.set_rmf(rmf)
ui.set_data(1, d)
ui.set_source(ui.powlaw1d.pl)
pl.ampl = 1e-4
pl.gamma = 1.7
# choose an energy that is not equal to the center of the bin
# just to check how this is handled
#
pdens = ui.calc_photon_flux(2.6)
edens = ui.calc_energy_flux(2.6)
# Evaluate the model over the bin 2-3 keV; since the grid
# has a width of 1 keV we do not need to divide by the bin
# width when calculating the density.
#
ymdl = pl([2], [3])
expected_pdens = ymdl.sum()
expected_edens = charge_e * 2.5 * expected_pdens
# Prior to fixing #619, Sherpa returns 0 for both densities
#
assert pdens == pytest.approx(expected_pdens)
# check against log as values ~ 5e-13
edens = np.log10(edens)
expected_edens = np.log10(expected_edens)
assert edens == pytest.approx(expected_edens)
@requires_data
@requires_fits
@pytest.mark.parametrize("id", [None, 1, "foo"])
@pytest.mark.parametrize("lo, hi", [(None, None),
(0.1, 11),
(0.1, 7),
(0.5, 11),
(0.5, 7),
(0.05, 7),
(0.5, 15),
(0.05, 15),
(0.01, 0.05),
(12, 14)])
def test_calc_flux_pha(id, lo, hi, make_data_path, clean_astro_ui):
"""Do calc_photon/energy_flux return the expected results: fluxes?
This skips those combinations where only one of lo or hi
is None, since this is handle by test_calc_flux_density_pha.
Flues are in units of <value>/cm^2/s {value=photon, erg}
The checks are made against ranges that are chosen to cover
matching the grid, a subset of the grid (with and without
matching the start/end), partial overlaps, and no overlap.
"""
infile = make_data_path('3c273.pi')
# The 3c273 RMF was generated over the range 0.1 to 11 keV
# (inclusive). By picking gamma = 1 the photon-flux
# integral is just ampl * (log(ehi) - log(elo))
# and the energy-flux ampl is ampl * (ehi - elo) * scale
# where scale converts 1 keV to erg.
#
ampl = 1e-4
if lo is None:
loval = 0.1
elif lo < 0.1:
loval = 0.1
else:
loval = lo
if hi is None:
hival = 11.0
elif hi > 11.0:
hival = 11.0
else:
hival = hi
# expected fluxes; special case the handling of there being no
# overlap between the user grid and the data grid.
#
if lo is not None and (lo > 11.0 or hi < 0.1):
pflux_exp = 0.0
eflux_exp = 0.0
else:
pflux_exp = ampl * (np.log(hival) - np.log(loval))
eflux_exp = 1.602e-9 * ampl * (hival - loval)
pl = ui.create_model_component('powlaw1d', 'pl')
pl.ampl = ampl
pl.gamma = 1
if id is None:
ui.load_pha(infile)
ui.set_source(pl)
else:
ui.load_pha(id, infile)
ui.set_source(id, pl)
# Use a subset of the data range (to check that the calc routines
# ignores them, ie uses the full 0.1 to 11 keV range.
#
ui.ignore(None, 0.5)
ui.ignore(7, None)
# Do not use named arguments, but assume positional arguments
if id is None:
pflux = ui.calc_photon_flux(lo, hi)
eflux = ui.calc_energy_flux(lo, hi)
else:
pflux = ui.calc_photon_flux(lo, hi, id)
eflux = ui.calc_energy_flux(lo, hi, id)
# Since the energy fluxes are ~1e-12 we want to rescale the
# value before comparison. Here we use a log transform.
#
eflux_exp = np.log10(eflux_exp)
eflux = np.log10(eflux)
assert pflux == pytest.approx(pflux_exp, rel=1e-3)
assert eflux == pytest.approx(eflux_exp, rel=1e-4)
# The lo/hi range which match in the different settings; using hc
# to convert from keV to Angstroms is a bit low-level.
#
# The energy-to-channel conversion was done by filtering in energy
# space and asking Sherpa what channels this selected.
#
@requires_data
@requires_fits
@pytest.mark.parametrize("elo, ehi, setting, lo, hi",
[(None, None, 'wave', None, None),
(None, None, 'channel', None, None),
(0.5, 7.0, 'wave',
hc / 7.0, hc / 0.5),
fail(0.5, 7.0, 'channel', 35, 480) # issue 619 see also 308
])
def test_calc_flux_pha_analysis(elo, ehi, setting, lo, hi, make_data_path, clean_astro_ui):
"""Do calc_photon/energy_flux return the expected results: fluxes + analysis setting
Basic test for different analysis settings: the
same range (modulo precision of conversion) gives the
same results.
"""
infile = make_data_path('3c273.pi')
pl = ui.create_model_component('powlaw1d', 'pl')
ui.load_pha(infile)
ui.set_source(pl)
pflux = ui.calc_photon_flux(elo, ehi)
eflux = ui.calc_energy_flux(elo, ehi)
ui.set_analysis(setting)
pflux2 = ui.calc_photon_flux(lo, hi)
eflux2 = ui.calc_energy_flux(lo, hi)
# use approx here since the bin edges are not guaranteed
# to line up, and use a large tolerance.
#
assert pflux2 == pytest.approx(pflux, rel=1e-2)
eflux = np.log10(eflux)
eflux2 = np.log10(eflux2)
assert eflux2 == pytest.approx(eflux, rel=1e-3)
@requires_data
@requires_fits
@pytest.mark.parametrize("id", [None, 1, "foo"])
@pytest.mark.parametrize("energy", [0.05,
0.1,
0.109,
0.11,
1,
1.015,
5,
10.99,
10.991,
11,
15])
def test_calc_flux_density_pha(id, energy, make_data_path, clean_astro_ui):
"""Do calc_photon/energy_flux return the expected results: densities
The answer should be the same when lo is set and hi
is None or vice versa. The flux densities are going to
be in units of <value>/cm^2/s/keV {value=photon, erg}
Note: this tests the "edge" condition when lo=hi; this
is not documented, but left in as a check (and perhaps
it should be documented).
"""
infile = make_data_path('3c273.pi')
# The 3c273 RMF was generated over the range 0.1 to 11 keV
# (inclusive). By picking gamma = 1 the photon flux
# density is ampl / e and the energy flux is scale * ampl.
# However, this is the exact calculation, but the one done by
# Sherpa involves calculating the model over a bin and then
# dividing by that bin width, which is different enough to
# the analytic formula that we use this approach here when
# calculating the expected values. The bin width is 0.01 keV,
# with bins starting at 0.1.
#
ampl = 1e-4
# flux densities: exact
# pflux_exp = ampl / energy
# eflux_exp = 1.602e-9 * ampl
# Note that you can calculate an answer at the left edge of the grid, but
# not at the right (this is either a < vs <= comparison, or numeric
# issues with the maximum grid value).
#
# Note that the RMF emin is just above 0.1 keV, ie
# 0.10000000149011612, which is why an energy of 0.1 gives
# an answer of 0. Now, sao_fcmp(0.1, 0.10000000149011612, sherpa.utils.eps)
# returns 0, so we could consider these two values equal, but
# that would complicate the flux calculation so is (currently) not
# done.
#
de = 0.01
if energy <= 0.1 or energy >= 11:
pflux_exp = 0.0
eflux_exp = 0.0
else:
# assuming a bin centered on the energy; the actual grid
# is not this, but this should be close
hwidth = de / 2
pflux_exp = ampl * (np.log(energy + hwidth) - np.log(energy - hwidth)) / de
eflux_exp = 1.602e-9 * energy * pflux_exp
pl = ui.create_model_component('powlaw1d', 'pl')
pl.ampl = ampl
pl.gamma = 1
if id is None:
ui.load_pha(infile)
ui.set_source(pl)
else:
ui.load_pha(id, infile)
ui.set_source(id, pl)
# Use a subset of the data range (to check that the calc routines
# ignores them, ie uses the full 0.1 to 11 keV range.
#
ui.ignore(None, 0.5)
ui.ignore(7, None)
# Do not use named arguments, but assume positional arguments
if id is None:
pflux1 = ui.calc_photon_flux(energy)
pflux2 = ui.calc_photon_flux(None, energy)
pflux3 = ui.calc_photon_flux(energy, energy)
eflux1 = ui.calc_energy_flux(energy)
eflux2 = ui.calc_energy_flux(None, energy)
eflux3 = ui.calc_energy_flux(energy, energy)
else:
pflux1 = ui.calc_photon_flux(energy, None, id)
pflux2 = ui.calc_photon_flux(None, energy, id)
pflux3 = ui.calc_photon_flux(energy, energy, id)
eflux1 = ui.calc_energy_flux(energy, None, id)
eflux2 = ui.calc_energy_flux(None, energy, id)
eflux3 = ui.calc_energy_flux(energy, energy, id)
eflux1 = np.log10(eflux1)
eflux2 = np.log10(eflux2)
eflux3 = np.log10(eflux3)
# Use equality here since the numbers should be the same
assert pflux1 == pflux2
assert pflux1 == pflux3
assert eflux1 == eflux2
assert eflux1 == eflux3
# Note the "large" tolerance here
eflux_exp = np.log10(eflux_exp)
assert pflux1 == pytest.approx(pflux_exp, rel=5e-2)
assert eflux1 == pytest.approx(eflux_exp, rel=1e-3)
@requires_data
@requires_fits
def test_calc_flux_pha_unabsorbed(make_data_path, clean_astro_ui):
"""Can we calculate an unabsorbed flux?"""
# The idea is that with a model expression of
# const1d.scale * powlaw1d.pl
# when scale is not 1 (and not integrated) then we can
# just look to see if the "absorbed" flux is scale * the
# "unabsorbed" flux.
#
infile = make_data_path('3c273.pi')
ui.load_pha(infile)
scale = ui.create_model_component('const1d', 'scale')
pl = ui.create_model_component('powlaw1d', 'pl')
scale.c0 = 0.8
scale.integrate = False
pl.gamma = 1.5
pl.ampl = 1e-4
ui.set_source(scale * pl)
pflux_abs = ui.calc_photon_flux(0.5, 7)
pflux_unabs = ui.calc_photon_flux(0.5, 7, model=pl)
eflux_abs = ui.calc_energy_flux(0.5, 7)
eflux_unabs = ui.calc_energy_flux(0.5, 7, model=pl)
pflux_scale = pflux_abs / pflux_unabs
eflux_scale = eflux_abs / eflux_unabs
assert pflux_scale == pytest.approx(0.8)
assert eflux_scale == pytest.approx(0.8)
@requires_data
@requires_fits
@pytest.mark.parametrize("method,sflux,bflux",
[(ui.calc_energy_flux, 8.296745792997814e-13, 1.342566520894761e-13),
(ui.calc_photon_flux, 0.00034801650283229483, 2.9675854718842685e-05)])
def test_calc_flux_bkg(method, sflux, bflux, make_data_path, clean_astro_ui):
"""Basic test of a background dataset.
This does not test all combinations, as it is expected that
they can be checked with existing tests.
"""
infile = make_data_path('3c273.pi')
ui.load_pha(infile)
# ignore low-energy so do not need XSPEC
ui.ungroup()
ui.notice(0.8, 7)
ui.set_stat('cstat')
spl = ui.create_model_component('powlaw1d', 'spl')
bpl = ui.create_model_component('powlaw1d', 'bpl')
spl.gamma = 1.91
spl.ampl = 1.85e-4
bpl.gamma = 0.73
bpl.ampl = 9.27e-6
ui.set_source(spl)
ui.set_bkg_source(bpl)
ui.fit()
# just to check the fit hasn't significantly moved
check = ui.calc_stat()
assert check == pytest.approx(775.6453986960231)
# These should be the same, by construction
sflux_all = method(0.5, 7)
sflux_spl = method(0.5, 7, model=spl)
assert sflux_all == sflux_spl # do not use pytest.approx
bflux_all = method(0.5, 7, bkg_id=1)
bflux_bpl = method(0.5, 7, bkg_id=1, model=bpl)
assert bflux_all == bflux_bpl # do not use pytest.approx
# check expected flux (regression test).
#
got = np.log10(sflux_spl)
exp = np.log10(sflux)
assert got == pytest.approx(exp)
got = np.log10(bflux_bpl)
exp = np.log10(bflux)
assert got == pytest.approx(exp)
def setup_sample(id, make_data_path, fit=True):
"""Set up the given dataset for a sample*flux call
The calling function needs @requires_data, @requires_fits, @requires_xspec
decorators.
"""
infile = make_data_path('3c273.pi')
if id is None:
ui.load_pha(infile)
ui.subtract()
else:
ui.load_pha(id, infile)
ui.subtract(id)
ui.notice(0.5, 7)
ui.set_stat('chi2datavar')
ui.set_method('levmar')
# get the starting point close to the best fit
#
# Use xswabs rather than xsphabs as it's faster and
# we don't care here about scientific validity of the
# results.
#
# gal = ui.create_model_component('xsphabs', 'gal')
gal = ui.create_model_component('xswabs', 'gal')
pl = ui.create_model_component('powlaw1d', 'pl')
mdl = gal * pl
gal.nh = 0.0393
pl.gamma = 2.027
pl.ampl = 1.96e-4
if id is None:
ui.set_source(mdl)
if fit:
ui.fit()
else:
ui.set_source(id, mdl)
if fit:
ui.fit(id)
return gal, pl
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.sample_energy_flux,
ui.sample_photon_flux])
@pytest.mark.parametrize("niter", [0, -1])
@pytest.mark.parametrize("id", [None, 1, "foo"])
def test_sample_foo_flux_invalid_niter(method, niter, id,
make_data_path, clean_astro_ui):
"""What happens for sample_energy/photon_flux when num is <= 0
See also test_sample_flux_invalid_niter
"""
setup_sample(id, make_data_path, fit=False)
with pytest.raises(ArgumentErr):
method(lo=0.5, hi=7, id=id, num=niter)
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.sample_energy_flux,
ui.sample_photon_flux])
@pytest.mark.parametrize("etype,correlated,scales", [(ModelErr, False, []),
(ArgumentErr, False, [[]]),
(ModelErr, False, [1, 2]),
(ModelErr, False, [1, 2, 3, 4]),
(ModelErr, False, [[1, 2], [3, 4]]),
(ArgumentErr, False, [[1, 2, 3], [3, 4, 5]]),
(ModelErr, False, np.asarray([])),
(ArgumentErr, False, np.asarray([[]])),
(ModelErr, False, np.asarray([1, 2])),
(ModelErr, False, np.asarray([1, 2, 3, 4])),
(ModelErr, False, np.asarray([[1, 2], [3, 4]])),
(ArgumentErr, False, np.asarray([[1, 2, 3], [3, 4, 5]])),
(ArgumentErr, True, []),
(ArgumentErr, True, [[]]),
(ArgumentErr, True, np.asarray([])),
(ArgumentErr, True, np.asarray([[]])),
(ArgumentErr, True, [1, 2, 3]),
(ArgumentErr, True, [[1, 2, 3], [1, 2, 3]]),
(ArgumentErr, True, np.asarray([1, 2, 3])),
(ModelErr, True, np.ones((2, 2))),
(ArgumentErr, True, np.ones((3, 3, 3))),
(ArgumentErr, False, [1, np.inf, 2]),
(ArgumentErr, False, [1, 2, None]),
(ArgumentErr, True, [[0.1, 0.01, 0.02], [0.01, np.nan, 0.05], [0.02, 0.01, 0.08]]),
(ArgumentErr, False, np.ones(3).reshape(1, 3, 1)),
(ArgumentErr, True, np.ones(9).reshape(1, 3, 3))])
def test_sample_foo_flux_invalid_scales(method, etype, correlated, scales,
make_data_path, clean_astro_ui):
"""What happens for sample_energy/photon_flux when scales is
the wrong shape, or contains invalid values
The scales parameter should be (for this fit with 3 free parameters):
correlated=True 3 by 3 covariance matrix
False 3 by 3 covariance matrix or 3-element errors vector
Since these checks are done at a low level, we do not have to
loop over every element (e.g. method, id setting) as done in some
other checks.
"""
setup_sample('x', make_data_path, fit=False)
with pytest.raises(etype):
method(lo=0.5, hi=7, id='x', num=10,
correlated=correlated, scales=scales)
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.sample_energy_flux,
ui.sample_photon_flux])
@pytest.mark.parametrize("correlated,scales", [(False, [0.1]),
(False, np.ones((4, 4)).diagonal()),
(False, np.ones((4, 4))),
(True, np.ones((1, 1))),
(True, np.ones((4, 4)))])
def test_sample_foo_flux_invalid_scales2(method, correlated, scales,
make_data_path, clean_astro_ui):
"""A repeat of test_sample_foo_flux_invalid_scales for explicit model components.
Unlike test_sample_foo_flux_invalid_scales, do not repeat as
many times. In this case we are testing that the grid is
either 3 by 3 or 2 by 2, and not checking for "invalid"
values in the inputs.
"""
cpts = setup_sample(1, make_data_path, fit=False)
# Test correlated=False with 1D and 2D
# = True 2D
#
# The full model has 3 free parameters and cpts[1]
# has 2 free parameters, so try 1 and 4 parameters.
#
with pytest.raises(ModelErr):
method(lo=0.5, hi=7, id=1, num=10, model=cpts[1],
correlated=correlated, scales=scales)
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.sample_energy_flux,
ui.sample_photon_flux])
def test_sample_foo_flux_no_free_params(method, make_data_path,
hide_logging, clean_astro_ui):
"""sample_energy/photon_flux when no free parameters.
"""
cpts = setup_sample(1, make_data_path, fit=False)
for cpt in cpts:
ui.freeze(cpt)
with pytest.raises(FitErr) as exc:
method(lo=0.5, hi=7, num=1)
assert str(exc.value) == 'model has no thawed parameters'
# try with explicit model setting
#
with pytest.raises(FitErr) as exc:
method(lo=0.5, hi=7, num=1, model=cpts[1])
assert str(exc.value) == 'model has no thawed parameters'
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.sample_energy_flux,
ui.sample_photon_flux])
def test_sample_foo_flux_not_a_model(method, make_data_path, clean_astro_ui):
"""sample_energy/photon_flux when src model is not a model.
This is currently not well handled (you get an error but
it's not a "nice" error).
"""
setup_sample(1, make_data_path, fit=False)
with pytest.raises(AttributeError) as exc:
method(lo=0.5, hi=7, num=1, model='x')
assert str(exc.value) == "'str' object has no attribute 'thawedpars'"
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.sample_energy_flux,
ui.sample_photon_flux])
def test_sample_foo_flux_invalid_model(method, make_data_path,
hide_logging, clean_astro_ui):
"""sample_energy/photon_flux when src model is not part of the fit.
"""
setup_sample(1, make_data_path, fit=False)
mdl = ui.create_model_component('powlaw1d', 'p1')
with pytest.raises(ArgumentErr) as exc:
method(lo=0.5, hi=7, num=1, model=mdl)
assert str(exc.value) == "Invalid src: 'model contains term not in fit'"
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("multi,single", [(ui.sample_energy_flux,
ui.calc_energy_flux),
(ui.sample_photon_flux,
ui.calc_photon_flux)])
@pytest.mark.parametrize("id", [None, 1, "foo"])
@pytest.mark.parametrize("niter", [1, 2, 10])
@pytest.mark.parametrize("correlated", [False, True])
def test_sample_foo_flux_niter(multi, single, id, niter, correlated,
make_data_path, clean_astro_ui):
"""Do the sample_energy/photon_flux do what we expect?
Iterate n times, check that each iteration is different
(at least, doesn't match the previous version), and that
the returned flux is as expected.
"""
gal, pl = setup_sample(id, make_data_path)
nh0 = gal.nh.val
gamma0 = pl.gamma.val
ampl0 = pl.ampl.val
ans = multi(lo=0.5, hi=7, id=id, num=niter, correlated=correlated)
assert ans.shape == (niter, 5)
# the routine hasn't changed the parameter values
assert gal.nh.val == nh0
assert pl.gamma.val == gamma0
assert pl.ampl.val == ampl0
# we expect that at least one of the parameter variables
# is different (technically the random sampler could pick
# the exact positions we started with, but this is unlikely)
# pytest.approx is used in case there is any loss in
# precision in storing the parameter values in the returned
# NumPy array.
#
# Since we loop over iterations the first line checks against
# the best fit, and then we check that the next iteration is
# different from the previous iteration.
#
for i in range(niter):
diffs = [ans[i, j] != pytest.approx(p.val)
for j, p in enumerate([gal.nh, pl.gamma, pl.ampl], 1)]
assert any(diffs)
# Can we re-create this flux?
gal.nh = ans[i, 1]
pl.gamma = ans[i, 2]
pl.ampl = ans[i, 3]
flux = single(lo=0.5, hi=7, id=id)
assert ans[i, 0] == flux
# check clipped is 0/1; ideally this is a boolean and not a
# float representation
#
clipped = ans[:, 4]
v0 = clipped == 0
v1 = clipped == 1
v = v0 | v1
assert v.all()
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("multi", [ui.sample_energy_flux,
ui.sample_photon_flux])
@pytest.mark.parametrize("correlated,lnh0,gamma0,lampl0,slnh0,sgamma0,slampl0",
[(False,
-1.4327586455259567, 2.023901305737941, -3.708831467739439,
-1.5187931648736508, 0.10547355541516636, -4.643460099308331),
(True, -1.412181958091415, 2.0328696702831586, -3.7063310517413326,
-1.4914185211470155, 0.10389408045222855, -4.637303782755868)])
def test_sample_foo_flux_params(multi, correlated, lnh0, gamma0, lampl0,
slnh0, sgamma0, slampl0,
make_data_path, clean_astro_ui,
hide_logging):
"""Is the parameter sampling in sample_energy/photon_flux sensible?
Do the parameter values used in the sampling make sense?
It is not obvious why we need a relatively high tolerance
(~1e-3) to test the numbers, given the seed is fixed.
"""
ui.set_rng(np.random.RandomState(4276))
# Rather than loop over ids, like earlier tests, just pick a non-default
# one.
#
id = 2
gal, pl = setup_sample(id, make_data_path)
ui.covar(id)
errs = ui.get_covar_results()
# The parameter sampling uses the hard-limit boundaries,
# not the soft-limit boundaries. This can be seen by
# artificially constricting the soft limits of the
# gamma parameter. With the default limits, gamma is 2.03 +/- 0.11,
# so 3-sigma limits are ~ 1.70 to 2.36. In 1000 iterations
# we would expect ~ 3 bins to fall outside this range.
# A 2-sigma limit range is 1.81 - 2.25, and we'd expect
# ~ 45 bins in 1000 to fall outside this range.
#
pl.gamma.min = 1.81
pl.gamma.max = 2.25
ans = multi(lo=0.5, hi=7, id=id, num=1000, correlated=correlated)
# do not expect any IEEE special values here
assert np.isfinite(ans).all()
nh = ans[:, 1]
gamma = ans[:, 2]
ampl = ans[:, 3]
# Checks we can run?
#
# - mean/median should be close to best-fit
# - sigma should be close to error
# (at least for correlated=False)
# - min/max should be restricted to parameter limits
# (this check is currently not enforced as the sampler
# does not enforce this).
#
# The checks use relatively-large tolerances, as there is
# no reason the values will match closely
#
# The nH value, as it bumps against the lower bound of 0, has
# been seen to require a larger tolerance than the other parameters.
#
assert np.log10(np.median(nh)) == pytest.approx(lnh0, rel=1e-3)
assert np.median(gamma) == pytest.approx(gamma0, rel=1e-3)
assert np.log10(np.median(ampl)) == pytest.approx(lampl0, rel=1e-3)
assert np.log10(np.std(nh)) == pytest.approx(slnh0, rel=1e-3)
assert np.std(gamma) == pytest.approx(sgamma0, rel=1e-3)
assert np.log10(np.std(ampl)) == pytest.approx(slampl0, rel=1e-3)
# Check against the hard limits, although this is not particularly
# informative since the hard limits for these parameters are
# all +/- 3.4e38
#
assert nh.min() >= gal.nh.hard_min
assert nh.max() <= gal.nh.hard_max
assert gamma.min() >= pl.gamma.hard_min
assert gamma.max() <= pl.gamma.hard_max
assert ampl.min() >= pl.ampl.hard_min
assert ampl.max() <= pl.ampl.hard_max
# A probabilistic check that the gamma range lies outside
# the soft limits. It is possible for this check to fail
# because of the RNG, but with ~45 expected values outside
# the limits this is unlikely. Now we have a set seed we can
# check both are triggered.
#
gmin = gamma.min() < pl.gamma.min
gmax = gamma.max() > pl.gamma.max
assert gmin
assert gmax
# a simple check on the flux, it should be > 0
#
assert ans[:, 0].min() > 0
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("multi", [ui.sample_energy_flux, ui.sample_photon_flux])
@pytest.mark.parametrize("id", [None, "foo"])
def test_sample_foo_flux_clip_soft(multi, id,
make_data_path, clean_astro_ui):
"""Can we clip with soft limits?
"""
gal, pl = setup_sample(id, make_data_path)
nh0 = gal.nh.val
gamma0 = pl.gamma.val
ampl0 = pl.ampl.val
niter = 100
# make this even more obvious than test_sample_foo_flux_params
pl.gamma.min = 1.9
pl.gamma.max = 2.1
ans = multi(lo=0.5, hi=7, id=id, num=niter, clip='soft')
assert ans.shape == (niter, 5)
# check clipped is 0/1; expect just under 50% clipped but just check
# we have some clipped, not the number
#
clipped = ans[:, 4]
v0 = clipped == 0
v1 = clipped == 1
v = v0 | v1
assert v.all()
assert v0.any()
assert v1.any()
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("multi", [ui.sample_energy_flux, ui.sample_photon_flux])
@pytest.mark.parametrize("id", [None, "foo"])
def test_sample_foo_flux_clip_none(multi, id,
make_data_path, clean_astro_ui):
"""We get no clipping.
Same setup as test_sample_foo_flux_clip_soft
"""
gal, pl = setup_sample(id, make_data_path)
nh0 = gal.nh.val
gamma0 = pl.gamma.val
ampl0 = pl.ampl.val
niter = 100
# make this even more obvious than test_sample_foo_flux_params
pl.gamma.min = 1.9
pl.gamma.max = 2.1
ans = multi(lo=0.5, hi=7, id=id, num=niter, clip='none')
assert ans.shape == (niter, 5)
# check clipped is 0/1
#
clipped = ans[:, 4]
v0 = clipped == 0
v1 = clipped == 1
v = v0 | v1
assert v.all()
assert v0.all()
assert not(v1.any())
# The covariance matrix should be close to the following
# (found from running the code):
#
# 1.28e-3 3.09e-3 7.41e-7
# 3.09e-3 1.10e-2 2.19e-6
# 7.41e-7 2.19e-6 5.38e-10
#
COVMAT = np.asarray([[1.28e-3, 3.09e-3, 7.41e-7],
[3.09e-3, 1.10e-2, 2.19e-6],
[7.41e-7, 2.19e-6, 5.38e-10]])
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("multi", [ui.sample_energy_flux,
ui.sample_photon_flux])
@pytest.mark.parametrize("correlated,scales,lnh0,gamma0,lampl0,slnh0,sgamma0,slampl0",
[(False, COVMAT,
-1.3910107005746297, 2.02960216422235, -3.7055883565005048,
-1.5045463684643257, 0.10508987949127284, -4.63785707737552),
# since np.sqrt(COVMAT.diagonal()) should == COVMAT
# this is a bit pointess
(False, np.sqrt(COVMAT.diagonal()),
-1.3910107005746297, 2.02960216422235, -3.7055883565005048,
-1.5045463684643257, 0.10508987949127284, -4.63785707737552),
(True, COVMAT,
-1.4143474006245673, 2.0232833551455367, -3.707730785910153,
-1.5014997538936377, 0.10428938426161602, -4.6312159319100346)])
def test_sample_foo_flux_scales(multi, correlated, scales,
lnh0, gamma0, lampl0,
slnh0, sgamma0, slampl0,
make_data_path, clean_astro_ui,
hide_logging):
"""What happens when we specify the scale parameters?
Test out sending in the errors to the sample_*_flux routines.
The form depends on the correlated parameter (1D vs 2D).
The tests are based on those in test_sample_foo_flux_params
"""
ui.set_rng(np.random.RandomState(888))
id = 2
gal, pl = setup_sample(id, make_data_path)
pl.gamma.min = 1.81
pl.gamma.max = 2.25
ans = multi(lo=0.5, hi=7, id=id, num=1000,
correlated=correlated, scales=scales)
assert np.isfinite(ans).all()
nh = ans[:, 1]
gamma = ans[:, 2]
ampl = ans[:, 3]
assert np.log10(np.median(nh)) == pytest.approx(lnh0, rel=1e-3)
assert np.median(gamma) == pytest.approx(gamma0, rel=1e-3)
assert np.log10(np.median(ampl)) == pytest.approx(lampl0, rel=1e-3)
if scales.ndim == 2:
errs = np.sqrt(scales.diagonal())
else:
errs = scales
snh = np.std(nh)
sgamma = np.std(gamma)
sampl = np.std(ampl)
assert np.log10(snh) == pytest.approx(slnh0, rel=1e-3)
assert sgamma == pytest.approx(sgamma0, rel=1e-3)
assert np.log10(sampl) == pytest.approx(slampl0, rel=1e-3)
assert nh.min() >= gal.nh.hard_min
assert nh.max() <= gal.nh.hard_max
assert gamma.min() >= pl.gamma.hard_min
assert gamma.max() <= pl.gamma.hard_max
assert ampl.min() >= pl.ampl.hard_min
assert ampl.max() <= pl.ampl.hard_max
gmin = gamma.min() < pl.gamma.min
gmax = gamma.max() > pl.gamma.max
# assert gmin or gmax
assert gmin
assert gmax
assert ans[:, 0].min() > 0
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("multi", [ui.sample_energy_flux,
ui.sample_photon_flux])
def test_sample_foo_flux_scales_example(multi, make_data_path, clean_astro_ui,
hide_logging):
"""Ensure that one of the examples works as expected.
It is a simplified version of test_sample_foo_flux_scales
but parameter errors sent in from the parmaxes field
of the covariance output.
"""
ui.set_rng(np.random.RandomState(3975529))
id = None
gal, pl = setup_sample(id, make_data_path)
ui.covar()
scales = ui.get_covar_results().parmaxes
ans = multi(lo=0.5, hi=7, id=id, num=1000,
correlated=False, scales=scales)
assert np.isfinite(ans).all()
nh = ans[:, 1]
gamma = ans[:, 2]
ampl = ans[:, 3]
assert np.log10(np.median(nh)) == pytest.approx(-1.434730948849745, rel=1e-3)
assert np.median(gamma) == pytest.approx(2.032662859390957, rel=1e-3)
assert np.log10(np.median(ampl)) == pytest.approx(-3.707907209935886, rel=1e-3)
assert np.log10(np.std(nh)) == pytest.approx(-1.5118443869902682, rel=1e-3)
assert np.std(gamma) == pytest.approx(0.10622782336666241, rel=1e-3)
assert np.log10(np.std(ampl)) == pytest.approx(-4.620006818656268, rel=1e-3)
assert ans[:, 0].min() > 0
@requires_data
@requires_fits
def test_bug_276(make_data_path):
ui.load_pha(make_data_path('3c273.pi'))
ui.set_model('polynom1d.p1')
ui.fit()
ui.covar()
scal = ui.get_covar_results().parmaxes
ui.sample_flux(ui.get_model_component('p1'), 0.5, 1, num=5,
correlated=False, scales=scal)
@pytest.mark.xfail
@pytest.mark.parametrize("niter", [0, -1])
def test_sample_flux_invalid_niter(niter):
"""What happens when num is 0 or negative?
To simplify things, run with a non PHA dataset.
This unfortunately fails at this time due to (probably two)
different bugs, so the test isn't actually effective.
"""
xbins = np.arange(5, 10, 1)
y = np.asarray([10, 12, 11, 12])
ui.load_arrays(1, xbins[:-1], xbins[1:], y, ui.Data1DInt)
ui.set_source(1, ui.const1d.mdl)
ui.set_stat('cash')
ui.fit()
ui.covar()
with pytest.raises(ArgumentErr) as exc:
ui.sample_flux(lo=6, hi=8, Xrays=False, num=niter)
assert str(exc.value) == "Invalid num: 'must be a positive integer'"
@requires_data
@requires_fits
@pytest.mark.parametrize("niter", [pytest.param(0, marks=pytest.mark.xfail), -1])
def test_sample_flux_invalid_niter_pha(niter, make_data_path, clean_astro_ui):
"""What happens when num is 0 or negative? PHA dataset
Since test_sample_flux_invalid_niter (currently) fails,
also try with a PHA dataset.
Note that niter=0 fails because internally we add 1 to it
inside sample_flux before we check its value.
"""
ui.load_pha(make_data_path('3c273.pi'))
ui.set_model('polynom1d.p1')
ui.notice(1, 7)
ui.set_stat('cash')
ui.fit()
ui.covar()
with pytest.raises(ArgumentErr) as exc:
ui.sample_flux(lo=2, hi=8, num=niter)
assert str(exc.value) == "Invalid num: 'must be a positive integer'"
@requires_data
@requires_fits
def test_sample_flux_not_a_model(make_data_path, clean_astro_ui):
"""What happens when the model component is not a model?
Unfortunately we need a PHA dataset as xrays=False errors
out at the moment.
"""
ui.load_pha(make_data_path('3c273.pi'))
ui.set_model('polynom1d.p1')
ui.notice(1, 7)
with pytest.raises(ArgumentTypeErr) as exc:
ui.sample_flux(lo=6, hi=8, modelcomponent="p1")
assert str(exc.value) == "'modelcomponent' must be a model"
@requires_data
@requires_fits
def test_sample_flux_invalid_model(hide_logging, make_data_path, clean_astro_ui):
"""What happens when the model component is not part of the source?
Unfortunately we need a PHA dataset as xrays=False errors
out at the moment.
At the moment there is no requirement that modelcomponent is
part of the model expression, so all this does is check the
call succeeds. It really should fail!
"""
ui.load_pha(make_data_path('3c273.pi'))
ui.set_model('polynom1d.p1')
ui.notice(1, 7)
ui.set_stat('cash')
ui.fit()
ui.covar()
m2 = ui.create_model_component('const1d', 'm2')
# This should error out! For now we just check the return values
# so we can check when the code changes.
res = ui.sample_flux(lo=6, hi=8, modelcomponent=m2)
assert len(res) == 3
assert res[2].shape == (2, 4)
@pytest.mark.parametrize("conf", [0, 100.1])
def test_sample_flux_invalid_confidence(conf):
"""What happens when confidence is outside the range (0, 100]?
"""
xbins = np.arange(5, 10, 1)
y = np.asarray([10, 12, 11, 12])
ui.load_arrays(1, xbins[:-1], xbins[1:], y, ui.Data1DInt)
ui.set_source(1, ui.const1d.mdl)
# confidence is checked before anything else, so this works even
# if the data isn't sensible for X-ray data
with pytest.raises(ArgumentErr):
ui.sample_flux(confidence=conf)
@pytest.mark.xfail
def test_sample_flux_1d_int():
"""Basic test of sample_flux with Data1DInt not DataPHA
Tests out behavior of
- Xrays=False
- a non-chi-square statistic
- model expression with a single parameter
At the moment this fails for the same reason test_sample_flux_invalid_niter
fails.
"""
xbins = np.arange(5, 10, 1)
y = np.asarray([10, 12, 11, 12])
ui.load_arrays(1, xbins[:-1], xbins[1:], y, ui.Data1DInt)
ui.set_source(1, ui.const1d.mdl)
ui.set_stat('cash')
ui.fit()
ui.covar()
f1, f2, vals = ui.sample_flux(lo=6, hi=8, Xrays=False, num=10)
assert f1.shape == (3, )
assert np.all(f1 == f2)
assert vals.shape == (11, 3)
assert f1[0] < f1[1]
assert f1[0] > f1[2]
# TODO: write more tests, once bug has been fixed to allow sample_flux
# to get this far
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("multi,fac", [(ui.sample_energy_flux, 1.1435100396354445),
(ui.sample_photon_flux, 1.1901038918815168)])
@pytest.mark.parametrize("correlated", [False, True])
def test_sample_foo_flux_component(multi, fac, correlated,
make_data_path, clean_astro_ui,
hide_logging):
"""Can we sample just a component?
The idea is to check that the flux for the unabsorbed
component is larger (on average) than the absorbed
component. We use the model argument for both calls,
which also tests we can send in a multiple-component
model expression.
The expected ratio between absorbed and unabsorbed flux
(the fac argument) was calculated from Sherpa's
calc_energy/photon_flux. This could have been included in
this test, but an external value acts as a regression test.
The assumption is that *for this dataset* the use of correlated
errors does not significantly affect the distributions,
so the same scale factor can be used (this is based on the
best-fit location, so shouldn't depend on the errors).
"""
ui.set_rng(np.random.RandomState(39401))
id = 'xx'
gal, pl = setup_sample(id, make_data_path)
mdl = gal * pl
nh0 = gal.nh.val
gamma0 = pl.gamma.val
ampl0 = pl.ampl.val
ui.covar()
errs = ui.get_covar_results().parmaxes
# restrict to 0.5-2 where the absorption makes a bigger
# difference, relatively speaking, than the 0.5-7 keV
# band used in a number of other tests.
#
absorbed_def = multi(lo=0.5, hi=2, id=id, num=1000,
correlated=correlated)
absorbed = multi(lo=0.5, hi=2, id=id, num=1000,
model=mdl, correlated=correlated)
unabsorbed = multi(lo=0.5, hi=2, id=id, num=1000,
model=pl, correlated=correlated)
assert absorbed.shape == (1000, 5)
assert unabsorbed.shape == (1000, 5)
assert np.isfinite(absorbed).all()
assert np.isfinite(unabsorbed).all()
flux_absorbed = absorbed[:, 0]
flux_unabsorbed = unabsorbed[:, 0]
assert flux_absorbed.min() > 0
assert flux_unabsorbed.min() > 0
# quick check that absorbed_def and absorbed are "the same"
# (modulo the RNG), by comparing the flux distribution. We
# do not perform a more-quantitative analysis here as this
# is assumed to be subsumed by the tests run below on the
# absorbed values, coupled with the previous tests that have
# been run.
#
flux_def = np.median(absorbed_def[:, 0])
flux_abs = np.median(flux_absorbed)
assert flux_abs == pytest.approx(flux_def, rel=0.1)
# Is the ratio similar to the expected values (which was
# calculated at the best-fit location)
#
ratio = np.median(flux_unabsorbed) / flux_abs
assert ratio == pytest.approx(fac, rel=0.004)
# The distributions of the two sets of parameters should be
# similar, since they are drawn from the same distributions.
#
# Compare the medians to the best-fit values and the
# standard deviations to the covariance estimates.
#
nh = absorbed[:, 1]
gamma = absorbed[:, 2]
ampl = absorbed[:, 3]
# We could convert this to a specific check now we have
# a fixed seed.
#
assert np.median(nh) == pytest.approx(nh0, rel=0.2)
assert np.median(gamma) == pytest.approx(gamma0, rel=0.1)
assert np.median(ampl) == pytest.approx(ampl0, rel=0.1)
assert np.std(nh) == pytest.approx(errs[0], rel=0.2)
assert np.std(gamma) == pytest.approx(errs[1], rel=0.1)
assert np.std(ampl) == pytest.approx(errs[2], rel=0.1)
gamma = unabsorbed[:, 2]
ampl = unabsorbed[:, 3]
assert np.median(gamma) == pytest.approx(gamma0, rel=0.1)
assert np.median(ampl) == pytest.approx(ampl0, rel=0.1)
assert np.std(gamma) == pytest.approx(errs[1], rel=0.1)
assert np.std(ampl) == pytest.approx(errs[2], rel=0.1)
@requires_data
@requires_fits
@pytest.mark.parametrize("idval", [1, 2])
def test_sample_flux_pha_num1(idval, make_data_path, clean_astro_ui,
hide_logging, caplog):
"""What happens with 1 iteration?
This is the same data as test_sample_flux_751_752 but
with some extra tests (just to check that the fit is
where we expect it to be; if it changes we should
review the tests, so make them asserts).
"""
# Use a different value to test_sample_flux_751_752
ui.set_rng(np.random.RandomState(3704))
gamma0 = 1.95014
ampl0 = 1.77506e-4
stat0 = 16.270233678440196
# This data set is not heavily absorbed, so can get away with
# just a powerlaw fit for this example (which means we do not
# need XSPEC to run the test).
#
ui.load_pha(idval, make_data_path('3c273.pi'))
ui.subtract(idval)
ui.ignore(None, 1)
ui.ignore(7, None)
ui.set_source(idval, ui.powlaw1d.p1)
ui.fit(idval)
ui.covar(idval)
# just to check we are in the right place; that is, if these fail
# it is not a problem with sample_flux but it (may be) worth
# erroring out quickly as it means we want to review this test
#
sinfo = ui.get_stat_info()
assert len(sinfo) == 1
assert sinfo[0].ids == [idval]
assert sinfo[0].statval == pytest.approx(stat0)
assert sinfo[0].dof == 28
pmdl = ui.get_model_component('p1')
assert pmdl.gamma.val == pytest.approx(gamma0)
assert pmdl.ampl.val == pytest.approx(ampl0)
assert len(caplog.records) == 0
scal = ui.get_covar_results().parmaxes
with SherpaVerbosity('INFO'):
flux1, flux2, vals = ui.sample_flux(id=idval, lo=1, hi=5, num=1,
correlated=False, scales=scal)
assert len(caplog.records) == 2
msgs = []
for rec in caplog.record_tuples:
assert rec[0] == 'sherpa.astro.flux'
assert rec[1] == logging.INFO
msgs.append(rec[2])
assert msgs[0] == 'original model flux = 5.06365e-13, + 3.21673e-14, - 3.21673e-14'
assert msgs[1] == 'model component flux = 5.06365e-13, + 3.21673e-14, - 3.21673e-14'
assert np.all(flux1 == flux2)
assert len(flux1) == 3
assert vals.shape == (2, 5)
# With a fixed seed we can "guarantee" the values are different.
#
for row in vals:
assert row[1] != pytest.approx(gamma0)
assert row[2] != pytest.approx(ampl0)
assert row[3] == 0
assert row[4] > stat0
# check that the parameter values have not changed, nor the
# statistic value, by calling sample_flux
#
assert pmdl.gamma.val == pytest.approx(gamma0)
assert pmdl.ampl.val == pytest.approx(ampl0)
sinfo = ui.get_stat_info()
assert len(sinfo) == 1
assert sinfo[0].ids == [idval]
assert sinfo[0].statval == pytest.approx(stat0)
assert sinfo[0].dof == 28
@requires_data
@requires_fits
def test_sample_flux_nologging(make_data_path, clean_astro_ui,
hide_logging, caplog):
"""Check the example code (using SherpaVerbosity).
We just want to check we get no logging output. We don't
check anything else.
"""
ui.set_rng(np.random.RandomState(3704))
gamma0 = 1.95014
ampl0 = 1.77506e-4
stat0 = 16.270233678440196
ui.load_pha(1, make_data_path('3c273.pi'))
ui.subtract(1)
ui.ignore(None, 1)
ui.ignore(7, None)
ui.set_source(1, ui.powlaw1d.p1)
ui.fit(1)
ui.covar(1)
assert len(caplog.records) == 0
with SherpaVerbosity('WARN'):
ui.sample_flux(id=1, lo=1, hi=5, num=1,
correlated=False)
assert len(caplog.records) == 0
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.sample_energy_flux, ui.sample_photon_flux])
@pytest.mark.parametrize("correlated,scales3",
[(False, [0.04, 0.12, 2.5e-5]),
(False, COVMAT),
(True, COVMAT)])
def test_sample_foo_flux_component_scales(method, correlated, scales3,
make_data_path, clean_astro_ui,
hide_logging):
"""Can we sample just a component and send in errors?
Since the full model (gal * pl) has 3 free parameters
and the power-law 2, do we get the "same" results
when using the full errors (nh, gamma, ampl) as
just (gamma, ampl)?
Checks for
- correlated=False scales=1D array
- correlated=False scales=2D covmat
- correlated=True scales=2D covmat
"""
ui.set_rng(np.random.RandomState(283491))
id = 2
cpts = setup_sample(id, make_data_path)
pl = cpts[1]
gamma0 = pl.gamma.val
ampl0 = pl.ampl.val
unabsorbed3 = method(lo=0.5, hi=2, id=id, num=1000,
model=pl, correlated=correlated,
scales=scales3)
assert unabsorbed3.shape == (1000, 5)
assert np.isfinite(unabsorbed3).all()
flux_unabsorbed3 = unabsorbed3[:, 0]
assert flux_unabsorbed3.min() > 0
# The distributions of the two sets of parameters should be
# similar, since they are drawn from the same distributions.
#
# Compare the medians to the best-fit values and the
# standard deviations to the covariance estimates.
#
# Now we have a fixed seed we could check the actual values
#
ans = np.asarray(scales3)
if ans.ndim == 2:
errs3 = np.sqrt(ans.diagonal())
else:
errs3 = ans
gamma = unabsorbed3[:, 2]
ampl = unabsorbed3[:, 3]
assert np.median(gamma) == pytest.approx(gamma0, rel=0.1)
assert np.median(ampl) == pytest.approx(ampl0, rel=0.1)
assert np.std(gamma) == pytest.approx(errs3[1], rel=0.1)
assert np.std(ampl) == pytest.approx(errs3[2], rel=0.1)
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method", [ui.sample_energy_flux, ui.sample_photon_flux])
@pytest.mark.parametrize("id", [None, 1, "foo"])
def test_sample_foo_flux_component_scales_fitpars(method, id,
make_data_path, clean_astro_ui):
"""Is the fit unchanged when a component + errors are used?
sample_energy/photon_flux can change the model parameters,
including frozen status, in particular when a component
of the fit is used and errors for just that component are
given. This may no-longer be true, but worth a check.
This test checks that running the sample does not change
the fit statistic, number of degrees of freedom, and
parameter values. This repeats some of the checks in
test_sample_foo_flux_niter but for a different set of
inputs.
"""
# save some time by not fitting
gal, pl = setup_sample(id, make_data_path, fit=False)
mdl = gal * pl
pnames0 = [p.fullname for p in mdl.pars]
pvals0 = [p.val for p in mdl.pars]
pstate0 = [p.frozen for p in mdl.pars]
stats0 = ui.get_stat_info()
assert len(stats0) == 1
stats0 = stats0[0]
if id is None:
assert stats0.ids == [1]
else:
assert stats0.ids == [id]
# just to check that the "fit" hasn't changed from the expected value
assert stats0.numpoints == 42
assert stats0.dof == 39
def validate():
"""Check the fit is unchanged"""
stats = ui.get_stat_info()
assert len(stats) == 1
stats = stats[0]
for field in ["name", "ids", "bkg_ids", "statname",
"statval", "numpoints", "dof", "qval", "rstat"]:
v = getattr(stats, field)
v0 = getattr(stats0, field)
assert v == v0
for par, name, val, state in zip(mdl.pars,
pnames0,
pvals0,
pstate0):
assert par.fullname == name
assert par.val == val
assert par.frozen == state
# add in fake errors for the nh values
errs = [0.1, 0.12, 3e-5]
cmat = [[0.1, 0, 0], [0, 0.12, 3e-6], [0, 3e-6, 6e-10]]
# uncorrelated, give errors
ans = method(lo=0.2, hi=10, id=id, num=2, model=pl, correlated=False,
scales=errs)
assert ans.shape == (2, 5)
validate()
# uncorrelated, give covariance matrix
ans = method(lo=0.2, hi=10, id=id, num=2, model=pl, correlated=False,
scales=cmat)
assert ans.shape == (2, 5)
validate()
# correlated, give covariance matrix
ans = method(lo=0.2, hi=10, id=id, num=2, model=pl, correlated=True,
scales=cmat)
assert ans.shape == (2, 5)
validate()
@requires_data
@requires_fits
@requires_xspec
@pytest.mark.parametrize("method,fluxval1,fluxval2",
[(ui.sample_energy_flux,
8.416796789450763e-13, 1.5474830654516002e-13),
(ui.sample_photon_flux,
0.00034170234129722176, 3.3578827014096626e-05)])
@pytest.mark.parametrize("id", [None, "foo"])
def test_sample_foo_flux_bkg(method, fluxval1, fluxval2,
id, make_data_path, clean_astro_ui,
hide_logging):
"""Basic test when calculating flux with a background model.
fluxval is a value used to check that the median values for the
source and background runs are "very roughly" correct: for
the energy flux, we expect the source and background rates to
be ~8e13 and ~1e-13 (with variance larger on the background),
so we use 6e-13 as the separation. Ditto for photon flux with
~4e-4 and ~3e-5 fluxes.
"""
ui.set_rng(np.random.RandomState(22843))
infile = make_data_path('3c273.pi')
if id is None:
ui.load_pha(infile)
ui.ungroup()
else:
ui.load_pha(id, infile)
ui.ungroup(id)
ui.notice(0.5, 7)
ui.set_stat('cstat')
ui.set_method('levmar') # use levmar even with cstat for this case
gal = ui.create_model_component('xswabs', 'gal')
spl = ui.create_model_component('powlaw1d', 'spl')
bpl = ui.create_model_component('powlaw1d', 'bpl')
mdl = gal * spl
gal.nh = 0.029
spl.gamma = 1.96
spl.ampl = 1.9e-4
bpl.gamma = 0.70
bpl.ampl = 9.0e-6
if id is None:
ui.set_source(mdl)
ui.set_bkg_source(bpl)
ui.fit()
else:
ui.set_source(id, mdl)
ui.set_bkg_source(id, bpl)
ui.fit(id)
# check bkg fit is sensible
res = ui.get_fit_results()
assert res.numpoints == 892
assert res.dof == 887
assert res.statval == pytest.approx(803.208946605444)
assert res.parnames == ('gal.nH', 'spl.gamma', 'spl.ampl', 'bpl.gamma', 'bpl.ampl')
assert res.succeeded
# Check how many parameters are returned:
# aflux: nh, source gamma, source ampl
# bflux: bgnd gamma, bgnd ampl
#
niter = 10
aflux = method(0.5, 7, id=id, num=niter)
assert aflux.shape == (niter, 7)
bflux = method(0.5, 7, id=id, bkg_id=1, num=niter)
assert bflux.shape == (niter, 7)
# Compare the median values to the input values.
#
assert np.log10(np.median(aflux[:, 0])) == pytest.approx(np.log10(fluxval1), rel=1e-4)
assert np.log10(np.median(bflux[:, 0])) == pytest.approx(np.log10(fluxval2), rel=1e-4)
# check the gamma values: source~2, bgnd~0.7
#
# Tolerances were rel=1e-4 but when run on macOS ARM it appears
# the values need to be relaxed slightly. An absolute tolerance of
# 3e-4 could have been used instead.
#
assert np.median(aflux[:, 2]) == pytest.approx(1.9575001493165511, rel=2e-4)
assert np.median(bflux[:, 4]) == pytest.approx(0.6022031224500035, rel=2e-4)
# This assumes there's at least one clipped value; this is not
# guaranteed but it looks like it happens consistently
print(aflux[:, 6])
assert aflux[:, 6].min() == 0
assert aflux[:, 6].max() == 1
@requires_data
@requires_fits
@requires_xspec
def test_sample_foo_flux_multi(make_data_path, clean_astro_ui,
hide_logging):
"""Basic test when calculating flux with multiple datasets
and, for completeness, fitting the background.
"""
ui.set_rng(np.random.RandomState(8290573))
# use xswabs as it is simple and unlikely to change
# (rather than one of the newwe absorption models)
#
gal = ui.create_model_component('xswabs', 'gal')
spl = ui.create_model_component('powlaw1d', 'spl')
bpl = ui.create_model_component('powlaw1d', 'bpl')
mdl = gal * spl
gal.nh = 0.04
gal.nh.freeze()
spl.gamma = 1.77
spl.ampl = 7.3e-7
bpl.gamma = 1.42
bpl.ampl = 1.0e-6
# read in obs1, obs3, obs4
for did in range(1, 5):
if did == 2:
continue
# mix and match integer and string ids
if did == 3:
did = str(did)
ui.load_pha(did, make_data_path('obs{}.pi'.format(did)))
ui.set_source(did, mdl)
ui.set_bkg_source(did, bpl)
ui.notice(0.5, 7)
ui.set_stat('cstat')
ui.set_method('levmar') # use levmar even with cstat for this case
ui.fit()
# check fit is sensible
res = ui.get_fit_results()
assert res.numpoints == 2676
assert res.dof == 2672
assert res.statval == pytest.approx(1038.2827482111202)
assert res.parnames == ('spl.gamma', 'spl.ampl', 'bpl.gamma', 'bpl.ampl')
assert res.datasets == (1, '3', 4)
assert res.succeeded
niter = 100
# Fitting to all datasets should return similar errors (not identical
# because random, and the energy grids could be different, but aren't
# in this dataset).
#
s1 = ui.sample_energy_flux(lo=0.5, hi=7, id=1, otherids=('3', 4),
model=spl, num=niter)
b1 = ui.sample_energy_flux(lo=0.5, hi=7, id=1, otherids=('3', 4),
bkg_id=1, model=bpl, num=niter)
s3 = ui.sample_energy_flux(lo=0.5, hi=7, id='3', otherids=(1, 4),
model=spl, num=niter)
b3 = ui.sample_energy_flux(lo=0.5, hi=7, id='3', otherids=(1, 4),
bkg_id=1, model=bpl, num=niter)
assert s1.shape == (niter, 6)
assert b1.shape == (niter, 6)
assert s3.shape == (niter, 6)
assert b3.shape == (niter, 6)
# Compare the median and std dev of the gamma parameter (as of order 1)
# for both the source and background measurements, as they should be
# similar.
#
y1 = np.median(s1[:, 1])
y3 = np.median(s3[:, 1])
assert y1 == pytest.approx(1.7798978430394854), 'source gamma: median'
assert y3 == pytest.approx(1.83540454021743)
y1 = np.median(b1[:, 3])
y3 = np.median(b3[:, 3])
assert y1 == pytest.approx(1.388683605319035), 'background gamma: median'
assert y3 == pytest.approx(1.3891467682303402)
y1 = np.std(s1[:, 1])
y3 = np.std(s3[:, 1])
assert y1 == pytest.approx(0.35157485056777504), 'source gamma: std'
assert y3 == pytest.approx(0.370558381331603)
y1 = np.std(b1[:, 3])
y3 = np.std(b3[:, 3])
assert y1 == pytest.approx(0.1402803370971452), 'background gamma: std'
assert y3 == pytest.approx(0.14460146969815185)
# If we compare to a single run we should see larger errors
# for the single-run case.
#
s4 = ui.sample_energy_flux(lo=0.5, hi=7, id=4, otherids=(),
model=spl, num=niter)
b4 = ui.sample_energy_flux(lo=0.5, hi=7, id=4, otherids=(),
bkg_id=1, model=bpl, num=niter)
assert s4.shape == (niter, 6)
assert b4.shape == (niter, 6)
# The point is that y4 > y3 in both these (compare to previously)
y4 = np.std(s4[:, 1])
assert y4 == pytest.approx(0.5597874155740422)
y4 = np.std(b4[:, 3])
assert y4 == pytest.approx(0.23594231624955062)
# would like to assume there's at least one clipped value for s4
# but not clear
assert s4[:, 5].min() == 0
assert s4[:, 5].max() <= 1
@requires_data
@requires_fits
@pytest.mark.parametrize("idval", [1, 2])
def test_sample_flux_751_752(idval, make_data_path, clean_astro_ui,
hide_logging, caplog):
"""Very basic test of sample_flux.
Based around issue #751 (not all iterations have a statistic
value) and #752 (fails when the id is not the default value).
Based on test_sample_flux_pha_num1.
"""
# Try to ensure we get some clipping.
#
ui.set_rng(np.random.RandomState(4073))
# we want niter to be even so that the returned number of
# values (niter+1) is odd, as that makes the median check
# easier.
#
niter = 100
ui.load_pha(idval, make_data_path('3c273.pi'))
ui.subtract(idval)
ui.ignore(None, 1)
ui.ignore(7, None)
ui.set_source(idval, ui.powlaw1d.p1)
ui.fit(idval)
ui.covar(idval)
scal = ui.get_covar_results().parmaxes
# Restrict gamma so that (hopefully, as it depends on the RNG, but seems
# to do so with niter >~ 10) it triggers clipping in
# sample_flux, which is the cause of #751. Using niter=100 I
# see clipping fractions of ~20-30% (before fixing #751).
#
p1 = ui.get_model_component('p1')
ui.set_par(p1.gamma, min=1.8, max=2.1)
with SherpaVerbosity(logging.INFO):
flux1, flux2, vals = ui.sample_flux(id=idval, lo=1, hi=5, num=niter,
correlated=False, scales=scal)
assert len(caplog.records) == 2
msgs = []
for rec in caplog.record_tuples:
assert rec[0] == 'sherpa.astro.flux'
assert rec[1] == logging.INFO
msgs.append(rec[2])
assert msgs[0] == 'original model flux = 4.90527e-13, + 6.93747e-14, - 6.25625e-14'
assert msgs[1] == 'model component flux = 4.90527e-13, + 6.93747e-14, - 6.25625e-14'
# as modelcomponent is None, first two arguments should be the same
assert np.all(flux1 == flux2)
assert flux1.shape == (3, )
assert vals.shape == (niter + 1, 5)
# Basic checks on the flux errors:
# - are they in the right order
# - manual check that they are close to the expected value
# (the default is confidence=68).
# as we have an odd number of iterations
# THIS IS NOT DONE YET - see #286, in particular
# https://github.com/sherpa/sherpa/issues/286#issuecomment-596207243
#
fmed, fusig, flsig = flux1
assert fusig > fmed
assert flsig < fmed
# It isn't clear what should be tested here (see #286) so just
# test something very basic
#
fluxes = vals[:, 0]
assert flsig > fluxes.min()
assert fusig < fluxes.max()
# The clip values are set.
#
clipped = vals[:, -2] != 0
assert clipped.sum() == 20
# All the statistic values should be set (> 0). This wasn't until #751
# was addressed.
#
stats = vals[:, -1]
assert (stats > 0).all()
# We assume that the stats for the clipped values are worse
# than for the unclipped values. Unfortunately they are not guaranteed
# to not overlap, so all we can do is ensure some simple checks,
# such as the minimum values are different.
#
assert stats[clipped].min() >= stats[~clipped].min()
# check that the calculated median is the same as the median
# we can calculate with the unclipped data. This is for flux1 not
# flux2 (although in this test they are the same).
#
fcalc = np.median(fluxes[~clipped])
assert fcalc == pytest.approx(fmed)
# regression test
assert stats[clipped][0] == pytest.approx(51.56646084)
assert stats[~clipped][-1] == pytest.approx(22.10377607)
@requires_xspec
@requires_data
@requires_fits
def test_sample_flux_457(make_data_path, clean_astro_ui,
hide_logging):
"""What happens with upper-bounds?
The absorption is an upper limit, so check what happens
with the filtered data? Issue #457 noted that values at
the soft limits were not being included, causing a bias
(at least for this situation, when nh=0).
"""
ui.set_default_id('bob')
ui.set_stat('chi2datavar')
# Try to ensure we get some clipping.
#
ui.set_rng(np.random.RandomState(8077))
# we want niter to be even so that the returned number of
# values (niter+1) is odd, as that makes the median check
# easier.
#
niter = 100
ui.load_pha(make_data_path('3c273.pi'))
ui.subtract()
ui.notice(0.5, 6)
ui.set_source(ui.xsphabs.gal * ui.powlaw1d.p1)
ui.fit()
ui.covar()
scal = ui.get_covar_results().extra_output
flux1, flux2, vals = ui.sample_flux(p1, lo=0.5, hi=7, num=niter,
correlated=True, scales=scal)
# Values taken from the screen output
assert flux1[0] == pytest.approx(7.50199e-13)
assert flux1[1] == pytest.approx(7.50199e-13 + 3.64329e-14)
assert flux1[2] == pytest.approx(7.50199e-13 - 2.87033e-14)
assert flux2[0] == pytest.approx(8.19482e-13)
assert flux2[1] == pytest.approx(8.19482e-13 + 5.42782e-14)
assert flux2[2] == pytest.approx(8.19482e-13 - 6.87875e-14)
# unabsorbed flux should be >= absorbed.
assert np.all(flux2 >= flux1)
assert flux1.shape == (3, )
assert vals.shape == (niter + 1, 6)
# There are 17 "clipped" rows.
#
clipped = vals[:, -2] != 0
assert clipped.sum() == 17
# A check for issue #751.
#
stats = vals[:, -1]
assert (stats > 0).sum() == (niter + 1)
@requires_data
@requires_fits
@pytest.mark.parametrize("getfunc,medflux",
[(ui.get_photon_flux_hist, 1.276591979716474e-4),
(ui.get_energy_flux_hist, 4.550271338687814e-13)])
def test_get_xxx_flux_hist_unabsorbed(getfunc, medflux, make_data_path, clean_astro_ui,
hide_logging):
"""Can we get the histogram data for fluxes (for an unabsorbed flux?)"""
ui.set_rng(np.random.RandomState(427247))
infile = make_data_path('3c273.pi')
ui.load_pha(infile)
scale = ui.create_model_component('const1d', 'scale')
pl = ui.create_model_component('powlaw1d', 'pl')
scale.c0 = 0.8
scale.integrate = False
pl.gamma = 1.5
pl.ampl = 1e-4
ui.set_source(scale * pl)
# Would like to use model=pl but needs #803 (I think)
flux = getfunc(0.7, 7, num=500, bins=10)
assert flux.flux.shape == (500, )
assert flux.modelvals.shape == (500, 3)
assert flux.xlo.size == 11
assert flux.xhi.size == 11
assert flux.y.size == 11
assert (flux.xlo[1:] == flux.xhi[:-1]).all()
assert np.median(flux.flux) == pytest.approx(medflux)
@requires_data
@requires_fits
@pytest.mark.parametrize("plotfunc",
[ui.plot_photon_flux, ui.plot_energy_flux])
def test_plot_xxx_flux_unabsorbed(plotfunc, make_data_path, clean_astro_ui,
hide_logging):
"""Can we plot the histogram data for fluxes (for an unabsorbed flux?)
There is essentially no check that we do the right thing
"""
ui.set_rng(np.random.RandomState(427248))
infile = make_data_path('3c273.pi')
ui.load_pha(infile)
scale = ui.create_model_component('const1d', 'scale')
pl = ui.create_model_component('powlaw1d', 'pl')
scale.c0 = 0.8
scale.integrate = False
pl.gamma = 1.5
pl.ampl = 1e-4
ui.set_source(scale * pl)
# Would like to use model=pl but needs #803 (I think)
plotfunc(0.7, 7, num=500, bins=10)
# What do we do to test this?
@requires_data
@requires_fits
def test_sample_flux_errors(make_data_path, clean_astro_ui,
hide_logging):
"""Does sample_flux return sensible sigma limits?
This can be thought of as test_sample_flux_751_752 but just
looking at the flux median/upper/lower limits (to have a
simple test for addressing #286).
There is also a test of the statistics "column" information.
"""
ui.set_rng(np.random.RandomState(28737))
# now we have a seed can we get tighter constraints
# want to get good stats
niter = 1000
ui.load_pha(make_data_path('3c273.pi'))
ui.subtract()
ui.ignore(None, 1)
ui.ignore(7, None)
ui.set_source(ui.powlaw1d.p1)
ui.fit()
stat0 = ui.calc_stat()
res = ui.sample_flux(lo=0.5, hi=7, num=niter, correlated=False)
# check the source model hasn't been changed (note: do not use
# pytest.approx as expect the same value, but can switch if
# needed).
#
assert ui.calc_stat() == stat0
# Get values close to 1 to make comparison easier
res[0] *= 1e14
fmed = res[0][0]
fusig = res[0][1]
flsig = res[0][2]
# Regression test
#
elo = fmed - flsig
ehi = fusig - fmed
assert fmed == pytest.approx(77.27966775437665)
assert elo == pytest.approx(9.773389936230018)
assert ehi == pytest.approx(11.417501513386611)
# The last column of res[2] is the statistic value for a row -
# although due to filtering we don't know which row without some
# significant work. Check that the values make sense (ie if we
# have found the best-fit then all values should be >= stat0).
#
assert res[2].shape == (niter + 1, 5)
stats = res[2][:, 4]
# For this dataset no rows are excluded.
#
assert (stats > 0).all()
# Ideally the best-fit location is the best fit!
assert stats.min() >= stat0
# Check the clip column too. This lists the soft-clipped rows,
# which for this case is ?
#
clips = res[2][:, 3]
assert (clips == 0).all()
@requires_data
@requires_fits
@pytest.mark.parametrize("idval", [1, 2])
def test_sample_flux_pha_component(idval, make_data_path, clean_astro_ui,
hide_logging, caplog):
"""Does the component analysis work?
Apply a model which has a normalization term in it (which is fixed)
so that we can easily compare the full and component fluxes.
The parameter checks are "generic" (ie don't need to be
done with a model component given), but are included here because
this uses multiple model components in the source expression.
"""
ui.set_rng(np.random.RandomState(97284))
# Now we have a fixed seed we don't need to run as many iterations.
#
niter = 100
ui.load_pha(idval, make_data_path('3c273.pi'))
ui.subtract(idval)
ui.ignore(None, 1)
ui.ignore(7, None)
ui.set_source(idval, ui.const1d.scal * ui.powlaw1d.p1)
p1 = ui.get_model_component('p1')
scal = ui.get_model_component('scal')
scal.c0 = 0.8
scal.integrate = False
scal.c0.frozen = True
ui.fit(idval)
ui.covar(idval)
stat0 = ui.calc_stat(idval)
scal = ui.get_covar_results().parmaxes
with SherpaVerbosity('INFO'):
flux1, flux2, vals = ui.sample_flux(modelcomponent=p1,
id=idval, lo=1, hi=5, num=niter,
correlated=False, scales=scal)
assert len(caplog.records) == 2
msgs = []
for rec in caplog.record_tuples:
msgs.append(rec[2])
assert msgs[0] == 'original model flux = 4.78484e-13, + 7.8702e-14, - 5.87503e-14'
assert msgs[1] == 'model component flux = 5.98105e-13, + 9.83775e-14, - 7.34378e-14'
# check the source model hasn't been changed (note: do not use
# pytest.approx as expect the same value, but can switch if
# needed).
#
assert ui.calc_stat(idval) == stat0
assert flux1.shape == (3, )
assert flux2.shape == (3, )
assert np.any(flux1 != flux2)
assert vals.shape == (niter + 1, 5)
assert flux1[0] < flux1[1]
assert flux1[0] > flux1[2]
# Now, flux2 should be 1/0.8 = 1.25 times larger,
# and this should hold for all three terms (since drawn from the
# same distributions modulo the different model components there
# is no "randomness" in this ratio).
#
for i in range(3):
rlim = flux2[i] / flux1[i]
assert rlim == pytest.approx(1 / 0.8)
# Regression test
assert np.log10(flux1[0]) == pytest.approx(-12.320132853894787)
# Regression test of the output (if these change, compare against
# p1.gamma.val, p1.ampl.val).
#
mgamma = np.median(vals[:, 1])
mampl = np.log10(np.median(vals[:, 2]))
assert mgamma == pytest.approx(1.9476566223146197)
assert mampl == pytest.approx(-3.6498020707240153)
# No clipping
#
assert (vals[:, 3] == 0).all()
# No missing values (statistic is set for all bins)
#
assert (vals[:, 4] > 0).all()
@requires_data
@requires_fits
@pytest.mark.parametrize("idval", [1, 2])
def test_sample_flux_pha_bkg_no_source(idval, make_data_path, clean_astro_ui,
hide_logging):
"""Can we get the flux for the background fit when there's no source model?"""
ui.set_rng(np.random.RandomState(287241))
niter = 100
ui.load_pha(idval, make_data_path('3c273.pi'))
ui.ignore(None, 0.8)
ui.ignore(7, None)
ui.set_bkg_source(idval, ui.powlaw1d.bpl)
bpl = ui.get_model_component('bpl')
bpl.gamma = 0.54
bpl.ampl = 6.4e-6
ui.fit_bkg(idval)
# At the moment we need a source model (I guess to get the
# covariance), so this fails.
#
with pytest.raises(IdentifierErr) as exc:
ui.sample_flux(id=idval, bkg_id=1,
lo=1, hi=5, num=niter,
correlated=False)
assert str(exc.value) == 'model stack is empty'
@requires_data
@requires_fits
@requires_group
@requires_xspec
@pytest.mark.parametrize("idval", [1, 2])
def test_sample_flux_pha_bkg(idval, make_data_path, clean_astro_ui,
hide_logging):
"""Can we get the flux for the background fit.
In this case we have a source fit that has also been run,
so the error analysis should be fine.
"""
ui.set_stat('chi2datavar')
ui.set_method('levmar')
niter = 100
ui.load_pha(idval, make_data_path('3c273.pi'))
# Need to ungroup so we can use the mask attribute
ui.ungroup(idval)
ui.ignore(None, 0.8)
ui.ignore(7, None)
d = ui.get_data(idval)
b = ui.get_bkg(idval)
# We need to do it this way (background first)
ui.group_counts(num=20, id=idval, bkg_id=1, tabStops=~b.mask)
ui.group_counts(num=20, id=idval, tabStops=~d.mask)
ui.set_bkg_source(idval, ui.powlaw1d.bpl)
ui.set_source(idval, ui.xswabs.gabs * ui.powlaw1d.pl)
bpl = ui.get_model_component('bpl')
bpl.gamma = 0.54
bpl.ampl = 6.4e-6
pl = ui.get_model_component('pl')
pl.gamma = 2.0
pl.ampl = 2e-4
gabs = ui.get_model_component('gabs')
gabs.nh = 0.05
gabs.nh.freeze()
ui.fit_bkg(idval)
ui.fit(idval)
# We don't try to run covar or get the statistic values
# (the API doesn't make that easy for background fits).
#
# Use the same seed for both runs.
#
ui.set_rng(np.random.RandomState(287247))
bflux1, bflux2, bvals = ui.sample_flux(id=idval, bkg_id=1,
lo=1, hi=5, num=niter,
correlated=False)
ui.set_rng(np.random.RandomState(287247))
flux1, flux2, vals = ui.sample_flux(id=idval,
lo=1, hi=5, num=niter,
correlated=False)
assert flux2 == pytest.approx(flux1)
assert bflux2 == pytest.approx(bflux1)
assert np.log10(flux1) == pytest.approx([-12.31348652, -12.28200881, -12.34610975])
assert np.log10(bflux1) == pytest.approx([-13.15241991, -12.97986006, -13.31382087])
# Just check that the flux we've got is close to the one calculated by
# calc_energy_flux. This is just to test the values we have checked for
# the median value of flux1 and bflux1.
#
# Note that I am slightly concerned that the background flux has been
# calculated using the source response, not the background response.
# This is too hard to identify with this dataset. We need a test which
# has drastically different background response (and maybe exposure
# time).
#
sflux = ui.calc_energy_flux(id=idval, lo=1, hi=5)
bflux = ui.calc_energy_flux(id=idval, bkg_id=1, lo=1, hi=5)
assert np.log10(sflux) == pytest.approx(-12.310733810154623)
assert np.log10(bflux) == pytest.approx(-13.110679628882489)
# The random parameters are assumed to be the same. In reality the
# background doesn't need to include the source dataset but that's an
# issue to look at later.
#
assert bvals.shape == (101, 7)
assert vals.shape == (101, 7)
# For the value checks we need to drop the first column, which has the
# fluxes.
#
assert (bvals[:, 1:] == vals[:, 1:]).all()
@requires_data
@requires_fits
@pytest.mark.parametrize("idval", [1, 2])
def test_sample_flux_pha_full_model(idval, make_data_path, clean_astro_ui,
hide_logging, caplog):
"""When using set_full_model we error out. Is it a nice error?"""
ui.set_rng(np.random.RandomState(9783))
niter = 100
ui.load_pha(idval, make_data_path('3c273.pi'))
ui.subtract(idval)
ui.ignore(None, 1)
ui.ignore(7, None)
rsp = ui.get_response(idval)
ui.set_full_model(idval, rsp(ui.const1d.scal * ui.powlaw1d.p1))
p1 = ui.get_model_component('p1')
scal = ui.get_model_component('scal')
scal.c0 = 0.8
scal.integrate = False
scal.c0.frozen = True
ui.fit(idval)
ui.covar(idval)
scal = ui.get_covar_results().parmaxes
with pytest.raises(IdentifierErr) as ie:
ui.sample_flux(modelcomponent=p1,
id=idval, lo=1, hi=5, num=niter,
correlated=False, scales=scal)
assert str(ie.value) == 'Please use calc_energy_flux as set_full_model was used'
@requires_data
@requires_fits
@pytest.mark.parametrize("idval", [1, 2])
def test_sample_flux_pha_bkg_full_model(idval, make_data_path, clean_astro_ui,
hide_logging, caplog):
"""When using set_bkg_full_model we error out. Is it a nice error?"""
ui.set_rng(np.random.RandomState(9783))
niter = 100
ui.load_pha(idval, make_data_path('3c273.pi'))
ui.subtract(idval)
ui.ignore(None, 1)
ui.ignore(7, None)
# I don't think we can get covar for just the background data so we have
# had to fit the whole dataset.
#
brsp = ui.get_response(idval, bkg_id=1)
ui.set_bkg_full_model(idval, brsp(ui.powlaw1d.bpl))
bpl = ui.get_model_component('bpl')
bpl.gamma = 0.54
bpl.ampl = 6.4e-6
ui.fit_bkg(idval)
bscale = ui.get_bkg_scale(idval)
rsp = ui.get_response(idval)
ui.set_full_model(idval, rsp(ui.powlaw1d.pl) + bscale * rsp(bpl))
ui.fit(idval)
ui.covar(idval) # , bkg_id=1)
scal = ui.get_covar_results().parmaxes
with pytest.raises(IdentifierErr) as ie:
ui.sample_flux(modelcomponent=bpl, bkg_id=1,
id=idval, lo=1, hi=5, num=niter,
correlated=False, scales=scal)
assert str(ie.value) == 'Please use calc_energy_flux as set_bkg_full_model was used'
|
sherpaREPO_NAMEsherpaPATH_START.@sherpa_extracted@sherpa-main@sherpa@astro@ui@tests@test_astro_ui_fluxes.py@.PATH_END.py
|
{
"filename": "_family.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/funnelarea/title/font/_family.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="family", parent_name="funnelarea.title.font", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "plot"),
no_blank=kwargs.pop("no_blank", True),
strict=kwargs.pop("strict", True),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@funnelarea@title@font@_family.py@.PATH_END.py
|
{
"filename": "README.md",
"repo_name": "amusecode/amuse",
"repo_path": "amuse_extracted/amuse-main/packages/amuse-bhtree/README.md",
"type": "Markdown"
}
|
This package installs the BHTree community code for AMUSE.
|
amusecodeREPO_NAMEamusePATH_START.@amuse_extracted@amuse-main@packages@amuse-bhtree@README.md@.PATH_END.py
|
{
"filename": "_ticklabelstep.py",
"repo_name": "plotly/plotly.py",
"repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/layout/polar/radialaxis/_ticklabelstep.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class TicklabelstepValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self,
plotly_name="ticklabelstep",
parent_name="layout.polar.radialaxis",
**kwargs,
):
super(TicklabelstepValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
min=kwargs.pop("min", 1),
**kwargs,
)
|
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@layout@polar@radialaxis@_ticklabelstep.py@.PATH_END.py
|
{
"filename": "_aggregations_app.md",
"repo_name": "zooniverse/caesar",
"repo_path": "caesar_extracted/caesar-master/docs/source/includes/_aggregations_app.md",
"type": "Markdown"
}
|
A list of task-specific outputs is detailed in the sections below.
## Tool specific data
### Question tool
>Sample task data for a simple Question task
```json
"T0": [
{
"task": "T0",
"value": 0,
"taskType": "single"
}
```
The question tool stores the answer in the`value` key, as the index of the answer (first answer is a 0).
## Data Formats for Extractors
In this section, we outline the JSON data format details to be passed to different extractors in the aggregation-caeser API. If you have a custom ExternalExtractor API, you must make sure that the input and output data is in the same format as shown here.
>Sample task data for a simple Question extractor
```json
"T0": [
{
"task": "T0",
"value": 0,
"taskType": "single"
}
```
### Question Extractor
The question extract retrieves the `value` key from a task. For a normal
question task, the value is the index of the answer (first answer is a
0), and how many times that answer has been chosen.
> returns
```json
{
"0": 1,
"aggregation_version": "3.6.0"
}
```
## Shape Extractor
This is a general-purpose extractor that can retrieve information regarding various shape tools used. One can specify which shape information to extract by passing the `task identifier` (e.g., `T0`) and `shape=name` (e.g., `shape=rectangle`) as such: `https://aggregation-caesar.zooniverse.org/extractors/shape_extractor?task=T1&shape=circle`. The following are the list of shapes that you can extract using the shape extractor:
+ `Rectangle Extractor`
+ `Circle Extractor`
+ `Point Extractor`
+ `Line Extractor`
> Example data for a Rectangle Extractor
```json
"T1": [
{
"task": "T1",
"value": [
{
"x": 190.0546875,
"y": 292.55859375,
"tool": 1,
"angle": -36.34308118417328,
"frame": 0,
"width": 313.40234375,
"height": 149.66796875,
"details": []
}
]
}
],
```
### Rectangle Extractor
A rectangle extractor takes the following information from the data dump (in the specified format on the right) to extract details of the rectangles specified by the classifier. The usage is `https://aggregation-caesar.zooniverse.org/extractors/shape_extractor?task=T1&shape=rectangle`
__Note__: There is a dedicated `Rectangle Extractor` that one can use instead of the shape extractor by `https://aggregation-caesar.zooniverse.org/extractors/rectangle_extractor?task=T1`, where `task=T*` should be the task identifier corresponding to the rectangle tool usage task.
#### Input
+ `x`: x coodrinate of the rectangle's centroid.
+ `y`: y coordinate of the rectangle's centroid.
+ `tool`: tool id of the rectangle?
+ `angle`: rotation angle of the rectangle.
+ `frame`: ???
+ `width`: width of the rectangle.
+ `height`: height of the rectangle.
>Example output of the rectangle extractor
```json
{
"aggregation_version": "3.6.0",
"frame0": {
"T1_tool1_height": [
149.66796875
],
"T1_tool1_width": [
313.40234375
],
"T1_tool1_x": [
190.0546875
],
"T1_tool1_y": [
292.55859375
]
}
}
```
#### Output
The parameters follow the general format of TaskIdentifier_ToolIdentifier
+ `frameX`: ??
+ `T*_tool*_height`: The width of the .
+ `T*_tool*_width`: The height of the tool ()
>Sample task data for a Circle Extractor
```json
"T1": [
{
"task": "T1",
"value": [
{
"r": 82.84781455160156,
"x": 276.80859375,
"y": 317.0390625,
"tool": 0,
"angle": 159.37755608105448,
"frame": 0,
"details": []
}
]
]
```
### Circle Extractor
You can use the `shape=circle` argument to specify the shape extractor to get the information of the circle tool used in the classification task. Example usage is: `https://aggregation-caesar.zooniverse.org/extractors/shape_extractor?task=T1&shape=circle`, where `task=T*` is the task corresponding to the circle tool.
+ `task`: task identifier
+ `r`: Radius of the circle.
+ `x`: x coordinate of the circle's center.
+ `y`: y coordinate of the circle's center.
+ `tool`: ??
+ `angle`: azimuthal rotation angle??
> Sample data for the tasks empty extractor
> Multiple tasks where each task is empty:
```json
"T0": [
{
"task": "T0"
}
],
"T1": [
{
"task": "T1"
}
]
```
> Sample data for point extractor
```json
"T1": [
{
"task": "T1",
"value": [
{
"x": 278.75,
"y": 141.96665954589844,
"tool": 3,
"frame": 0,
"details": []
}
]
}
]
```
### Point extractor/Point extractor by frame
This extractor obtains the x, y coordinate values of the point task. Note that in this case,
the external URL must also contain the task ID (e.g., [https://aggregation-caesar.zooniverse.org/extractors/point_extractor?task=T1](https://aggregation-caesar.zooniverse.org/extractors/point_extractor?task=T1)) so that the extractor has information about the task from which to extract the coordinate values. In this case, the following values are used as input in the `value` key:
+ `x` : The x-coordinate of the point
+ `y` : The y-coordinate of the point
+ `tool`: (I think this is the index of the tool on the front end?)
+ `frame` : .... no clue
+ `details` : .... no clue
The returned values are in the format `[taskID]_tool[toolID]_[x/y]`, similar to the other shape extractors above.
The `point_extractor_by_frame` extractor performs a similar function, except at the output level, where each (x,y) coordinate value is categorized by the frame number:
> returns
```json
{
"T1_tool3_x": [
278.75
],
"T1_tool3_y": [
141.96665954589844
],
"aggregation_version": "3.6.0"
}
```
> or with the `point_extractor_by_frame`:
```json
{
"aggregation_version": "3.6.0",
"frame0": {
"T1_tool3_x": [
278.75
],
"T1_tool3_y": [
141.96665954589844
]
}
}
```
### Line Extractor
A line extraction functionality in the shape extractor retrieves the information of the `(x1,y1)` and `(x2,y2)` points of the line. Example usage is: `https://aggregation-caesar.zooniverse.org/extractors/shape_extractor?task=T1&shape=line`, where `task=T*` is the task corresponding to the line tool.
> Sample input data to line extractor
```json
{
{
"x1": 191.75,
"x2": 647.75,
"y1": 477.9666748046875,
"y2": 295.9666748046875,
"tool": 2,
"frame": 0,
"details": []
}
}
```
> Output of the line extraction
```json
{
"aggregation_version": "3.6.0",
"frame0": {
"T1_tool2_x1": [
191.75
],
"T1_tool2_x2": [
647.75
],
"T1_tool2_y1": [
477.9666748046875
],
"T1_tool2_y2": [
295.9666748046875
]
}
}
```
### All Tasks Empty extractor
This extractor checks whether all tasks in the classification are empty.
If all tasks do not have a `value` key, then the extractor returns the
`result` key as `True`. If any of the tasks have a classification, then
the `result` key is `False`.
> returns
```json
{
"aggregation_version": "3.6.0",
"result": true
}
```
|
zooniverseREPO_NAMEcaesarPATH_START.@caesar_extracted@caesar-master@docs@source@includes@_aggregations_app.md@.PATH_END.py
|
{
"filename": "test_half.py",
"repo_name": "numpy/numpy",
"repo_path": "numpy_extracted/numpy-main/numpy/_core/tests/test_half.py",
"type": "Python"
}
|
import platform
import pytest
import numpy as np
from numpy import uint16, float16, float32, float64
from numpy.testing import assert_, assert_equal, IS_WASM
def assert_raises_fpe(strmatch, callable, *args, **kwargs):
try:
callable(*args, **kwargs)
except FloatingPointError as exc:
assert_(str(exc).find(strmatch) >= 0,
"Did not raise floating point %s error" % strmatch)
else:
assert_(False,
"Did not raise floating point %s error" % strmatch)
class TestHalf:
def setup_method(self):
# An array of all possible float16 values
self.all_f16 = np.arange(0x10000, dtype=uint16)
self.all_f16.dtype = float16
# NaN value can cause an invalid FP exception if HW is being used
with np.errstate(invalid='ignore'):
self.all_f32 = np.array(self.all_f16, dtype=float32)
self.all_f64 = np.array(self.all_f16, dtype=float64)
# An array of all non-NaN float16 values, in sorted order
self.nonan_f16 = np.concatenate(
(np.arange(0xfc00, 0x7fff, -1, dtype=uint16),
np.arange(0x0000, 0x7c01, 1, dtype=uint16)))
self.nonan_f16.dtype = float16
self.nonan_f32 = np.array(self.nonan_f16, dtype=float32)
self.nonan_f64 = np.array(self.nonan_f16, dtype=float64)
# An array of all finite float16 values, in sorted order
self.finite_f16 = self.nonan_f16[1:-1]
self.finite_f32 = self.nonan_f32[1:-1]
self.finite_f64 = self.nonan_f64[1:-1]
def test_half_conversions(self):
"""Checks that all 16-bit values survive conversion
to/from 32-bit and 64-bit float"""
# Because the underlying routines preserve the NaN bits, every
# value is preserved when converting to/from other floats.
# Convert from float32 back to float16
with np.errstate(invalid='ignore'):
b = np.array(self.all_f32, dtype=float16)
# avoid testing NaNs due to differing bit patterns in Q/S NaNs
b_nn = b == b
assert_equal(self.all_f16[b_nn].view(dtype=uint16),
b[b_nn].view(dtype=uint16))
# Convert from float64 back to float16
with np.errstate(invalid='ignore'):
b = np.array(self.all_f64, dtype=float16)
b_nn = b == b
assert_equal(self.all_f16[b_nn].view(dtype=uint16),
b[b_nn].view(dtype=uint16))
# Convert float16 to longdouble and back
# This doesn't necessarily preserve the extra NaN bits,
# so exclude NaNs.
a_ld = np.array(self.nonan_f16, dtype=np.longdouble)
b = np.array(a_ld, dtype=float16)
assert_equal(self.nonan_f16.view(dtype=uint16),
b.view(dtype=uint16))
# Check the range for which all integers can be represented
i_int = np.arange(-2048, 2049)
i_f16 = np.array(i_int, dtype=float16)
j = np.array(i_f16, dtype=int)
assert_equal(i_int, j)
@pytest.mark.parametrize("string_dt", ["S", "U"])
def test_half_conversion_to_string(self, string_dt):
# Currently uses S/U32 (which is sufficient for float32)
expected_dt = np.dtype(f"{string_dt}32")
assert np.promote_types(np.float16, string_dt) == expected_dt
assert np.promote_types(string_dt, np.float16) == expected_dt
arr = np.ones(3, dtype=np.float16).astype(string_dt)
assert arr.dtype == expected_dt
@pytest.mark.parametrize("string_dt", ["S", "U"])
def test_half_conversion_from_string(self, string_dt):
string = np.array("3.1416", dtype=string_dt)
assert string.astype(np.float16) == np.array(3.1416, dtype=np.float16)
@pytest.mark.parametrize("offset", [None, "up", "down"])
@pytest.mark.parametrize("shift", [None, "up", "down"])
@pytest.mark.parametrize("float_t", [np.float32, np.float64])
def test_half_conversion_rounding(self, float_t, shift, offset):
# Assumes that round to even is used during casting.
max_pattern = np.float16(np.finfo(np.float16).max).view(np.uint16)
# Test all (positive) finite numbers, denormals are most interesting
# however:
f16s_patterns = np.arange(0, max_pattern+1, dtype=np.uint16)
f16s_float = f16s_patterns.view(np.float16).astype(float_t)
# Shift the values by half a bit up or a down (or do not shift),
if shift == "up":
f16s_float = 0.5 * (f16s_float[:-1] + f16s_float[1:])[1:]
elif shift == "down":
f16s_float = 0.5 * (f16s_float[:-1] + f16s_float[1:])[:-1]
else:
f16s_float = f16s_float[1:-1]
# Increase the float by a minimal value:
if offset == "up":
f16s_float = np.nextafter(f16s_float, float_t(np.inf))
elif offset == "down":
f16s_float = np.nextafter(f16s_float, float_t(-np.inf))
# Convert back to float16 and its bit pattern:
res_patterns = f16s_float.astype(np.float16).view(np.uint16)
# The above calculation tries the original values, or the exact
# midpoints between the float16 values. It then further offsets them
# by as little as possible. If no offset occurs, "round to even"
# logic will be necessary, an arbitrarily small offset should cause
# normal up/down rounding always.
# Calculate the expected pattern:
cmp_patterns = f16s_patterns[1:-1].copy()
if shift == "down" and offset != "up":
shift_pattern = -1
elif shift == "up" and offset != "down":
shift_pattern = 1
else:
# There cannot be a shift, either shift is None, so all rounding
# will go back to original, or shift is reduced by offset too much.
shift_pattern = 0
# If rounding occurs, is it normal rounding or round to even?
if offset is None:
# Round to even occurs, modify only non-even, cast to allow + (-1)
cmp_patterns[0::2].view(np.int16)[...] += shift_pattern
else:
cmp_patterns.view(np.int16)[...] += shift_pattern
assert_equal(res_patterns, cmp_patterns)
@pytest.mark.parametrize(["float_t", "uint_t", "bits"],
[(np.float32, np.uint32, 23),
(np.float64, np.uint64, 52)])
def test_half_conversion_denormal_round_even(self, float_t, uint_t, bits):
# Test specifically that all bits are considered when deciding
# whether round to even should occur (i.e. no bits are lost at the
# end. Compare also gh-12721. The most bits can get lost for the
# smallest denormal:
smallest_value = np.uint16(1).view(np.float16).astype(float_t)
assert smallest_value == 2**-24
# Will be rounded to zero based on round to even rule:
rounded_to_zero = smallest_value / float_t(2)
assert rounded_to_zero.astype(np.float16) == 0
# The significand will be all 0 for the float_t, test that we do not
# lose the lower ones of these:
for i in range(bits):
# slightly increasing the value should make it round up:
larger_pattern = rounded_to_zero.view(uint_t) | uint_t(1 << i)
larger_value = larger_pattern.view(float_t)
assert larger_value.astype(np.float16) == smallest_value
def test_nans_infs(self):
with np.errstate(all='ignore'):
# Check some of the ufuncs
assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32))
assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32))
assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32))
assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32))
assert_equal(np.spacing(float16(65504)), np.inf)
# Check comparisons of all values with NaN
nan = float16(np.nan)
assert_(not (self.all_f16 == nan).any())
assert_(not (nan == self.all_f16).any())
assert_((self.all_f16 != nan).all())
assert_((nan != self.all_f16).all())
assert_(not (self.all_f16 < nan).any())
assert_(not (nan < self.all_f16).any())
assert_(not (self.all_f16 <= nan).any())
assert_(not (nan <= self.all_f16).any())
assert_(not (self.all_f16 > nan).any())
assert_(not (nan > self.all_f16).any())
assert_(not (self.all_f16 >= nan).any())
assert_(not (nan >= self.all_f16).any())
def test_half_values(self):
"""Confirms a small number of known half values"""
a = np.array([1.0, -1.0,
2.0, -2.0,
0.0999755859375, 0.333251953125, # 1/10, 1/3
65504, -65504, # Maximum magnitude
2.0**(-14), -2.0**(-14), # Minimum normal
2.0**(-24), -2.0**(-24), # Minimum subnormal
0, -1/1e1000, # Signed zeros
np.inf, -np.inf])
b = np.array([0x3c00, 0xbc00,
0x4000, 0xc000,
0x2e66, 0x3555,
0x7bff, 0xfbff,
0x0400, 0x8400,
0x0001, 0x8001,
0x0000, 0x8000,
0x7c00, 0xfc00], dtype=uint16)
b.dtype = float16
assert_equal(a, b)
def test_half_rounding(self):
"""Checks that rounding when converting to half is correct"""
a = np.array([2.0**-25 + 2.0**-35, # Rounds to minimum subnormal
2.0**-25, # Underflows to zero (nearest even mode)
2.0**-26, # Underflows to zero
1.0+2.0**-11 + 2.0**-16, # rounds to 1.0+2**(-10)
1.0+2.0**-11, # rounds to 1.0 (nearest even mode)
1.0+2.0**-12, # rounds to 1.0
65519, # rounds to 65504
65520], # rounds to inf
dtype=float64)
rounded = [2.0**-24,
0.0,
0.0,
1.0+2.0**(-10),
1.0,
1.0,
65504,
np.inf]
# Check float64->float16 rounding
with np.errstate(over="ignore"):
b = np.array(a, dtype=float16)
assert_equal(b, rounded)
# Check float32->float16 rounding
a = np.array(a, dtype=float32)
with np.errstate(over="ignore"):
b = np.array(a, dtype=float16)
assert_equal(b, rounded)
def test_half_correctness(self):
"""Take every finite float16, and check the casting functions with
a manual conversion."""
# Create an array of all finite float16s
a_bits = self.finite_f16.view(dtype=uint16)
# Convert to 64-bit float manually
a_sgn = (-1.0)**((a_bits & 0x8000) >> 15)
a_exp = np.array((a_bits & 0x7c00) >> 10, dtype=np.int32) - 15
a_man = (a_bits & 0x03ff) * 2.0**(-10)
# Implicit bit of normalized floats
a_man[a_exp != -15] += 1
# Denormalized exponent is -14
a_exp[a_exp == -15] = -14
a_manual = a_sgn * a_man * 2.0**a_exp
a32_fail = np.nonzero(self.finite_f32 != a_manual)[0]
if len(a32_fail) != 0:
bad_index = a32_fail[0]
assert_equal(self.finite_f32, a_manual,
"First non-equal is half value 0x%x -> %g != %g" %
(a_bits[bad_index],
self.finite_f32[bad_index],
a_manual[bad_index]))
a64_fail = np.nonzero(self.finite_f64 != a_manual)[0]
if len(a64_fail) != 0:
bad_index = a64_fail[0]
assert_equal(self.finite_f64, a_manual,
"First non-equal is half value 0x%x -> %g != %g" %
(a_bits[bad_index],
self.finite_f64[bad_index],
a_manual[bad_index]))
def test_half_ordering(self):
"""Make sure comparisons are working right"""
# All non-NaN float16 values in reverse order
a = self.nonan_f16[::-1].copy()
# 32-bit float copy
b = np.array(a, dtype=float32)
# Should sort the same
a.sort()
b.sort()
assert_equal(a, b)
# Comparisons should work
assert_((a[:-1] <= a[1:]).all())
assert_(not (a[:-1] > a[1:]).any())
assert_((a[1:] >= a[:-1]).all())
assert_(not (a[1:] < a[:-1]).any())
# All != except for +/-0
assert_equal(np.nonzero(a[:-1] < a[1:])[0].size, a.size-2)
assert_equal(np.nonzero(a[1:] > a[:-1])[0].size, a.size-2)
def test_half_funcs(self):
"""Test the various ArrFuncs"""
# fill
assert_equal(np.arange(10, dtype=float16),
np.arange(10, dtype=float32))
# fillwithscalar
a = np.zeros((5,), dtype=float16)
a.fill(1)
assert_equal(a, np.ones((5,), dtype=float16))
# nonzero and copyswap
a = np.array([0, 0, -1, -1/1e20, 0, 2.0**-24, 7.629e-6], dtype=float16)
assert_equal(a.nonzero()[0],
[2, 5, 6])
a = a.byteswap()
a = a.view(a.dtype.newbyteorder())
assert_equal(a.nonzero()[0],
[2, 5, 6])
# dot
a = np.arange(0, 10, 0.5, dtype=float16)
b = np.ones((20,), dtype=float16)
assert_equal(np.dot(a, b),
95)
# argmax
a = np.array([0, -np.inf, -2, 0.5, 12.55, 7.3, 2.1, 12.4], dtype=float16)
assert_equal(a.argmax(),
4)
a = np.array([0, -np.inf, -2, np.inf, 12.55, np.nan, 2.1, 12.4], dtype=float16)
assert_equal(a.argmax(),
5)
# getitem
a = np.arange(10, dtype=float16)
for i in range(10):
assert_equal(a.item(i), i)
def test_spacing_nextafter(self):
"""Test np.spacing and np.nextafter"""
# All non-negative finite #'s
a = np.arange(0x7c00, dtype=uint16)
hinf = np.array((np.inf,), dtype=float16)
hnan = np.array((np.nan,), dtype=float16)
a_f16 = a.view(dtype=float16)
assert_equal(np.spacing(a_f16[:-1]), a_f16[1:]-a_f16[:-1])
assert_equal(np.nextafter(a_f16[:-1], hinf), a_f16[1:])
assert_equal(np.nextafter(a_f16[0], -hinf), -a_f16[1])
assert_equal(np.nextafter(a_f16[1:], -hinf), a_f16[:-1])
assert_equal(np.nextafter(hinf, a_f16), a_f16[-1])
assert_equal(np.nextafter(-hinf, a_f16), -a_f16[-1])
assert_equal(np.nextafter(hinf, hinf), hinf)
assert_equal(np.nextafter(hinf, -hinf), a_f16[-1])
assert_equal(np.nextafter(-hinf, hinf), -a_f16[-1])
assert_equal(np.nextafter(-hinf, -hinf), -hinf)
assert_equal(np.nextafter(a_f16, hnan), hnan[0])
assert_equal(np.nextafter(hnan, a_f16), hnan[0])
assert_equal(np.nextafter(hnan, hnan), hnan)
assert_equal(np.nextafter(hinf, hnan), hnan)
assert_equal(np.nextafter(hnan, hinf), hnan)
# switch to negatives
a |= 0x8000
assert_equal(np.spacing(a_f16[0]), np.spacing(a_f16[1]))
assert_equal(np.spacing(a_f16[1:]), a_f16[:-1]-a_f16[1:])
assert_equal(np.nextafter(a_f16[0], hinf), -a_f16[1])
assert_equal(np.nextafter(a_f16[1:], hinf), a_f16[:-1])
assert_equal(np.nextafter(a_f16[:-1], -hinf), a_f16[1:])
assert_equal(np.nextafter(hinf, a_f16), -a_f16[-1])
assert_equal(np.nextafter(-hinf, a_f16), a_f16[-1])
assert_equal(np.nextafter(a_f16, hnan), hnan[0])
assert_equal(np.nextafter(hnan, a_f16), hnan[0])
def test_half_ufuncs(self):
"""Test the various ufuncs"""
a = np.array([0, 1, 2, 4, 2], dtype=float16)
b = np.array([-2, 5, 1, 4, 3], dtype=float16)
c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)
assert_equal(np.add(a, b), [-2, 6, 3, 8, 5])
assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1])
assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6])
assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625])
assert_equal(np.equal(a, b), [False, False, False, True, False])
assert_equal(np.not_equal(a, b), [True, True, True, False, True])
assert_equal(np.less(a, b), [False, True, False, False, True])
assert_equal(np.less_equal(a, b), [False, True, False, True, True])
assert_equal(np.greater(a, b), [True, False, True, False, False])
assert_equal(np.greater_equal(a, b), [True, False, True, True, False])
assert_equal(np.logical_and(a, b), [False, True, True, True, True])
assert_equal(np.logical_or(a, b), [True, True, True, True, True])
assert_equal(np.logical_xor(a, b), [True, False, False, False, False])
assert_equal(np.logical_not(a), [True, False, False, False, False])
assert_equal(np.isnan(c), [False, False, False, True, False])
assert_equal(np.isinf(c), [False, False, True, False, False])
assert_equal(np.isfinite(c), [True, True, False, False, True])
assert_equal(np.signbit(b), [True, False, False, False, False])
assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3])
assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3])
x = np.maximum(b, c)
assert_(np.isnan(x[3]))
x[3] = 0
assert_equal(x, [0, 5, 1, 0, 6])
assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2])
x = np.minimum(b, c)
assert_(np.isnan(x[3]))
x[3] = 0
assert_equal(x, [-2, -1, -np.inf, 0, 3])
assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3])
assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6])
assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2])
assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3])
assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0])
assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2])
assert_equal(np.divmod(a, b), ([0, 0, 2, 1, 0], [0, 1, 0, 0, 2]))
assert_equal(np.square(b), [4, 25, 1, 16, 9])
assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125])
assert_equal(np.ones_like(b), [1, 1, 1, 1, 1])
assert_equal(np.conjugate(b), b)
assert_equal(np.absolute(b), [2, 5, 1, 4, 3])
assert_equal(np.negative(b), [2, -5, -1, -4, -3])
assert_equal(np.positive(b), b)
assert_equal(np.sign(b), [-1, 1, 1, 1, 1])
assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b))
assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2]))
assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
def test_half_coercion(self):
"""Test that half gets coerced properly with the other types"""
a16 = np.array((1,), dtype=float16)
a32 = np.array((1,), dtype=float32)
b16 = float16(1)
b32 = float32(1)
assert np.power(a16, 2).dtype == float16
assert np.power(a16, 2.0).dtype == float16
assert np.power(a16, b16).dtype == float16
assert np.power(a16, b32).dtype == float32
assert np.power(a16, a16).dtype == float16
assert np.power(a16, a32).dtype == float32
assert np.power(b16, 2).dtype == float16
assert np.power(b16, 2.0).dtype == float16
assert np.power(b16, b16).dtype, float16
assert np.power(b16, b32).dtype, float32
assert np.power(b16, a16).dtype, float16
assert np.power(b16, a32).dtype, float32
assert np.power(a32, a16).dtype == float32
assert np.power(a32, b16).dtype == float32
assert np.power(b32, a16).dtype == float32
assert np.power(b32, b16).dtype == float32
@pytest.mark.skipif(platform.machine() == "armv5tel",
reason="See gh-413.")
@pytest.mark.skipif(IS_WASM,
reason="fp exceptions don't work in wasm.")
def test_half_fpe(self):
with np.errstate(all='raise'):
sx16 = np.array((1e-4,), dtype=float16)
bx16 = np.array((1e4,), dtype=float16)
sy16 = float16(1e-4)
by16 = float16(1e4)
# Underflow errors
assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sx16)
assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sy16)
assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sx16)
assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sy16)
assert_raises_fpe('underflow', lambda a, b:a/b, sx16, bx16)
assert_raises_fpe('underflow', lambda a, b:a/b, sx16, by16)
assert_raises_fpe('underflow', lambda a, b:a/b, sy16, bx16)
assert_raises_fpe('underflow', lambda a, b:a/b, sy16, by16)
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14), float16(2**11))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(-2.**-14), float16(2**11))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14+2**-24), float16(2))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(-2.**-14-2**-24), float16(2))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14+2**-23), float16(4))
# Overflow errors
assert_raises_fpe('overflow', lambda a, b:a*b, bx16, bx16)
assert_raises_fpe('overflow', lambda a, b:a*b, bx16, by16)
assert_raises_fpe('overflow', lambda a, b:a*b, by16, bx16)
assert_raises_fpe('overflow', lambda a, b:a*b, by16, by16)
assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sx16)
assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sy16)
assert_raises_fpe('overflow', lambda a, b:a/b, by16, sx16)
assert_raises_fpe('overflow', lambda a, b:a/b, by16, sy16)
assert_raises_fpe('overflow', lambda a, b:a+b,
float16(65504), float16(17))
assert_raises_fpe('overflow', lambda a, b:a-b,
float16(-65504), float16(17))
assert_raises_fpe('overflow', np.nextafter, float16(65504), float16(np.inf))
assert_raises_fpe('overflow', np.nextafter, float16(-65504), float16(-np.inf))
assert_raises_fpe('overflow', np.spacing, float16(65504))
# Invalid value errors
assert_raises_fpe('invalid', np.divide, float16(np.inf), float16(np.inf))
assert_raises_fpe('invalid', np.spacing, float16(np.inf))
assert_raises_fpe('invalid', np.spacing, float16(np.nan))
# These should not raise
float16(65472)+float16(32)
float16(2**-13)/float16(2)
float16(2**-14)/float16(2**10)
np.spacing(float16(-65504))
np.nextafter(float16(65504), float16(-np.inf))
np.nextafter(float16(-65504), float16(np.inf))
np.nextafter(float16(np.inf), float16(0))
np.nextafter(float16(-np.inf), float16(0))
np.nextafter(float16(0), float16(np.nan))
np.nextafter(float16(np.nan), float16(0))
float16(2**-14)/float16(2**10)
float16(-2**-14)/float16(2**10)
float16(2**-14+2**-23)/float16(2)
float16(-2**-14-2**-23)/float16(2)
def test_half_array_interface(self):
"""Test that half is compatible with __array_interface__"""
class Dummy:
pass
a = np.ones((1,), dtype=float16)
b = Dummy()
b.__array_interface__ = a.__array_interface__
c = np.array(b)
assert_(c.dtype == float16)
assert_equal(a, c)
|
numpyREPO_NAMEnumpyPATH_START.@numpy_extracted@numpy-main@numpy@_core@tests@test_half.py@.PATH_END.py
|
{
"filename": "_shadow.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scatterpolar/legendgrouptitle/font/_shadow.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class ShadowValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="shadow",
parent_name="scatterpolar.legendgrouptitle.font",
**kwargs,
):
super(ShadowValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scatterpolar@legendgrouptitle@font@_shadow.py@.PATH_END.py
|
{
"filename": "test_stat_moments.py",
"repo_name": "Astroua/TurbuStat",
"repo_path": "TurbuStat_extracted/TurbuStat-master/turbustat/tests/test_stat_moments.py",
"type": "Python"
}
|
# Licensed under an MIT open source license - see LICENSE
from __future__ import print_function, absolute_import, division
import pytest
import numpy as np
import numpy.testing as npt
import astropy.units as u
import os
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_moments():
tester = StatMoments(dataset1["moment0"])
tester.run(verbose=True, save_name='test.png')
os.system("rm test.png")
assert np.allclose(tester.kurtosis_hist[1],
computed_data['kurtosis_nondist_val'])
assert np.allclose(tester.skewness_hist[1],
computed_data['skewness_nondist_val'])
# TODO: Add more test comparisons. Save the total moments over the whole
# arrays, portions of the local arrays, and the histogram values.
# Test loading and saving
tester.save_results("statmom_output.pkl", keep_data=False)
saved_tester = StatMoments.load_results("statmom_output.pkl")
# Remove the file
os.remove("statmom_output.pkl")
assert np.allclose(saved_tester.kurtosis_hist[1],
computed_data['kurtosis_nondist_val'])
assert np.allclose(saved_tester.skewness_hist[1],
computed_data['skewness_nondist_val'])
def test_moments_units():
distance = 250 * u.pc
radius = 5 * u.pix
tester = StatMoments(dataset1["moment0"], radius=radius)
tester.run()
# Angular units
radius = radius.value * dataset1['moment0'][1]['CDELT2'] * u.deg
tester2 = StatMoments(dataset1["moment0"], radius=radius)
tester2.run()
# Physical units
radius = radius.to(u.rad).value * distance
tester3 = StatMoments(dataset1["moment0"], radius=radius,
distance=distance)
tester3.run()
npt.assert_allclose(tester.mean, tester2.mean)
npt.assert_allclose(tester.mean, tester3.mean)
npt.assert_allclose(tester.variance, tester2.variance)
npt.assert_allclose(tester.variance, tester3.variance)
npt.assert_allclose(tester.skewness, tester2.skewness)
npt.assert_allclose(tester.skewness, tester3.skewness)
npt.assert_allclose(tester.kurtosis, tester2.kurtosis)
npt.assert_allclose(tester.kurtosis, tester3.kurtosis)
def test_moments_nonperiodic():
tester = StatMoments(dataset1["moment0"])
tester.run(periodic=False)
assert np.allclose(tester.kurtosis_hist[1],
computed_data['kurtosis_nonper_val'])
assert np.allclose(tester.skewness_hist[1],
computed_data['skewness_nonper_val'])
def test_moment_distance():
tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
tester_dist.distance_metric(verbose=True, save_name='test.png')
os.system("rm test.png")
assert np.allclose(tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist.skewness_distance,
computed_distances['skewness_distance'])
# With StatMoments classes as inputs
tester_dist2 = \
StatMoments_Distance(tester_dist.moments1,
tester_dist.moments2)
tester_dist2.distance_metric()
assert np.allclose(tester_dist2.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist2.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist2.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist2.skewness_distance,
computed_distances['skewness_distance'])
# With fresh StatMoments classes
tester = StatMoments(dataset1["moment0"])
tester2 = StatMoments(dataset2["moment0"])
tester_dist3 = \
StatMoments_Distance(tester,
tester2)
tester_dist3.distance_metric()
assert np.allclose(tester_dist3.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist3.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist3.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist3.skewness_distance,
computed_distances['skewness_distance'])
|
AstrouaREPO_NAMETurbuStatPATH_START.@TurbuStat_extracted@TurbuStat-master@turbustat@tests@test_stat_moments.py@.PATH_END.py
|
{
"filename": "ImagingReduction.py",
"repo_name": "avigan/SPHERE",
"repo_path": "SPHERE_extracted/SPHERE-master/sphere/IRDIS/ImagingReduction.py",
"type": "Python"
}
|
import pandas as pd
import subprocess
import logging
import numpy as np
import shutil
import configparser
import collections
from pathlib import Path
from astropy.io import fits
import sphere
import sphere.utils as utils
import sphere.utils.imutils as imutils
import sphere.utils.toolbox as toolbox
import sphere.utils.transmission as transmission
_log = logging.getLogger(__name__)
class ImagingReduction(object):
'''
SPHERE/IRDIS imaging reduction class. It handles both the
dual-band imaging (DBI) and classical imaging (CI) observing
modes.
'''
##################################################
# Class variables
##################################################
# specify for each recipe which other recipes need to have been executed before
recipe_requirements = collections.OrderedDict([
('sort_files', []),
('sort_frames', ['sort_files']),
('check_files_association', ['sort_files']),
('sph_ird_cal_dark', ['sort_files']),
('sph_ird_cal_detector_flat', ['sort_files']),
('sph_ird_preprocess_science', ['sort_files', 'sort_frames', 'sph_ird_cal_dark',
'sph_ird_cal_detector_flat']),
('sph_ird_star_center', ['sort_files', 'sort_frames', 'sph_ird_preprocess_science']),
('sph_ird_combine_data', ['sort_files', 'sort_frames', 'sph_ird_preprocess_science']),
('sph_ird_clean', [])
])
##################################################
# Constructor
##################################################
def __new__(cls, path, clean_start=True, log_level='info', user_config=None, sphere_handler=None):
'''Custom instantiation for the class and initialization for the
instances
The customized instantiation enables to check that the
provided path is a valid reduction path. If not, None will be
returned for the reduction being created. Otherwise, an
instance is created and returned at the end.
Parameters
----------
path : str
Path to the directory containing the dataset
clean_start : bool
Remove all results from previous reductions for a clean start.
Default is True
log_level : {'debug', 'info', 'warning', 'error', 'critical'}
The log level of the handler
user_config : str
Path to a user-provided configuration. Default is None, i.e. the
reduction will use the package default configuration parameters
sphere_handler : log handler
Higher-level SPHERE.Dataset log handler
'''
#
# make sure we are dealing with a proper reduction directory
#
# init path
path = Path(path).expanduser().resolve()
# zeroth-order reduction validation
raw = path / 'raw'
if not raw.exists():
_log.error(f'No raw/ subdirectory. {path} is not a valid reduction path')
return None
else:
# it's all good: create instance!
reduction = super(ImagingReduction, cls).__new__(cls)
#
# basic init
#
# init path
reduction._path = utils.ReductionPath(path)
# instrument and mode
reduction._instrument = 'IRDIS'
reduction._mode = 'Unknown'
#
# logging
#
logger = logging.getLogger(str(path))
logger.setLevel(log_level.upper())
if logger.hasHandlers():
for hdlr in logger.handlers:
logger.removeHandler(hdlr)
handler = logging.FileHandler(reduction._path.products / 'reduction.log', mode='w', encoding='utf-8')
formatter = logging.Formatter('%(asctime)s\t%(levelname)8s\t%(message)s')
formatter.default_msec_format = '%s.%03d'
handler.setFormatter(formatter)
logger.addHandler(handler)
if sphere_handler:
logger.addHandler(sphere_handler)
reduction._logger = logger
reduction._logger.info(f'Creating IRDIS imaging reduction at path {path}')
#
# v1.4 - True North correction change
#
reduction._logger.warning('##################################################################')
reduction._logger.warning('Since version 1.4 of the pipeline, the default -1.75° true North ')
reduction._logger.warning('offset is automatically added to the derotation angles. The offset')
reduction._logger.warning('value can be modified in the configuration of the reduction: ')
reduction._logger.warning(' ')
reduction._logger.warning(' >>> reduction.config[\'cal_true_north\'] = xxx ')
reduction._logger.warning(' ')
reduction._logger.warning('To avoid any issues, make sure to: ')
reduction._logger.warning(' * either reprocess data previously processed with version <1.4 ')
reduction._logger.warning(' * or take into account the offset in your astrometric analysis ')
reduction._logger.warning('##################################################################')
#
# clean start
#
if clean_start:
reduction._logger.info('Erase outputs of previous reduction for a clean start')
reduction._path.remove(delete_raw=False, delete_products=True, logger=reduction._logger)
config_file = reduction._path.root / 'reduction_config.ini'
if config_file.exists():
config_file.unlink()
#
# configuration
#
cfgfile = f'{Path(sphere.__file__).parent}/instruments/{reduction._instrument}.ini'
cfgparser = configparser.ConfigParser()
reduction._logger.debug('> read default configuration')
cfgparser.read(cfgfile)
# instrument
reduction._pixel = float(cfgparser.get('instrument', 'pixel'))
reduction._nwave = 2
# calibration
reduction._wave_cal_lasers = np.array(eval(cfgparser.get('calibration', 'wave_cal_lasers')))
# imaging calibration
reduction._default_center = np.array(eval(cfgparser.get('calibration-imaging', 'default_center')))
reduction._orientation_offset = eval(cfgparser.get('calibration-imaging', 'orientation_offset'))
# reduction parameters
cfg = {}
for group in ['reduction', 'reduction-imaging']:
items = dict(cfgparser.items(group))
for key, value in items.items():
try:
val = eval(value)
except NameError:
val = value
cfg[key] = val
reduction._config = utils.Configuration(reduction._path, reduction._logger, cfg)
# load user-provided default configuration parameters
if user_config:
user_config = Path(user_config).expanduser()
reduction._config.load_from_file(user_config)
#
# reduction and recipes status
#
reduction._status = sphere.INIT
reduction._recipes_status = collections.OrderedDict()
for recipe in reduction.recipe_requirements.keys():
reduction._update_recipe_status(recipe, sphere.NOTSET)
# reload any existing data frames
reduction._read_info()
#
# return instance
#
return reduction
##################################################
# Representation
##################################################
def __repr__(self):
return f'<ImagingReduction, instrument={self._instrument}, mode={self._mode}, path={self._path}, log={self.loglevel}>'
def __format__(self):
return self.__repr__()
##################################################
# Properties
##################################################
@property
def loglevel(self):
return logging.getLevelName(self._logger.level)
@loglevel.setter
def loglevel(self, level):
self._logger.setLevel(level.upper())
@property
def instrument(self):
return self._instrument
@property
def pixel(self):
return self._pixel
@property
def nwave(self):
return self._nwave
@property
def path(self):
return self._path
@property
def files_info(self):
return self._files_info
@property
def frames_info(self):
return self._frames_info
@property
def frames_info_preproc(self):
return self._frames_info_preproc
@property
def recipes_status(self):
return self._recipes_status
@property
def status(self):
return self._status
@property
def config(self):
return self._config
@property
def mode(self):
return self._mode
##################################################
# Generic class methods
##################################################
def init_reduction(self):
'''
Sort files and frames, perform sanity check
'''
self._logger.info('====> Init <====')
self.sort_files()
self.sort_frames()
self.check_files_association()
def create_static_calibrations(self):
'''
Create static calibrations with esorex
'''
self._logger.info('====> Static calibrations <====')
config = self.config
self.sph_ird_cal_dark(silent=config['misc_silent_esorex'])
self.sph_ird_cal_detector_flat(silent=config['misc_silent_esorex'])
def preprocess_science(self):
'''
Clean and collapse images
'''
self._logger.info('====> Science pre-processing <====')
config = self.config
self.sph_ird_preprocess_science(subtract_background=config['preproc_subtract_background'],
fix_badpix=config['preproc_fix_badpix'],
collapse_science=config['preproc_collapse_science'],
collapse_type=config['preproc_collapse_type'],
coadd_value=config['preproc_coadd_value'],
collapse_psf=config['preproc_collapse_psf'],
collapse_center=config['preproc_collapse_center'])
def process_science(self):
'''
Perform star center, combine cubes into final (x,y,time,lambda)
cubes, correct anamorphism and scale the images
'''
self._logger.info('====> Science processing <====')
config = self.config
self.sph_ird_star_center(high_pass_psf=config['center_high_pass_psf'],
high_pass_waffle=config['center_high_pass_waffle'],
offset=config['center_offset'],
box_psf=config['center_box_psf'],
box_waffle=config['center_box_waffle'],
plot=config['misc_plot'])
self.sph_ird_combine_data(cpix=config['combine_cpix'],
psf_dim=config['combine_psf_dim'],
science_dim=config['combine_science_dim'],
correct_anamorphism=config['combine_correct_anamorphism'],
manual_center=config['combine_manual_center'],
center_selection=config['combine_center_selection'],
coarse_centering=config['combine_coarse_centering'],
shift_method=config['combine_shift_method'],
save_scaled=config['combine_save_scaled'])
def clean(self):
'''
Clean the reduction directory, leaving only the raw and products
sub-directory
'''
self._logger.info('====> Clean-up <====')
config = self.config
if config['clean']:
self.sph_ird_clean(delete_raw=config['clean_delete_raw'],
delete_products=config['clean_delete_products'],
delete_config=config['clean_delete_config'])
def full_reduction(self):
'''
Performs a full reduction of a data set, from the static
calibrations to the final (x,y,time,lambda) cubes
'''
self._logger.info('====> Full reduction <====')
self.init_reduction()
self.create_static_calibrations()
self.preprocess_science()
self.process_science()
self.clean()
##################################################
# Private methods
##################################################
def _read_info(self):
'''
Read the files, calibs and frames information from disk
files_info : dataframe
The data frame with all the information on files
frames_info : dataframe
The data frame with all the information on science frames
frames_info_preproc : dataframe
The data frame with all the information on science frames after pre-processing
This function is not supposed to be called directly by the user.
'''
self._logger.info('Read existing reduction information')
# path
path = self.path
# load existing configuration
self.config.load()
# files info
fname = path.preproc / 'files.csv'
if fname.exists():
self._logger.debug('> read files.csv')
files_info = pd.read_csv(fname, index_col=0)
# convert times
files_info['DATE-OBS'] = pd.to_datetime(files_info['DATE-OBS'], utc=False)
files_info['DATE'] = pd.to_datetime(files_info['DATE'], utc=False)
files_info['DET FRAM UTC'] = pd.to_datetime(files_info['DET FRAM UTC'], utc=False)
# recipe execution status
self._update_recipe_status('sort_files', sphere.SUCCESS)
if np.any(files_info['PRO CATG'] == 'IRD_MASTER_DARK'):
self._update_recipe_status('sph_ird_cal_dark', sphere.SUCCESS)
if np.any(files_info['PRO CATG'] == 'IRD_FLAT_FIELD'):
self._update_recipe_status('sph_ird_cal_detector_flat', sphere.SUCCESS)
# update instrument mode
self._mode = files_info.loc[files_info['DPR CATG'] == 'SCIENCE', 'INS1 MODE'].iloc[0]
else:
files_info = None
fname = path.preproc / 'frames.csv'
if fname.exists():
self._logger.debug('> read frames.csv')
frames_info = pd.read_csv(fname, index_col=(0, 1))
# convert times
frames_info['DATE-OBS'] = pd.to_datetime(frames_info['DATE-OBS'], utc=False)
frames_info['DATE'] = pd.to_datetime(frames_info['DATE'], utc=False)
frames_info['DET FRAM UTC'] = pd.to_datetime(frames_info['DET FRAM UTC'], utc=False)
frames_info['TIME START'] = pd.to_datetime(frames_info['TIME START'], utc=False)
frames_info['TIME'] = pd.to_datetime(frames_info['TIME'], utc=False)
frames_info['TIME END'] = pd.to_datetime(frames_info['TIME END'], utc=False)
# recipe execution status
self._update_recipe_status('sort_frames', sphere.SUCCESS)
else:
frames_info = None
fname = path.preproc / 'frames_preproc.csv'
if fname.exists():
self._logger.debug('> read frames_preproc.csv')
frames_info_preproc = pd.read_csv(fname, index_col=(0, 1))
# convert times
frames_info_preproc['DATE-OBS'] = pd.to_datetime(frames_info_preproc['DATE-OBS'], utc=False)
frames_info_preproc['DATE'] = pd.to_datetime(frames_info_preproc['DATE'], utc=False)
frames_info_preproc['DET FRAM UTC'] = pd.to_datetime(frames_info_preproc['DET FRAM UTC'], utc=False)
frames_info_preproc['TIME START'] = pd.to_datetime(frames_info_preproc['TIME START'], utc=False)
frames_info_preproc['TIME'] = pd.to_datetime(frames_info_preproc['TIME'], utc=False)
frames_info_preproc['TIME END'] = pd.to_datetime(frames_info_preproc['TIME END'], utc=False)
else:
frames_info_preproc = None
# save data frames in instance variables
self._files_info = files_info
self._frames_info = frames_info
self._frames_info_preproc = frames_info_preproc
# additional checks to recipe execution status
if frames_info_preproc is not None:
done = True
files = frames_info_preproc.index
for file, idx in files:
fname = f'{file}_DIT{idx:03d}_preproc'
file = list(path.preproc.glob(f'{fname}.fits'))
done = done and (len(file) == 1)
if done:
self._update_recipe_status('sph_ird_preprocess_science', sphere.SUCCESS)
self._logger.debug(f'> sph_ird_preprocess_science status = {done}')
done = True
files = frames_info_preproc[(frames_info_preproc['DPR TYPE'] == 'OBJECT,FLUX') |
(frames_info_preproc['DPR TYPE'] == 'OBJECT,CENTER')].index
for file, idx in files:
fname = f'{file}_DIT{idx:03d}_preproc_centers'
file = list(path.preproc.glob(f'{fname}.fits'))
done = done and (len(file) == 1)
if done:
self._update_recipe_status('sph_ird_star_center', sphere.SUCCESS)
self._logger.debug(f'> sph_ird_star_center status = {done}')
# reduction status
self._status = sphere.INCOMPLETE
def _update_recipe_status(self, recipe, status):
'''Update execution status for reduction and recipe
Parameters
----------
recipe : str
Recipe name
status : sphere status (int)
Status of the recipe. Can be either one of sphere.NOTSET,
sphere.SUCCESS or sphere.ERROR
'''
self._logger.debug('> update recipe execution')
self._recipes_status[recipe] = status
##################################################
# SPHERE/IRDIS methods
##################################################
def sort_files(self):
'''
Sort all raw files and save result in a data frame
files_info : dataframe
Data frame with the information on raw files
'''
self._logger.info('Sort raw files')
# recipe execution status
self._update_recipe_status('sort_files', sphere.NOTSET)
# parameters
path = self.path
# list files
files = path.raw.glob('*.fits')
files = [f.stem for f in files]
if len(files) == 0:
self._logger.critical('No raw FITS files in reduction path')
self._update_recipe_status('sort_files', sphere.ERROR)
self._status = sphere.FATAL
return
self._logger.info(f' * found {len(files)} raw FITS files')
# read list of keywords
self._logger.debug('> read keyword list')
keywords = []
file = open(Path(sphere.__file__).parent / 'instruments' / 'keywords_irdifs.dat', 'r')
for line in file:
line = line.strip()
if line:
if line[0] != '#':
keywords.append(line)
file.close()
# short keywords
self._logger.debug('> translate into short keywords')
keywords_short = keywords.copy()
for idx in range(len(keywords_short)):
key = keywords_short[idx]
if key.find('HIERARCH ESO ') != -1:
keywords_short[idx] = key[13:]
# files table
self._logger.debug('> create files_info data frame')
files_info = pd.DataFrame(index=pd.Index(files, name='FILE'), columns=keywords_short)
self._logger.debug('> read FITS keywords')
for f in files:
hdu = fits.open(path.raw / f'{f}.fits')
hdr = hdu[0].header
for k, sk in zip(keywords, keywords_short):
if k == 'HIERARCH ESO INS4 DROT2 BEGIN':
# in June 2021 ESO changed INS4 DROT2 BEGIN to INS4 DROT2 START
v_begin = hdr.get('HIERARCH ESO INS4 DROT2 BEGIN')
v_start = hdr.get('HIERARCH ESO INS4 DROT2 START')
files_info.loc[f, sk] = v_begin if v_begin else v_start
elif k == 'HIERARCH ESO INS4 DROT3 BEGIN':
# in June 2021 ESO changed INS4 DROT3 BEGIN to INS4 DROT3 START
v_begin = hdr.get('HIERARCH ESO INS4 DROT3 BEGIN')
v_start = hdr.get('HIERARCH ESO INS4 DROT3 START')
files_info.loc[f, sk] = v_begin if v_begin else v_start
else:
files_info.loc[f, sk] = hdr.get(k)
hdu.close()
# make sure some columns are float
float_columns = ['DET SEQ1 DIT', 'DET NDIT', 'OBS ID', 'DET DITDELAY', 'INS4 DROT2 RA', 'INS4 DROT2 DEC', 'TEL ALT', 'TEL AZ',
'INS4 DROT2 BEGIN', 'INS4 DROT2 END', 'INS4 DROT2 POSANG', 'INS4 DROT3 BEGIN', 'INS4 DROT3 END', 'INS4 DROT3 POSANG',
'INS1 PAC X', 'INS1 PAC Y', 'TEL AIRM START', 'TEL AIRM END', 'TEL AMBI FWHM START', 'TEL AMBI FWHM END', 'TEL IA FWHM',
'TEL AMBI TAU0', 'TEL AMBI TEMP', 'TEL AMBI WINDSP', 'TEL AMBI WINDDIR']
for col in float_columns:
files_info[col] = files_info[col].astype(float)
# drop files that are not handled, based on DPR keywords
self._logger.debug('> drop unsupported file types')
files_info.dropna(subset=['DPR TYPE'], inplace=True)
files_info = files_info[(files_info['DPR CATG'] != 'ACQUISITION') & (files_info['DPR TYPE'] != 'OBJECT,AO')]
# check instruments
instru = files_info['SEQ ARM'].unique()
if len(instru) != 1:
self._logger.critical(f'Sequence is mixing different instruments: {instru}')
self._update_recipe_status('sort_files', sphere.ERROR)
self._status = sphere.FATAL
return
# check science files
sci_files = files_info[(files_info['DPR CATG'] == 'SCIENCE') & (files_info['DPR TYPE'] != 'SKY')]
if len(sci_files) == 0:
self._logger.critical('This dataset contains no science frame. There should be at least one!')
self._update_recipe_status('sort_frames', sphere.ERROR)
self._status = sphere.FATAL
return
# processed column
files_info.insert(len(files_info.columns), 'PROCESSED', False)
files_info.insert(len(files_info.columns), 'PRO CATG', ' ')
# convert times
self._logger.debug('> convert times')
files_info['DATE-OBS'] = pd.to_datetime(files_info['DATE-OBS'], utc=False)
files_info['DATE'] = pd.to_datetime(files_info['DATE'], utc=False)
files_info['DET FRAM UTC'] = pd.to_datetime(files_info['DET FRAM UTC'], utc=False)
# update instrument mode
self._mode = files_info.loc[files_info['DPR CATG'] == 'SCIENCE', 'INS1 MODE'].iloc[0]
# sort by acquisition time
files_info.sort_values(by='DATE-OBS', inplace=True)
# save files_info
self._logger.debug('> save files.csv')
files_info.to_csv(path.preproc / 'files.csv')
self._files_info = files_info
# recipe execution status
self._update_recipe_status('sort_files', sphere.SUCCESS)
# reduction status
self._status = sphere.INCOMPLETE
def sort_frames(self):
'''
Extract the frames information from the science files and save
result in a data frame
calibs : dataframe
A data frame with the information on all frames
'''
self._logger.info('Extract frames information')
# check if recipe can be executed
if not toolbox.recipe_executable(self._recipes_status, self._status, 'sort_frames',
self.recipe_requirements, logger=self._logger):
return
# parameters
path = self.path
files_info = self.files_info
# science files
sci_files = files_info[(files_info['DPR CATG'] == 'SCIENCE') & (files_info['DPR TYPE'] != 'SKY')]
# build indices
files = []
img = []
for file, finfo in sci_files.iterrows():
NDIT = int(finfo['DET NDIT'])
files.extend(np.repeat(file, NDIT))
img.extend(list(np.arange(NDIT)))
# create new dataframe
self._logger.debug('> create frames_info data frame')
frames_info = pd.DataFrame(columns=sci_files.columns, index=pd.MultiIndex.from_arrays([files, img], names=['FILE', 'IMG']))
# expand files_info into frames_info
frames_info = frames_info.align(files_info, level=0)[1]
# compute timestamps
toolbox.compute_times(frames_info, logger=self._logger)
# compute angles (ra, dec, parang)
true_north = self.config['cal_true_north']
ret = toolbox.compute_angles(frames_info, true_north, logger=self._logger)
if ret == sphere.ERROR:
self._update_recipe_status('sort_frames', sphere.ERROR)
self._status = sphere.FATAL
return
# save
self._logger.debug('> save frames.csv')
frames_info.to_csv(path.preproc / 'frames.csv')
self._frames_info = frames_info
#
# print some info
#
self._logger.debug('> print observation info')
cinfo = frames_info[frames_info['DPR TYPE'] == 'OBJECT']
if len(cinfo) == 0:
cinfo = frames_info[frames_info['DPR TYPE'] == 'OBJECT,CENTER']
ra_drot = cinfo['INS4 DROT2 RA'].iloc[0]
ra_drot_h = np.floor(ra_drot/1e4)
ra_drot_m = np.floor((ra_drot - ra_drot_h*1e4)/1e2)
ra_drot_s = ra_drot - ra_drot_h*1e4 - ra_drot_m*1e2
RA = f'{ra_drot_h:02.0f}:{ra_drot_m:02.0f}:{ra_drot_s:02.3f}'
dec_drot = cinfo['INS4 DROT2 DEC'].iloc[0]
sign = np.sign(dec_drot)
udec_drot = np.abs(dec_drot)
dec_drot_d = np.floor(udec_drot/1e4)
dec_drot_m = np.floor((udec_drot - dec_drot_d*1e4)/1e2)
dec_drot_s = udec_drot - dec_drot_d*1e4 - dec_drot_m*1e2
dec_drot_d *= sign
DEC = f'{dec_drot_d:02.0f}:{dec_drot_m:02.0f}:{dec_drot_s:02.2f}'
pa_start = cinfo['PARANG'].iloc[0]
pa_end = cinfo['PARANG'].iloc[-1]
posang = cinfo['INS4 DROT2 POSANG'].unique()
posangs = [f'{p:.2f}°' for p in posang]
date = str(cinfo['DATE'].iloc[0])[0:10]
self._logger.info(f" * Programme ID: {cinfo['OBS PROG ID'].iloc[0]}")
self._logger.info(f" * OB name: {cinfo['OBS NAME'].iloc[0]}")
self._logger.info(f" * OB ID: {cinfo['OBS ID'].iloc[0]}")
self._logger.info(f" * Object: {cinfo['OBJECT'].iloc[0]}")
self._logger.info(f' * RA / DEC: {RA} / {DEC}')
self._logger.info(f' * Date: {date}')
self._logger.info(f" * Instrument: {cinfo['SEQ ARM'].iloc[0]}")
self._logger.info(f" * Derotator: {cinfo['INS4 DROT2 MODE'].iloc[0]}")
self._logger.info(f" * VIS WFS mode: {cinfo['AOS VISWFS MODE'].iloc[0]}")
self._logger.info(f" * IR WFS mode: {cinfo['AOS IRWFS MODE'].iloc[0]}")
self._logger.info(f" * Coronagraph: {cinfo['INS COMB ICOR'].iloc[0]}")
self._logger.info(f" * Mode: {cinfo['INS1 MODE'].iloc[0]}")
self._logger.info(f" * Filter: {cinfo['INS COMB IFLT'].iloc[0]}")
self._logger.info(f" * DIT: {cinfo['DET SEQ1 DIT'].iloc[0]:.2f} sec")
self._logger.info(f" * NDIT: {cinfo['DET NDIT'].iloc[0]:.0f}")
self._logger.info(f" * Texp: {cinfo['DET SEQ1 DIT'].sum() / 60:.2f} min")
self._logger.info(f' * PA: {pa_start:.2f}° ==> {pa_end:.2f}° = {np.abs(pa_end - pa_start):.2f}°')
self._logger.info(f" * POSANG: {', '.join(posangs)}")
# recipe execution status
self._update_recipe_status('sort_frames', sphere.SUCCESS)
# reduction status
self._status = sphere.INCOMPLETE
def check_files_association(self):
'''
Performs the calibration files association as a sanity check.
Warnings and errors are reported at the end. Execution is
interupted in case of error.
'''
self._logger.info('File association for calibrations')
# check if recipe can be executed
if not toolbox.recipe_executable(self._recipes_status, self._status, 'check_files_association',
self.recipe_requirements, logger=self._logger):
return
# parameters
files_info = self.files_info
# instrument arm
arm = files_info['SEQ ARM'].unique()
if len(arm) != 1:
self._logger.error(f'Sequence is mixing different instruments: {arm}')
self._update_recipe_status('check_files_association', sphere.ERROR)
return
# IRDIS obs mode and filter combination
modes = files_info.loc[files_info['DPR CATG'] == 'SCIENCE', 'INS1 MODE'].unique()
if len(modes) != 1:
self._logger.error(f'Sequence is mixing different types of observations: {modes}')
self._update_recipe_status('check_files_association', sphere.ERROR)
return
filter_combs = files_info.loc[files_info['DPR CATG'] == 'SCIENCE', 'INS COMB IFLT'].unique()
if len(filter_combs) != 1:
self._logger.error(f'Sequence is mixing different types of filters combinations: {filter_combs}')
self._update_recipe_status('check_files_association', sphere.ERROR)
return
filter_comb = filter_combs[0]
# specific data frame for calibrations
# keep static calibrations and sky backgrounds
self._logger.debug('> select calib files')
calibs = files_info[(files_info['DPR CATG'] == 'CALIB') |
((files_info['DPR CATG'] == 'SCIENCE') & (files_info['DPR TYPE'] == 'SKY'))]
###############################################
# static calibrations not dependent on DIT
###############################################
error_flag = 0
warning_flag = 0
# flat
self._logger.debug('> check instrument flat requirements')
cfiles = calibs[(calibs['DPR TYPE'] == 'FLAT,LAMP') & (calibs['INS COMB IFLT'] == filter_comb)]
if len(cfiles) <= 1:
error_flag += 1
self._logger.error(f' * there should be more than 1 flat in filter combination {filter_comb}')
##################################################
# static calibrations that depend on science DIT
##################################################
self._logger.debug('> select science files')
obj = files_info.loc[files_info['DPR CATG'] == 'SCIENCE', 'DPR TYPE'].apply(lambda s: s[0:6])
DITs = files_info.loc[(files_info['DPR CATG'] == 'SCIENCE') & (obj == 'OBJECT'), 'DET SEQ1 DIT'].unique().round(2)
# handle darks in a slightly different way because there might be several different DITs
self._logger.debug('> check dark/background requirements')
for DIT in DITs:
# instrumental backgrounds
cfiles = calibs[((calibs['DPR TYPE'] == 'DARK') | (calibs['DPR TYPE'] == 'DARK,BACKGROUND')) &
(calibs['DET SEQ1 DIT'].round(2) == DIT)]
if len(cfiles) == 0:
warning_flag += 1
self._logger.warning(f' * there is no dark/background for science files with DIT={DIT} sec. It is *highly recommended* to include one to obtain the best data reduction. A single dark/background file is sufficient, and it can easily be downloaded from the ESO archive')
# sky backgrounds
cfiles = files_info[(files_info['DPR TYPE'] == 'SKY') & (files_info['DET SEQ1 DIT'].round(2) == DIT)]
if len(cfiles) == 0:
warning_flag += 1
self._logger.warning(f' * there is no sky background for science files with DIT={DIT} sec. Using a sky background instead of an internal instrumental background can usually provide a cleaner data reduction, especially in K-band')
# error reporting
self._logger.debug('> report status')
if error_flag:
self._logger.error(f'There are {warning_flag} warning(s) and {error_flag} error(s) in the classification of files')
self._update_recipe_status('check_files_association', sphere.ERROR)
return
else:
self._logger.warning(f'There are {warning_flag} warning(s) and {error_flag} error(s) in the classification of files')
# recipe execution status
self._update_recipe_status('check_files_association', sphere.SUCCESS)
# reduction status
self._status = sphere.INCOMPLETE
def sph_ird_cal_dark(self, silent=True):
'''
Create the dark and background calibrations
Parameters
----------
silent : bool
Suppress esorex output. Default is True
'''
self._logger.info('Darks and backgrounds')
# check if recipe can be executed
if not toolbox.recipe_executable(self._recipes_status, self._status, 'sph_ird_cal_dark',
self.recipe_requirements, logger=self._logger):
return
# parameters
path = self.path
files_info = self.files_info
# get list of files
calibs = files_info[np.logical_not(files_info['PROCESSED']) &
((files_info['DPR TYPE'] == 'DARK') |
(files_info['DPR TYPE'] == 'DARK,BACKGROUND') |
(files_info['DPR TYPE'] == 'SKY'))]
# loops on type and DIT value
types = ['DARK', 'DARK,BACKGROUND', 'SKY']
DITs = calibs['DET SEQ1 DIT'].unique().round(2)
filter_combs = calibs['INS COMB IFLT'].unique()
for ctype in types:
for DIT in DITs:
for cfilt in filter_combs:
cfiles = calibs[(calibs['DPR TYPE'] == ctype) & (calibs['DET SEQ1 DIT'].round(2) == DIT) &
(calibs['INS COMB IFLT'] == cfilt)]
files = cfiles.index
# skip non-existing combinations
if len(cfiles) == 0:
continue
self._logger.info(f' * {ctype} in filter {cfilt} with DIT={DIT:.2f} sec ({len(cfiles)} files)')
# create sof
self._logger.debug('> create sof file')
sof = path.sof / f'dark_filt={cfilt}_DIT={DIT:.2f}.sof'
file = open(sof, 'w')
for f in files:
file.write(f"{path.raw}/{f}.fits IRD_DARK_RAW\n")
file.close()
# products
if ctype == 'SKY':
loc = 'sky'
else:
loc = 'internal'
dark_file = f'dark_{loc}_filt={cfilt}_DIT={DIT:.2f}'
bpm_file = f'dark_{loc}_bpm_filt={cfilt}_DIT={DIT:.2f}'
# different max level in K-band
max_level = 1000
if cfilt in ['DB_K12', 'BB_Ks']:
max_level = 15000
# esorex parameters
args = ['esorex',
'--no-checksum=TRUE',
'--no-datamd5=TRUE',
'sph_ird_master_dark',
'--ird.master_dark.sigma_clip=5.0',
'--ird.master_dark.save_addprod=TRUE',
f'--ird.master_dark.max_acceptable={max_level}',
f'--ird.master_dark.outfilename={path.calib}/{dark_file}.fits',
f'--ird.master_dark.badpixfilename={path.calib}/{bpm_file}.fits',
str(sof)]
# check esorex
if shutil.which('esorex') is None:
self._logger.error('esorex does not appear to be in your PATH. Please make sure that the ESO pipeline is properly installed before running vlt-sphere.')
self._update_recipe_status('sph_ird_cal_dark', sphere.ERROR)
return
# execute esorex
self._logger.debug(f"> execute {' '.join(args)}")
if silent:
proc = subprocess.run(args, cwd=path.tmp, stdout=subprocess.DEVNULL)
else:
proc = subprocess.run(args, cwd=path.tmp)
if proc.returncode != 0:
self._logger.error('esorex process was not successful')
self._update_recipe_status('sph_ird_cal_dark', sphere.ERROR)
return
# store products
self._logger.debug('> update files_info data frame')
files_info.loc[dark_file, 'DPR CATG'] = cfiles['DPR CATG'].iloc[0]
files_info.loc[dark_file, 'DPR TYPE'] = cfiles['DPR TYPE'].iloc[0]
files_info.loc[dark_file, 'INS COMB IFLT'] = cfiles['INS COMB IFLT'].iloc[0]
files_info.loc[dark_file, 'INS4 FILT2 NAME'] = cfiles['INS4 FILT2 NAME'].iloc[0]
files_info.loc[dark_file, 'INS1 MODE'] = cfiles['INS1 MODE'].iloc[0]
files_info.loc[dark_file, 'INS1 FILT NAME'] = cfiles['INS1 FILT NAME'].iloc[0]
files_info.loc[dark_file, 'INS1 OPTI2 NAME'] = cfiles['INS1 OPTI2 NAME'].iloc[0]
files_info.loc[dark_file, 'DET SEQ1 DIT'] = cfiles['DET SEQ1 DIT'].iloc[0]
files_info.loc[dark_file, 'PROCESSED'] = True
files_info.loc[dark_file, 'PRO CATG'] = 'IRD_MASTER_DARK'
files_info.loc[bpm_file, 'DPR CATG'] = cfiles['DPR CATG'].iloc[0]
files_info.loc[bpm_file, 'DPR TYPE'] = cfiles['DPR TYPE'].iloc[0]
files_info.loc[bpm_file, 'INS COMB IFLT'] = cfiles['INS COMB IFLT'].iloc[0]
files_info.loc[bpm_file, 'INS4 FILT2 NAME'] = cfiles['INS4 FILT2 NAME'].iloc[0]
files_info.loc[bpm_file, 'INS1 MODE'] = cfiles['INS1 MODE'].iloc[0]
files_info.loc[bpm_file, 'INS1 FILT NAME'] = cfiles['INS1 FILT NAME'].iloc[0]
files_info.loc[bpm_file, 'INS1 OPTI2 NAME'] = cfiles['INS1 OPTI2 NAME'].iloc[0]
files_info.loc[bpm_file, 'PROCESSED'] = True
files_info.loc[bpm_file, 'PRO CATG'] = 'IRD_STATIC_BADPIXELMAP'
# save
self._logger.debug('> save files.csv')
files_info.to_csv(path.preproc / 'files.csv')
# recipe execution status
self._update_recipe_status('sph_ird_cal_dark', sphere.SUCCESS)
# reduction status
self._status = sphere.INCOMPLETE
def sph_ird_cal_detector_flat(self, silent=True):
'''
Create the detector flat calibrations
Parameters
----------
silent : bool
Suppress esorex output. Default is True
'''
self._logger.info('Instrument flats')
# check if recipe can be executed
if not toolbox.recipe_executable(self._recipes_status, self._status, 'sph_ird_cal_detector_flat',
self.recipe_requirements, logger=self._logger):
return
# parameters
path = self.path
files_info = self.files_info
# get list of files
calibs = files_info[np.logical_not(files_info['PROCESSED']) &
((files_info['DPR TYPE'] == 'FLAT,LAMP') |
(files_info['DPR TECH'] == 'IMAGE'))]
filter_combs = calibs['INS COMB IFLT'].unique()
for cfilt in filter_combs:
cfiles = calibs[calibs['INS COMB IFLT'] == cfilt]
files = cfiles.index
self._logger.info(f' * filter {cfilt} ({len(cfiles)} files)')
# create sof
self._logger.debug('> create sof file')
sof = path.sof / f'flat_filt={cfilt}.sof'
file = open(sof, 'w')
for f in files:
file.write(f"{path.raw}/{f}.fits IRD_FLAT_FIELD_RAW\n")
file.close()
# products
flat_file = f'flat_filt={cfilt}'
bpm_file = f'flat_bpm_filt={cfilt}'
# esorex parameters
args = ['esorex',
'--no-checksum=TRUE',
'--no-datamd5=TRUE',
'sph_ird_instrument_flat',
'--ird.instrument_flat.save_addprod=TRUE',
f'--ird.instrument_flat.outfilename={path.calib}/{flat_file}.fits',
f'--ird.instrument_flat.badpixfilename={path.calib}/{bpm_file}.fits',
str(sof)]
# check esorex
if shutil.which('esorex') is None:
self._logger.error('esorex does not appear to be in your PATH. Please make sure that the ESO pipeline is properly installed before running vlt-sphere.')
self._update_recipe_status('sph_ird_cal_detector_flat', sphere.ERROR)
return
# execute esorex
self._logger.debug(f"> execute {' '.join(args)}")
if silent:
proc = subprocess.run(args, cwd=path.tmp, stdout=subprocess.DEVNULL)
else:
proc = subprocess.run(args, cwd=path.tmp)
if proc.returncode != 0:
self._logger.error('esorex process was not successful')
self._update_recipe_status('sph_ird_cal_detector_flat', sphere.ERROR)
return
# store products
self._logger.debug('> update files_info data frame')
files_info.loc[flat_file, 'DPR CATG'] = cfiles['DPR CATG'].iloc[0]
files_info.loc[flat_file, 'DPR TYPE'] = cfiles['DPR TYPE'].iloc[0]
files_info.loc[flat_file, 'INS COMB IFLT'] = cfiles['INS COMB IFLT'].iloc[0]
files_info.loc[flat_file, 'INS4 FILT2 NAME'] = cfiles['INS4 FILT2 NAME'].iloc[0]
files_info.loc[flat_file, 'INS1 MODE'] = cfiles['INS1 MODE'].iloc[0]
files_info.loc[flat_file, 'INS1 FILT NAME'] = cfiles['INS1 FILT NAME'].iloc[0]
files_info.loc[flat_file, 'INS1 OPTI2 NAME'] = cfiles['INS1 OPTI2 NAME'].iloc[0]
files_info.loc[flat_file, 'DET SEQ1 DIT'] = cfiles['DET SEQ1 DIT'].iloc[0]
files_info.loc[flat_file, 'PROCESSED'] = True
files_info.loc[flat_file, 'PRO CATG'] = 'IRD_FLAT_FIELD'
files_info.loc[bpm_file, 'DPR CATG'] = cfiles['DPR CATG'].iloc[0]
files_info.loc[bpm_file, 'DPR TYPE'] = cfiles['DPR TYPE'].iloc[0]
files_info.loc[bpm_file, 'INS COMB IFLT'] = cfiles['INS COMB IFLT'].iloc[0]
files_info.loc[bpm_file, 'INS4 FILT2 NAME'] = cfiles['INS4 FILT2 NAME'].iloc[0]
files_info.loc[bpm_file, 'INS1 MODE'] = cfiles['INS1 MODE'].iloc[0]
files_info.loc[bpm_file, 'INS1 FILT NAME'] = cfiles['INS1 FILT NAME'].iloc[0]
files_info.loc[bpm_file, 'INS1 OPTI2 NAME'] = cfiles['INS1 OPTI2 NAME'].iloc[0]
files_info.loc[bpm_file, 'PROCESSED'] = True
files_info.loc[bpm_file, 'PRO CATG'] = 'IRD_NON_LINEAR_BADPIXELMAP'
# save
self._logger.debug('> save files.csv')
files_info.to_csv(path.preproc / 'files.csv')
# recipe execution status
self._update_recipe_status('sph_ird_cal_detector_flat', sphere.SUCCESS)
# reduction status
self._status = sphere.INCOMPLETE
def sph_ird_preprocess_science(self,
subtract_background=True, fix_badpix=True,
collapse_science=False, collapse_type='mean', coadd_value=2,
collapse_psf=True, collapse_center=True):
'''Pre-processes the science frames.
This function can perform multiple steps:
- collapse of the frames according to different schemes
- subtract the background
- correct bad pixels
- reformat IRDIS data in (x,y,lambda) cubes
For the science, 2 collapse methods are available: mean or
coadd. With mean, the full cubes are mean-combined into a single
frame. With coadd, the frames are coadded following the
coadd_value. This can result in lost frames if the number of NDIT
is not a multiple of coadd_value.
For the PSFs and star center frames, there is either no collapse
or a mean collapse.
The pre-processed frames are saved in the preproc
sub-directory and will be combined later.
Parameters
----------
subtract_background : bool
Performs background subtraction. Default is True
fix_badpix : bool
Performs correction of bad pixels. Default is True
collapse_science : bool
Collapse data for OBJECT cubes. Default is False
collapse_type : str
Type of collapse. Possible values are mean or coadd. Default
is mean.
coadd_value : int
Number of consecutive frames to be coadded when collapse_type
is coadd. Default is 2
collapse_psf : bool
Collapse data for OBJECT,FLUX cubes. Default is True. Note
that the collapse type is mean and cannot be changed.
collapse_center : bool
Collapse data for OBJECT,CENTER cubes. Default is True. Note
that the collapse type is mean and cannot be changed.
'''
self._logger.info('Pre-process science files')
# check if recipe can be executed
if not toolbox.recipe_executable(self._recipes_status, self._status, 'sph_ird_preprocess_science',
self.recipe_requirements, logger=self._logger):
return
# parameters
path = self.path
files_info = self.files_info
frames_info = self.frames_info
# clean before we start
self._logger.debug('> remove old preproc files')
files = path.preproc.glob('*_DIT???_preproc.fits')
for file in files:
file.unlink()
# filter combination
filter_comb = files_info.loc[files_info['DPR CATG'] == 'SCIENCE', 'INS COMB IFLT'].unique()[0]
# bpm
if fix_badpix:
bpm_files = files_info[(files_info['PRO CATG'] == 'IRD_STATIC_BADPIXELMAP') |
(files_info['PRO CATG'] == 'IRD_NON_LINEAR_BADPIXELMAP')].index
bpm_files = [path.calib / f'{f}.fits' for f in bpm_files]
if len(bpm_files) == 0:
self._logger.error('Could not fin any bad pixel maps')
self._update_recipe_status('sph_ird_preprocess_science', sphere.ERROR)
return
bpm = toolbox.compute_bad_pixel_map(bpm_files, logger=self._logger)
# mask dead regions
bpm[:15, :] = 0
bpm[1013:, :] = 0
bpm[:, :50] = 0
bpm[:, 941:1078] = 0
bpm[:, 1966:] = 0
# flat
flat_file = files_info[files_info['PROCESSED'] & (files_info['PRO CATG'] == 'IRD_FLAT_FIELD') &
(files_info['INS COMB IFLT'] == filter_comb)]
if len(flat_file) != 1:
self._logger.error(f'There should be exactly 1 flat file. Found {len(flat_file)}.')
self._update_recipe_status('sph_ird_preprocess_science', sphere.ERROR)
return
flat = fits.getdata(path.calib / f'{flat_file.index[0]}.fits')
# final dataframe
self._logger.debug('> create frames_info_preproc data frame')
index = pd.MultiIndex(names=['FILE', 'IMG'], levels=[[], []], codes=[[], []])
frames_info_preproc = pd.DataFrame(index=index, columns=frames_info.columns)
# loop on the different type of science files
sci_types = ['OBJECT,CENTER', 'OBJECT,FLUX', 'OBJECT']
dark_types = ['SKY', 'DARK,BACKGROUND', 'DARK']
for typ in sci_types:
# science files
sci_files = files_info[(files_info['DPR CATG'] == 'SCIENCE') & (files_info['DPR TYPE'] == typ)]
sci_DITs = list(sci_files['DET SEQ1 DIT'].round(2).unique())
if len(sci_files) == 0:
continue
for DIT in sci_DITs:
sfiles = sci_files[sci_files['DET SEQ1 DIT'].round(2) == DIT]
self._logger.info(f'{len(sfiles)} files of type {typ} with DIT={DIT} sec')
if subtract_background:
# look for sky, then background, then darks
# normally there should be only one with the proper DIT
dfiles = []
for d in dark_types:
dfiles = files_info[(files_info['PRO CATG'] == 'IRD_MASTER_DARK') &
(files_info['DPR TYPE'] == d) & (files_info['DET SEQ1 DIT'].round(2) == DIT)]
if len(dfiles) != 0:
break
self._logger.info(f' ==> found {len(dfiles)} corresponding {d} file')
if len(dfiles) == 0:
# issue a warning if absolutely no background is found
self._logger.warning('No background has been found. Pre-processing will continue but data quality will likely be affected')
bkg = np.zeros((1024, 2048))
elif len(dfiles) == 1:
bkg = fits.getdata(path.calib / f'{dfiles.index[0]}.fits')
elif len(dfiles) > 1:
# FIXME: handle cases when multiple backgrounds are found?
self._logger.error(f'Unexpected number of background files ({len(dfiles)})')
self._update_recipe_status('sph_ird_preprocess_science', sphere.ERROR)
return
# process files
for idx, (fname, finfo) in enumerate(sfiles.iterrows()):
# frames_info extract
finfo = frames_info.loc[(fname, slice(None)), :]
self._logger.info(f' * file {idx + 1}/{len(sfiles)}: {fname}, NDIT={len(finfo)}')
# read data
self._logger.info(' ==> read data')
img, hdr = fits.getdata(path.raw / f'{fname}.fits', header=True)
# add extra dimension to single images to make cubes
if img.ndim == 2:
img = img[np.newaxis, ...]
# mask dead regions
img[:, :15, :] = np.nan
img[:, 1013:, :] = np.nan
img[:, :, :50] = np.nan
img[:, :, 941:1078] = np.nan
img[:, :, 1966:] = np.nan
# collapse
true_north = self.config['cal_true_north']
if (typ == 'OBJECT,CENTER'):
if collapse_center:
self._logger.info(' ==> collapse: mean')
img = np.mean(img, axis=0, keepdims=True)
frames_info_new = toolbox.collapse_frames_info(finfo, fname, true_north, 'mean', logger=self._logger)
else:
frames_info_new = toolbox.collapse_frames_info(finfo, fname, true_north, 'none', logger=self._logger)
elif (typ == 'OBJECT,FLUX'):
if collapse_psf:
self._logger.info(' ==> collapse: mean')
img = np.mean(img, axis=0, keepdims=True)
frames_info_new = toolbox.collapse_frames_info(finfo, fname, true_north, 'mean', logger=self._logger)
else:
frames_info_new = toolbox.collapse_frames_info(finfo, fname, true_north, 'none', logger=self._logger)
elif (typ == 'OBJECT'):
if collapse_science:
if collapse_type == 'mean':
self._logger.info(f' ==> collapse: mean ({len(img)} -> 1 frame, 0 dropped)')
img = np.mean(img, axis=0, keepdims=True)
frames_info_new = toolbox.collapse_frames_info(finfo, fname, true_north, 'mean', logger=self._logger)
elif collapse_type == 'coadd':
if (not isinstance(coadd_value, int)) or (coadd_value <= 1):
self._logger.error('coadd_value must be an integer >1')
self._update_recipe_status('sph_ird_preprocess_science', sphere.ERROR)
return
coadd_value = int(coadd_value)
NDIT = len(img)
NDIT_new = NDIT // coadd_value
dropped = NDIT % coadd_value
if coadd_value > NDIT:
self._logger.error(f'coadd_value ({coadd_value}) must be < NDIT ({NDIT})')
self._update_recipe_status('sph_ird_preprocess_science', sphere.ERROR)
return
self._logger.info(f' ==> collapse: coadd by {coadd_value} ({NDIT} -> {NDIT_new} frames, {dropped} dropped)')
# coadd frames
nimg = np.empty((NDIT_new, 1024, 2048), dtype=img.dtype)
for f in range(NDIT_new):
nimg[f] = np.mean(img[f*coadd_value:(f+1)*coadd_value], axis=0)
img = nimg
frames_info_new = toolbox.collapse_frames_info(finfo, fname, true_north, 'coadd', coadd_value=coadd_value, logger=self._logger)
else:
self._logger.error(f'Unknown collapse type {collapse_type}')
self._update_recipe_status('sph_ird_preprocess_science', sphere.ERROR)
return
else:
frames_info_new = toolbox.collapse_frames_info(finfo, fname, true_north, 'none', logger=self._logger)
# check for any error during collapse of frame information
if frames_info_new is None:
self._logger.error('An error occured when collapsing frames info')
self._update_recipe_status('sph_ird_preprocess_science', sphere.ERROR)
return
# merge frames info
frames_info_preproc = pd.concat((frames_info_preproc, frames_info_new))
# background subtraction
if subtract_background:
self._logger.info(' ==> subtract background')
for f in range(len(img)):
img[f] -= bkg
# divide flat
if subtract_background:
self._logger.info(' ==> divide by flat field')
for f in range(len(img)):
img[f] /= flat
# bad pixels correction
if fix_badpix:
self._logger.info(' ==> correct bad pixels')
for f in range(len(img)):
frame = img[f]
frame = imutils.fix_badpix(frame, bpm, npix=12, weight=True)
# additional sigma clipping to remove transitory bad pixels
# not done for OBJECT,FLUX because PSF peak can be clipped
if (typ != 'OBJECT,FLUX'):
frame = imutils.sigma_filter(frame, box=7, nsigma=4, iterate=False)
img[f] = frame
# reshape data
self._logger.info(' ==> reshape data')
NDIT = img.shape[0]
nimg = np.zeros((NDIT, 2, 1024, 1024))
for f in range(len(img)):
nimg[f, 0] = img[f, :, 0:1024]
nimg[f, 1] = img[f, :, 1024:]
img = nimg
# save DITs individually
self._logger.debug('> save pre-processed images')
for f in range(len(img)):
frame = nimg[f, ...].squeeze()
hdr['HIERARCH ESO DET NDIT'] = 1
fits.writeto(path.preproc / f'{fname}_DIT{f:03d}_preproc.fits', frame, hdr,
overwrite=True, output_verify='silentfix')
# sort and save final dataframe
self._logger.debug('> save frames_info_preproc.csv')
frames_info_preproc.sort_values(by='TIME', inplace=True)
frames_info_preproc.to_csv(path.preproc / 'frames_preproc.csv')
self._frames_info_preproc = frames_info_preproc
# recipe execution status
self._update_recipe_status('sph_ird_preprocess_science', sphere.SUCCESS)
# reduction status
self._status = sphere.INCOMPLETE
def sph_ird_star_center(self, high_pass_psf=False, high_pass_waffle=False, offset=(0, 0), box_psf=60, box_waffle=16, plot=True):
'''Determines the star center for all frames where a center can be
determined (OBJECT,CENTER and OBJECT,FLUX)
Parameters
----------
high_pass_psf : bool
Apply high-pass filter to the PSF image before searching for the center.
Default is False
high_pass_waffle : bool
Apply high-pass filter to the center image before searching for the waffle spots.
Default is False
offset : tuple
Apply an (x,y) offset to the default center position, for the waffle centering.
The offset will move the search box of the waffle spots by the amount of
specified pixels in each direction. Default is no offset
box_psf : int
Size of the box in which the PSF fit is performed. Default is 60 pixels
box_waffle : int
Size of the box in which the waffle fit is performed. Default is 16 pixels
plot : bool
Display and save diagnostic plot for quality check. Default is True
'''
self._logger.info('Star centers determination')
# check if recipe can be executed
if not toolbox.recipe_executable(self._recipes_status, self._status, 'sph_ird_star_center',
self.recipe_requirements, logger=self._logger):
return
# parameters
path = self.path
pixel = self.pixel
orientation_offset = self._orientation_offset
center_guess = self._default_center
frames_info = self.frames_info_preproc
# wavelength
filter_comb = frames_info['INS COMB IFLT'].unique()[0]
wave, bandwidth = transmission.wavelength_bandwidth_filter(filter_comb)
wave = np.array(wave)
# start with OBJECT,FLUX
flux_files = frames_info[frames_info['DPR TYPE'] == 'OBJECT,FLUX']
if len(flux_files) != 0:
for file, idx in flux_files.index:
self._logger.info(f' * OBJECT,FLUX: {file}')
# read data
self._logger.debug('> read data')
fname = f'{file}_DIT{idx:03d}_preproc'
cube, hdr = fits.getdata(path.preproc / f'{fname}.fits', header=True)
# centers
if plot:
save_path = path.products / f'{fname}_psf_fitting.pdf'
else:
save_path = None
img_center = toolbox.star_centers_from_PSF_img_cube(cube, wave, pixel, exclude_fraction=0.3,
high_pass=high_pass_psf, box_size=box_psf,
save_path=save_path, logger=self._logger)
# save
self._logger.debug('> save centers')
fits.writeto(path.preproc / f'{fname}_centers.fits', img_center, overwrite=True)
# then OBJECT,CENTER
starcen_files = frames_info[frames_info['DPR TYPE'] == 'OBJECT,CENTER']
if len(starcen_files) != 0:
for file, idx in starcen_files.index:
self._logger.info(f' * OBJECT,CENTER: {file}')
# read data
self._logger.debug('> read data')
fname = f'{file}_DIT{idx:03d}_preproc'
cube, hdr = fits.getdata(path.preproc / f'{fname}.fits', header=True)
# coronagraph
coro_name = starcen_files.loc[(file, idx), 'INS COMB ICOR']
if coro_name == 'N_NS_CLEAR':
coro = False
else:
coro = True
# centers
waffle_orientation = hdr['HIERARCH ESO OCS WAFFLE ORIENT']
self._logger.debug(f'> waffle orientation: {waffle_orientation}')
if plot:
save_path = path.products / f'{fname}_waffle_fitting.pdf'
else:
save_path = None
spot_center, spot_dist, img_center \
= toolbox.star_centers_from_waffle_img_cube(cube, wave, waffle_orientation, center_guess,
pixel, orientation_offset, high_pass=high_pass_waffle,
center_offset=offset, box_size=box_waffle,
coro=coro, save_path=save_path, logger=self._logger)
# save
self._logger.debug('> save centers')
fits.writeto(path.preproc / f'{fname}_centers.fits', img_center, overwrite=True)
# recipe execution status
self._update_recipe_status('sph_ird_star_center', sphere.SUCCESS)
# reduction status
self._status = sphere.INCOMPLETE
def sph_ird_combine_data(self, cpix=True, psf_dim=80, science_dim=290, correct_anamorphism=True,
shift_method='fft', manual_center=None, center_selection='first',
coarse_centering=False, save_scaled=False):
'''Combine and save the science data into final cubes
All types of data are combined independently: PSFs
(OBJECT,FLUX), star centers (OBJECT,CENTER) and standard
coronagraphic images (OBJECT). For each type of data, the
method saves 4 or 5 different files:
- *_cube: the (x,y,time,lambda) cube
- *_derot: the derotation angles vector. This vector takes
into account the parallactic angle, the default
-1.75° true North offset, and any instrumental
pupil offset. This is the values that need to be
used for aligning the images with North up and
East left.
- *_frames: a csv file with all the information for every
frames. There is one line by time step in the
data cube.
- *_cube_scaled: the (x,y,time,lambda) cube with images
rescaled spectraly. This is useful if you
plan to perform spectral differential
imaging in your analysis.
Centering
---------
By default, a fine (sub-pixel) centering is performed if the
an OBJECT,CENTER frame was acquired in the sequence or if
there is a valid user-provided center. However, if the
coarse_centering keyword is set to True, only a "coarse
centering" is performed, which requires no interpolation:
- only integer shifts (shift_method='roll')
- centering on an integer pixel (cpix=True)
- no correction of the anamorphism (correct_anamorphism=False)
- no saving of the rescaled frames (save_scaled=False)
This option is useful if the user wants to perform a
posteriori centering of the frames, e.g. to fully preserve
photometry.
If there was no OBJECT,CENTER acquired in the sequence, then
the centering will be performed with respect to a default,
pre-defined center that is representative of the typical
center of the coronagraph.
Parameters
----------
cpix : bool
If True the images are centered on the pixel at coordinate
(dim//2,dim//2). If False the images are centered between
4 pixels, at coordinates ((dim-1)/2,(dim-1)/2). The value
of cpix is automatically set to True when coarse_centering
is set to True. Default is True.
psf_dim : even int
Size of the PSF images. Default is 80x80 pixels
science_dim : even int
Size of the science images (star centers and standard
coronagraphic images). Default is 290, 290 pixels
correct_anamorphism : bool
Correct the optical anamorphism of the instrument (see
user manual for details). The value of correct_anamorphism
is automatically set to True when coarse_centering is set
to True. Default is True.
manual_center : array
User provided centers for the OBJECT,CENTER and OBJECT
frames. This should be an array of either 2 or nwave*2
values. Default is None
center_selection : str
Specify which star center to use when multiple are
available. Possible values are first, last, and time. The
time option indicates to use the star center file that is
closest in time with respect to each science file. Default
is first
coarse_centering : bool
Control if images are finely centered or not before being
combined. However the images are still roughly centered by
shifting them by an integer number of pixel to bring the
center of the data close to the center of the images. This
option is useful if fine centering must be done
afterwards. Default is False.
shift_method : str
Method to scaling and shifting the images: fft or interp.
Default is fft
save_scaled : bool
Also save the wavelength-rescaled cubes. Makes the process
much longer. The value of save_scaled is automatically set
to False when coarse_centering is set to True. The default
is False
'''
self._logger.info('Combine science data')
# check if recipe can be executed
if not toolbox.recipe_executable(self._recipes_status, self._status, 'sph_ird_combine_data',
self.recipe_requirements, logger=self._logger):
return
# parameters
path = self.path
nwave = self.nwave
frames_info = self.frames_info_preproc
# wavelength
filter_comb = frames_info['INS COMB IFLT'].unique()[0]
wave, bandwidth = transmission.wavelength_bandwidth_filter(filter_comb)
wave = np.array(wave)
self._logger.debug('> save final wavelength')
hdu = fits.PrimaryHDU(wave)
hdu.header['UNIT'] = 'nm'
hdu.writeto(path.products / 'wavelength.fits', overwrite=True)
# max images size
if psf_dim > 1024:
self._logger.warning('psf_dim cannot be larger than 1024 pix. A value of 1024 will be used.')
psf_dim = 1024
if science_dim > 1024:
self._logger.warning('science_dim cannot be larger than 1024 pix. A value of 1024 will be used.')
science_dim = 1024
# centering configuration
if coarse_centering:
self._logger.warning('Images will be coarsely centered without any interpolation. Automatic settings for coarse centering: shift_method=\'roll\', cpix=True, correct_anamorphism=False, save_scaled=False')
shift_method = 'roll'
cpix = True
correct_anamorphism = False
save_scaled = False
if manual_center is not None:
manual_center = np.array(manual_center)
if (manual_center.shape != (2,)) and (manual_center.shape != (nwave, 2)):
self._logger.error('manual_center does not have the right number of dimensions.')
self._update_recipe_status('sph_ird_combine_data', sphere.ERROR)
return
if manual_center.shape == (2,):
manual_center = np.full((nwave, 2), manual_center, dtype=float)
self._logger.warning('Images will be centered using the user-provided center ({},{})'.format(*manual_center[0]))
#
# OBJECT,FLUX
#
flux_files = frames_info[frames_info['DPR TYPE'] == 'OBJECT,FLUX']
nfiles = len(flux_files)
if nfiles != 0:
self._logger.info(' * OBJECT,FLUX data')
# final arrays
psf_cube = np.zeros((nwave, nfiles, psf_dim, psf_dim))
psf_parang = np.zeros(nfiles)
psf_derot = np.zeros(nfiles)
if save_scaled:
psf_cube_scaled = np.zeros((nwave, nfiles, psf_dim, psf_dim))
# final center
if cpix:
cc = psf_dim // 2
else:
cc = (psf_dim - 1) / 2
# read and combine files
for file_idx, (file, idx) in enumerate(flux_files.index):
self._logger.info(f' ==> file {file_idx + 1}/{len(flux_files)}: {file}, DIT #{idx}')
# read data
self._logger.debug('> read data')
fname = f'{file}_DIT{idx:03d}_preproc'
cube = fits.getdata(path.preproc / f'{fname}.fits')
self._logger.debug('> read centers')
cfile = path.preproc / f'{fname}_centers.fits'
if cfile.exists():
centers = fits.getdata(cfile)
else:
self._logger.warning('sph_ird_star_center() has not been executed. Images will be centered using default center ({},{})'.format(*self._default_center))
centers = self._default_center
# make sure we have only integers if user wants coarse centering
if coarse_centering:
centers = centers.astype(int)
# neutral density
self._logger.debug('> read neutral density information')
ND = frames_info.loc[(file, idx), 'INS4 FILT2 NAME']
w, attenuation = transmission.transmission_nd(ND, wave=wave)
# DIT, angles, etc
self._logger.debug('> read angles')
DIT = frames_info.loc[(file, idx), 'DET SEQ1 DIT']
psf_parang[file_idx] = frames_info.loc[(file, idx), 'PARANG']
psf_derot[file_idx] = frames_info.loc[(file, idx), 'DEROT ANGLE']
# center frames
for wave_idx, img in enumerate(cube):
self._logger.debug(f'> wave {wave_idx}')
cx, cy = centers[wave_idx, :]
self._logger.debug('> shift and normalize')
img = img.astype(float)
nimg = imutils.shift(img, (cc-cx, cc-cy), method=shift_method)
nimg = nimg / DIT / attenuation[wave_idx]
psf_cube[wave_idx, file_idx] = nimg[:psf_dim, :psf_dim]
# correct anamorphism
if correct_anamorphism:
self._logger.debug('> correct anamorphism')
nimg = psf_cube[wave_idx, file_idx]
nimg = imutils.scale(nimg, (1.0000, 1.0062), method='interp')
psf_cube[wave_idx, file_idx] = nimg
# wavelength-scaled version
if save_scaled:
self._logger.debug('> spatial scaling')
nimg = psf_cube[wave_idx, file_idx]
psf_cube_scaled[wave_idx, file_idx] = imutils.scale(nimg, wave[0]/wave[wave_idx], method=shift_method)
# save final cubes
self._logger.debug('> save final cubes and metadata')
flux_files.to_csv(path.products / 'psf_frames.csv')
hdu = fits.PrimaryHDU(psf_cube)
hdu.header['UNIT'] = 'ADU/s'
hdu.writeto(path.products / 'psf_cube.fits', overwrite=True)
hdu = fits.PrimaryHDU(psf_derot)
hdu.header['UNIT'] = 'deg'
hdu.writeto(path.products / 'psf_derot.fits', overwrite=True)
if save_scaled:
self._logger.debug('> save scaled cubes')
hdu = fits.PrimaryHDU(psf_cube_scaled)
hdu.header['UNIT'] = 'ADU/s'
hdu.writeto(path.products / 'psf_cube_scaled.fits', overwrite=True)
# delete big cubes
self._logger.debug('> free memory')
del psf_cube
if save_scaled:
del psf_cube_scaled
#
# OBJECT,CENTER
#
starcen_files = frames_info[frames_info['DPR TYPE'] == 'OBJECT,CENTER']
nfiles = len(starcen_files)
if nfiles != 0:
self._logger.info(' * OBJECT,CENTER data')
# final arrays
cen_cube = np.zeros((nwave, nfiles, science_dim, science_dim))
cen_parang = np.zeros(nfiles)
cen_derot = np.zeros(nfiles)
if save_scaled:
cen_cube_scaled = np.zeros((nwave, nfiles, science_dim, science_dim))
# final center
if cpix:
cc = science_dim // 2
else:
cc = (science_dim - 1) / 2
# read and combine files
for file_idx, (file, idx) in enumerate(starcen_files.index):
self._logger.info(f' ==> file {file_idx + 1}/{len(starcen_files)}: {file}, DIT #{idx}')
# read data
self._logger.debug('> read data')
fname = f'{file}_DIT{idx:03d}_preproc'
cube = fits.getdata(path.preproc / f'{fname}.fits')
# use manual center if explicitely requested
self._logger.debug('> read centers')
if manual_center is not None:
centers = manual_center
else:
# otherwise read center data
centers = fits.getdata(path.preproc / f'{fname}_centers.fits')
# make sure we have only integers if user wants coarse centering
if coarse_centering:
centers = centers.astype(int)
# neutral density
self._logger.debug('> read neutral density information')
ND = frames_info.loc[(file, idx), 'INS4 FILT2 NAME']
w, attenuation = transmission.transmission_nd(ND, wave=wave)
# DIT, angles, etc
self._logger.debug('> read angles')
DIT = frames_info.loc[(file, idx), 'DET SEQ1 DIT']
cen_parang[file_idx] = frames_info.loc[(file, idx), 'PARANG']
cen_derot[file_idx] = frames_info.loc[(file, idx), 'DEROT ANGLE']
# center frames
for wave_idx, img in enumerate(cube):
self._logger.debug(f'> wave {wave_idx}')
cx, cy = centers[wave_idx, :]
self._logger.debug('> shift and normalize')
img = img.astype(float)
nimg = imutils.shift(img, (cc-cx, cc-cy), method=shift_method)
nimg = nimg / DIT / attenuation[wave_idx]
cen_cube[wave_idx, file_idx] = nimg[:science_dim, :science_dim]
# correct anamorphism
if correct_anamorphism:
self._logger.debug('> correct anamorphism')
nimg = cen_cube[wave_idx, file_idx]
nimg = imutils.scale(nimg, (1.0000, 1.0062), method='interp')
cen_cube[wave_idx, file_idx] = nimg
# wavelength-scaled version
if save_scaled:
self._logger.debug('> spatial scaling')
nimg = cen_cube[wave_idx, file_idx]
cen_cube_scaled[wave_idx, file_idx] = imutils.scale(nimg, wave[0]/wave[wave_idx], method=shift_method)
# save final cubes
self._logger.debug('> save final cubes and metadata')
starcen_files.to_csv(path.products / 'starcenter_frames.csv')
hdu = fits.PrimaryHDU(cen_cube)
hdu.header['UNIT'] = 'ADU/s'
hdu.writeto(path.products / 'starcenter_cube.fits', overwrite=True)
hdu = fits.PrimaryHDU(cen_derot)
hdu.header['UNIT'] = 'ADU/s'
hdu.writeto(path.products / 'starcenter_derot.fits', overwrite=True)
if save_scaled:
self._logger.debug('> save scaled cubes')
hdu = fits.PrimaryHDU(cen_cube_scaled)
hdu.header['UNIT'] = 'ADU/s'
hdu.writeto(path.products / 'starcenter_cube_scaled.fits', overwrite=True)
# delete big cubes
self._logger.debug('> free memory')
del cen_cube
if save_scaled:
del cen_cube_scaled
#
# OBJECT
#
object_files = frames_info[frames_info['DPR TYPE'] == 'OBJECT']
nfiles = len(object_files)
if nfiles != 0:
self._logger.info(' * OBJECT data')
# null value for Dithering Motion Stage by default
dms_dx_ref = 0
dms_dy_ref = 0
# final center
if cpix:
cc = science_dim // 2
else:
cc = (science_dim - 1) / 2
# final arrays
sci_cube = np.zeros((nwave, nfiles, science_dim, science_dim))
sci_parang = np.zeros(nfiles)
sci_derot = np.zeros(nfiles)
if save_scaled:
sci_cube_scaled = np.zeros((nwave, nfiles, science_dim, science_dim))
# read and combine files
for file_idx, (file, idx) in enumerate(object_files.index):
self._logger.info(f' ==> file {file_idx + 1}/{len(object_files)}: {file}, DIT #{idx}')
# use manual center if explicitely requested
self._logger.debug('> read centers')
if manual_center is not None:
centers = manual_center
else:
# otherwise, look whether we have an OBJECT,CENTER frame and select the one requested by user
starcen_files = frames_info[frames_info['DPR TYPE'] == 'OBJECT,CENTER']
if len(starcen_files) == 0:
self._logger.warning('No OBJECT,CENTER file in the dataset. Images will be centered using default center ({},{})'.format(*self._default_center))
centers = self._default_center
else:
# selection of the proper OBJECT,CENTER
center_selection = center_selection.lower()
if center_selection == 'first':
center_index = 0
elif center_selection == 'last':
center_index = len(starcen_files.index.values)-1
elif center_selection == 'time':
time_cen = starcen_files['DATE-OBS']
time_sci = frames_info.loc[(file, idx), 'DATE-OBS']
center_index = np.abs(time_sci - time_cen).argmin()
else:
self._logger.error(f'Unknown OBJECT,CENTER selection {center_selection}. Possible values are first, last, and time.')
self._update_recipe_status('sph_ird_combine_data', sphere.ERROR)
return
fname = f'{starcen_files.index.values[center_index][0]}_DIT{starcen_files.index.values[center_index][1]:03d}_preproc_centers.fits'
fpath = path.preproc / fname
if fpath.exists():
centers = fits.getdata(fpath)
# Dithering Motion Stage for star center: value is in micron,
# and the pixel size is 18 micron
dms_dx_ref = starcen_files['INS1 PAC X'].iloc[0] / 18
dms_dy_ref = starcen_files['INS1 PAC Y'].iloc[0] / 18
else:
self._logger.warning('sph_ird_star_center() has not been executed. Images will be centered using default center ({},{})'.format(*self._default_center))
centers = self._default_center
# make sure we have only integers if user wants coarse centering
if coarse_centering:
centers = centers.astype(int)
dms_dx_ref = int(dms_dx_ref)
dms_dy_ref = int(dms_dy_ref)
# read data
self._logger.debug('> read data')
fname = f'{file}_DIT{idx:03d}_preproc'
files = list(path.preproc.glob(f'{fname}*.fits'))
cube = fits.getdata(files[0])
# neutral density
self._logger.debug('> read neutral density information')
ND = frames_info.loc[(file, idx), 'INS4 FILT2 NAME']
w, attenuation = transmission.transmission_nd(ND, wave=wave)
# DIT, angles, etc
self._logger.debug('> read angles')
DIT = frames_info.loc[(file, idx), 'DET SEQ1 DIT']
sci_parang[file_idx] = frames_info.loc[(file, idx), 'PARANG']
sci_derot[file_idx] = frames_info.loc[(file, idx), 'DEROT ANGLE']
# Dithering Motion Stage for star center: value is in micron,
# and the pixel size is 18 micron
self._logger.debug('> read DMS position')
dms_dx = frames_info.loc[(file, idx), 'INS1 PAC X'] / 18
dms_dy = frames_info.loc[(file, idx), 'INS1 PAC Y'] / 18
# make sure we have only integers if user wants coarse centering
if coarse_centering:
dms_dx = int(dms_dx)
dms_dy = int(dms_dy)
# center frames
for wave_idx, img in enumerate(cube):
self._logger.debug(f'> wave {wave_idx}')
cx, cy = centers[wave_idx, :]
# DMS contribution
cx = cx + dms_dx_ref + dms_dx
cy = cy + dms_dy_ref + dms_dy
self._logger.debug('> shift and normalize')
img = img.astype(float)
nimg = imutils.shift(img, (cc-cx, cc-cy), method=shift_method)
nimg = nimg / DIT / attenuation[wave_idx]
sci_cube[wave_idx, file_idx] = nimg[:science_dim, :science_dim]
# correct anamorphism
if correct_anamorphism:
self._logger.debug('> correct anamorphism')
nimg = sci_cube[wave_idx, file_idx]
nimg = imutils.scale(nimg, (1.0000, 1.0062), method='interp')
sci_cube[wave_idx, file_idx] = nimg
# wavelength-scaled version
if save_scaled:
self._logger.debug('> spatial scaling')
nimg = sci_cube[wave_idx, file_idx]
sci_cube_scaled[wave_idx, file_idx] = imutils.scale(nimg, wave[0]/wave[wave_idx], method=shift_method)
# save final cubes
self._logger.debug('> save final cubes and metadata')
object_files.to_csv(path.products / 'science_frames.csv')
hdu = fits.PrimaryHDU(sci_cube)
hdu.header['UNIT'] = 'ADU/s'
hdu.writeto(path.products / 'science_cube.fits', overwrite=True)
hdu = fits.PrimaryHDU(sci_derot)
hdu.header['UNIT'] = 'ADU/s'
hdu.writeto(path.products / 'science_derot.fits', overwrite=True)
if save_scaled:
self._logger.debug('> save scaled cubes')
hdu = fits.PrimaryHDU(sci_cube_scaled)
hdu.header['UNIT'] = 'ADU/s'
hdu.writeto(path.products / 'science_cube_scaled.fits', overwrite=True)
# delete big cubes
self._logger.debug('> free memory')
del sci_cube
if save_scaled:
del sci_cube_scaled
# recipe execution status
self._update_recipe_status('sph_ird_combine_data', sphere.SUCCESS)
# reduction status
self._status = sphere.COMPLETE
def sph_ird_clean(self, delete_raw=False, delete_products=False, delete_config=False):
'''
Clean everything except for raw data and science products (by default)
Parameters
----------
delete_raw : bool
Delete raw data. Default is False
delete_products : bool
Delete science products. Default is False
delete_config : bool
Delete configuration file. Default is False
'''
self._logger.info('Clean reduction data')
# check if recipe can be executed
if not toolbox.recipe_executable(self._recipes_status, self._status, 'sph_ird_clean',
self.recipe_requirements, logger=self._logger):
return
# remove sub-directories
self.path.remove(delete_raw=delete_raw, delete_products=delete_products, logger=self._logger)
# remove config
if delete_config:
self.config._file.unlink()
# recipe execution status
self._update_recipe_status('sph_ird_clean', sphere.SUCCESS)
# reduction status
self._status = sphere.COMPLETE
|
aviganREPO_NAMESPHEREPATH_START.@SPHERE_extracted@SPHERE-master@sphere@IRDIS@ImagingReduction.py@.PATH_END.py
|
{
"filename": "plotestimators.py",
"repo_name": "artis-mcrt/artistools",
"repo_path": "artistools_extracted/artistools-main/artistools/estimators/plotestimators.py",
"type": "Python"
}
|
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
"""Functions for plotting artis estimators and internal structure.
Examples are temperatures, populations, heating/cooling rates.
"""
import argparse
import contextlib
import math
import string
import typing as t
from collections.abc import Sequence
from itertools import chain
from pathlib import Path
import argcomplete
import matplotlib.axes as mplax
import matplotlib.pyplot as plt
import numpy as np
import polars as pl
import polars.selectors as cs
import artistools as at
colors_tab10: list[str] = list(plt.get_cmap("tab10")(np.linspace(0, 1.0, 10)))
# reserve colours for these elements
elementcolors = {"Fe": colors_tab10[0], "Ni": colors_tab10[1], "Co": colors_tab10[2]}
def get_elemcolor(atomic_number: int | None = None, elsymbol: str | None = None) -> str | np.ndarray:
"""Get the colour of an element from the reserved color list (reserving a new one if needed)."""
assert (atomic_number is None) != (elsymbol is None)
if atomic_number is not None:
elsymbol = at.get_elsymbol(atomic_number)
assert elsymbol is not None
# assign a new colour to this element if needed
return elementcolors.setdefault(elsymbol, colors_tab10[len(elementcolors)])
def get_ylabel(variable: str) -> str:
return at.estimators.get_variablelongunits(variable) or at.estimators.get_units_string(variable)
def plot_init_abundances(
ax: mplax.Axes,
xlist: list[float],
specieslist: list[str],
mgilist: Sequence[float],
modelpath: Path,
seriestype: str,
startfromzero: bool,
args: argparse.Namespace,
**plotkwargs,
) -> None:
assert len(xlist) == len(mgilist)
if seriestype == "initabundances":
mergemodelabundata, _ = at.inputmodel.get_modeldata(modelpath, get_elemabundances=True)
elif seriestype == "initmasses":
mergemodelabundata = at.inputmodel.plotinitialcomposition.get_model_abundances_Msun_1D(modelpath)
else:
raise AssertionError
if startfromzero:
xlist = [0.0, *xlist]
for speciesstr in specieslist:
splitvariablename = speciesstr.split("_")
elsymbol = splitvariablename[0].strip(string.digits)
atomic_number = at.get_atomic_number(elsymbol)
if seriestype == "initabundances":
ax.set_ylim(1e-20, 1.0)
ax.set_ylabel("Initial mass fraction")
valuetype = "X_"
elif seriestype == "initmasses":
ax.set_ylabel(r"Initial mass [M$_\odot$]")
valuetype = "mass_X_"
else:
raise AssertionError
ylist = []
linelabel = speciesstr
linestyle = "-"
for modelgridindex in mgilist:
if speciesstr.lower() in {"ni_56", "ni56", "56ni"}:
yvalue = mergemodelabundata.loc[modelgridindex][f"{valuetype}Ni56"]
linelabel = "$^{56}$Ni"
linestyle = "--"
elif speciesstr.lower() in {"ni_stb", "ni_stable"}:
yvalue = (
mergemodelabundata.loc[modelgridindex][f"{valuetype}{elsymbol}"]
- mergemodelabundata.loc[modelgridindex]["X_Ni56"]
)
linelabel = "Stable Ni"
elif speciesstr.lower() in {"co_56", "co56", "56co"}:
yvalue = mergemodelabundata.loc[modelgridindex][f"{valuetype}Co56"]
linelabel = "$^{56}$Co"
elif speciesstr.lower() in {"fegrp", "ffegroup"}:
yvalue = mergemodelabundata.loc[modelgridindex][f"{valuetype}Fegroup"]
else:
yvalue = mergemodelabundata.loc[modelgridindex][f"{valuetype}{elsymbol}"]
ylist.append(yvalue)
color = get_elemcolor(atomic_number=atomic_number)
xlist, ylist = at.estimators.apply_filters(xlist, np.array(ylist), args)
if startfromzero:
ylist = [ylist[0], *ylist]
ax.plot(xlist, ylist, linewidth=1.5, label=linelabel, linestyle=linestyle, color=color, **plotkwargs)
# if args.yscale == 'log':
# ax.set_yscale('log')
def plot_average_ionisation_excitation(
ax: mplax.Axes,
xlist: list[float],
seriestype: str,
params: Sequence[str],
timestepslist: Sequence[Sequence[int]],
mgilist: Sequence[int],
estimators: pl.LazyFrame,
modelpath: Path | str,
startfromzero: bool,
args: argparse.Namespace | None = None,
**plotkwargs,
) -> None:
if args is None:
args = argparse.Namespace()
if seriestype == "averageexcitation":
ax.set_ylabel("Average excitation [eV]")
elif seriestype == "averageionisation":
ax.set_ylabel("Average ion charge")
else:
raise ValueError
if startfromzero:
xlist = [0.0, *xlist]
arr_tdelta = at.get_timestep_times(modelpath, loc="delta")
for paramvalue in params:
print(f"Plotting {seriestype} {paramvalue}")
if seriestype == "averageionisation":
atomic_number = at.get_atomic_number(paramvalue)
else:
atomic_number = at.get_atomic_number(paramvalue.split(" ")[0])
ion_stage = at.decode_roman_numeral(paramvalue.split(" ")[1])
ylist = []
if seriestype == "averageexcitation":
print(" This will be slow! TODO: reimplement with polars.")
for modelgridindex, timesteps in zip(mgilist, timestepslist, strict=False):
exc_ev_times_tdelta_sum = 0.0
tdeltasum = 0.0
for timestep in timesteps:
T_exc = (
estimators.filter(pl.col("timestep") == timestep)
.filter(pl.col("modelgridindex") == modelgridindex)
.select("Te")
.lazy()
.collect()
.item(0, 0)
)
exc_ev = at.estimators.get_averageexcitation(
modelpath, modelgridindex, timestep, atomic_number, ion_stage, T_exc
)
if exc_ev is not None:
exc_ev_times_tdelta_sum += exc_ev * arr_tdelta[timestep]
tdeltasum += arr_tdelta[timestep]
if tdeltasum == 0.0:
msg = f"ERROR: No excitation data found for {paramvalue}"
raise ValueError(msg)
ylist.append(exc_ev_times_tdelta_sum / tdeltasum if tdeltasum > 0 else math.nan)
elif seriestype == "averageionisation":
elsymb = at.get_elsymbol(atomic_number)
if f"nnelement_{elsymb}" not in estimators.collect_schema().names():
msg = f"ERROR: No element data found for {paramvalue}"
raise ValueError(msg)
dfselected = (
estimators.select(
cs.starts_with(f"nnion_{elsymb}_")
| cs.by_name(f"nnelement_{elsymb}")
| cs.by_name("modelgridindex")
| cs.by_name("timestep")
| cs.by_name("xvalue")
| cs.by_name("plotpointid")
)
.with_columns(pl.col(pl.Float32).fill_null(0.0))
.collect()
.join(
pl.DataFrame({"timestep": range(len(arr_tdelta)), "tdelta": arr_tdelta}).with_columns(
pl.col("timestep").cast(pl.Int32)
),
on="timestep",
how="left",
coalesce=True,
)
)
dfselected = dfselected.filter(pl.col(f"nnelement_{elsymb}") > 0.0)
ioncols = [col for col in dfselected.columns if col.startswith(f"nnion_{elsymb}_")]
ioncharges = [at.decode_roman_numeral(col.removeprefix(f"nnion_{elsymb}_")) - 1 for col in ioncols]
ax.set_ylim(0.0, max(ioncharges) + 0.1)
dfselected = dfselected.with_columns(
(
pl.sum_horizontal([
pl.col(ioncol) * ioncharge for ioncol, ioncharge in zip(ioncols, ioncharges, strict=False)
])
/ pl.col(f"nnelement_{elsymb}")
).alias(f"averageionisation_{elsymb}")
)
series = (
dfselected.group_by("plotpointid", maintain_order=True)
.agg(pl.col(f"averageionisation_{elsymb}").mean(), pl.col("xvalue").mean())
.lazy()
.collect()
)
xlist = series["xvalue"].to_list()
if startfromzero:
xlist = [0.0, *xlist]
ylist = series[f"averageionisation_{elsymb}"].to_list()
color = get_elemcolor(atomic_number=atomic_number)
xlist, ylist = at.estimators.apply_filters(xlist, ylist, args)
if startfromzero:
ylist = [ylist[0], *ylist]
ax.plot(xlist, ylist, label=paramvalue, color=color, **plotkwargs)
def plot_levelpop(
ax: mplax.Axes,
xlist: Sequence[int | float] | np.ndarray,
seriestype: str,
params: Sequence[str],
timestepslist: Sequence[Sequence[int]],
mgilist: Sequence[int | Sequence[int]],
modelpath: str | Path,
args: argparse.Namespace,
**plotkwargs: t.Any,
) -> None:
if seriestype == "levelpopulation_dn_on_dvel":
ax.set_ylabel("dN/dV [{}km$^{{-1}}$ s]")
ax.yaxis.set_major_formatter(at.plottools.ExponentLabelFormatter(ax.get_ylabel()))
elif seriestype == "levelpopulation":
ax.set_ylabel("X$_{{i}}$ [{}/cm3]")
ax.yaxis.set_major_formatter(at.plottools.ExponentLabelFormatter(ax.get_ylabel()))
else:
raise ValueError
modeldata, _ = at.inputmodel.get_modeldata(modelpath, derived_cols=["mass_g", "volume"])
adata = at.atomic.get_levels(modelpath)
arr_tdelta = at.get_timestep_times(modelpath, loc="delta")
for paramvalue in params:
paramsplit = paramvalue.split(" ")
atomic_number = at.get_atomic_number(paramsplit[0])
ion_stage = at.decode_roman_numeral(paramsplit[1])
levelindex = int(paramsplit[2])
ionlevels = adata.query("Z == @atomic_number and ion_stage == @ion_stage").iloc[0].levels
levelname = ionlevels.iloc[levelindex].levelname
label = (
f"{at.get_ionstring(atomic_number, ion_stage, style='chargelatex')} level {levelindex}:"
f" {at.nltepops.texifyconfiguration(levelname)}"
)
print(f"plot_levelpop {label}")
# level index query goes outside for caching granularity reasons
dfnltepops = at.nltepops.read_files(
modelpath, dfquery=f"Z=={atomic_number:.0f} and ion_stage=={ion_stage:.0f}"
).query("level==@levelindex")
ylist = []
for modelgridindex, timesteps in zip(mgilist, timestepslist, strict=False):
valuesum = 0.0
tdeltasum = 0.0
# print(f'modelgridindex {modelgridindex} timesteps {timesteps}')
for timestep in timesteps:
levelpop = (
dfnltepops.query(
"modelgridindex==@modelgridindex and timestep==@timestep and Z==@atomic_number"
" and ion_stage==@ion_stage and level==@levelindex"
)
.iloc[0]
.n_NLTE
)
valuesum += levelpop * arr_tdelta[timestep]
tdeltasum += arr_tdelta[timestep]
if seriestype == "levelpopulation_dn_on_dvel":
assert isinstance(modelgridindex, int)
deltav = modeldata.loc[modelgridindex].vel_r_max_kmps - modeldata.loc[modelgridindex].vel_r_min_kmps
ylist.append(valuesum / tdeltasum * modeldata.loc[modelgridindex].volume / deltav)
else:
ylist.append(valuesum / tdeltasum)
ylist = [ylist[0], *ylist]
xlist, ylist = at.estimators.apply_filters(xlist, np.array(ylist), args)
ax.plot(xlist, ylist, label=label, **plotkwargs)
def plot_multi_ion_series(
ax: mplax.Axes,
startfromzero: bool,
seriestype: str,
ionlist: Sequence[str],
estimators: pl.LazyFrame | pl.DataFrame,
modelpath: str | Path,
args: argparse.Namespace,
**plotkwargs: t.Any,
) -> None:
"""Plot an ion-specific property, e.g., populations."""
# if seriestype == 'populations':
# ax.yaxis.set_major_locator(ticker.MultipleLocator(base=0.10))
plotted_something = False
def get_iontuple(ionstr):
if ionstr in at.get_elsymbolslist():
return (at.get_atomic_number(ionstr), "ALL")
if " " in ionstr:
return (at.get_atomic_number(ionstr.split(" ")[0]), at.decode_roman_numeral(ionstr.split(" ")[1]))
if ionstr.rstrip("-0123456789") in at.get_elsymbolslist():
atomic_number = at.get_atomic_number(ionstr.rstrip("-0123456789"))
return (atomic_number, ionstr)
atomic_number = at.get_atomic_number(ionstr.split("_")[0])
return (atomic_number, ionstr)
# decoded into atomic number and parameter, e.g., [(26, 1), (26, 2), (26, 'ALL'), (26, 'Fe56')]
iontuplelist = [get_iontuple(ionstr) for ionstr in ionlist]
iontuplelist.sort()
print(f"Subplot with ions: {iontuplelist}")
missingions = set()
try:
if not args.classicartis:
compositiondata = at.get_composition_data(modelpath)
for atomic_number, ion_stage in iontuplelist:
if (
not hasattr(ion_stage, "lower")
and not args.classicartis
and compositiondata.query(
"Z == @atomic_number & lowermost_ion_stage <= @ion_stage & uppermost_ion_stage >= @ion_stage"
).empty
):
missingions.add((atomic_number, ion_stage))
except FileNotFoundError:
print("WARNING: Could not read an ARTIS compositiondata.txt file to check ion availability")
for atomic_number, ion_stage in iontuplelist:
ionstr = at.get_ionstring(atomic_number, ion_stage, sep="_", style="spectral")
if f"nnion_{ionstr}" not in estimators.collect_schema().names():
missingions.add((atomic_number, ion_stage))
if missingions:
print(f" Warning: Can't plot {seriestype} for {missingions} because these ions are not in compositiondata.txt")
iontuplelist = [iontuple for iontuple in iontuplelist if iontuple not in missingions]
prev_atomic_number = iontuplelist[0][0]
colorindex = 0
for atomic_number, ion_stage in iontuplelist:
if atomic_number != prev_atomic_number:
colorindex += 1
elsymbol = at.get_elsymbol(atomic_number)
ionstr = at.get_ionstring(atomic_number, ion_stage, sep="_", style="spectral")
if seriestype == "populations":
if ion_stage == "ALL":
key = f"nnelement_{elsymbol}"
elif isinstance(ion_stage, str) and ion_stage.startswith(at.get_elsymbol(atomic_number)):
# not really an ion_stage but an isotope name
key = f"nniso_{ion_stage}"
else:
key = f"nnion_{ionstr}"
else:
key = f"{seriestype}_{ionstr}"
print(f"Plotting {seriestype} {ionstr.replace('_', ' ')}")
if seriestype != "populations" or args.ionpoptype == "absolute":
scalefactor = pl.lit(1)
elif args.ionpoptype == "elpop":
scalefactor = pl.col(f"nnelement_{elsymbol}").mean()
elif args.ionpoptype == "totalpop":
scalefactor = pl.col("nntot").mean()
else:
raise AssertionError
series = (
estimators.group_by("plotpointid", maintain_order=True)
.agg(pl.col(key).mean() / scalefactor, pl.col("xvalue").mean())
.lazy()
.collect()
.sort("xvalue")
)
xlist = series["xvalue"].to_list()
ylist = series[key].to_list()
if startfromzero:
# make a line segment from 0 velocity
xlist = [0.0, *xlist]
ylist = [ylist[0], *ylist]
plotlabel = (
ion_stage
if hasattr(ion_stage, "lower") and ion_stage != "ALL"
else at.get_ionstring(atomic_number, ion_stage, style="chargelatex")
)
color = get_elemcolor(atomic_number=atomic_number)
# linestyle = ['-.', '-', '--', (0, (4, 1, 1, 1)), ':'] + [(0, x) for x in dashes_list][ion_stage - 1]
dashes: tuple[float, ...]
if isinstance(ion_stage, str):
if ion_stage == "ALL":
dashes = ()
linewidth = 1.0
else:
# isotopic abundance
index = 8 if ion_stage.endswith("stable") else int(ion_stage.lstrip(at.get_elsymbol(atomic_number)))
else:
assert isinstance(ion_stage, int)
index = ion_stage
dashes_list = [(3, 1, 1, 1), (), (1.5, 1.5), (6, 3), (1, 3)]
dashes = dashes_list[(index - 1) % len(dashes_list)]
linewidth_list = [1.0, 1.0, 1.0, 0.7, 0.7]
linewidth = linewidth_list[(index - 1) % len(linewidth_list)]
# color = ['blue', 'green', 'red', 'cyan', 'purple', 'grey', 'brown', 'orange'][index - 1]
if args.colorbyion:
color = f"C{index - 1 % 10}"
# plotlabel = f'{at.get_elsymbol(atomic_number)} {at.roman_numerals[ion_stage]}'
dashes = ()
# assert colorindex < 10
# color = f'C{colorindex}'
# or ax.step(where='pre', )
xlist, ylist = at.estimators.apply_filters(xlist, ylist, args)
if plotkwargs.get("linestyle", "solid") != "None":
plotkwargs["dashes"] = dashes
ax.plot(xlist, ylist, linewidth=linewidth, label=plotlabel, color=color, **plotkwargs)
prev_atomic_number = atomic_number
plotted_something = True
if seriestype == "populations":
if args.ionpoptype == "absolute":
ax.set_ylabel(r"Number density $\left[\rm{cm}^{-3}\right]$")
elif args.ionpoptype == "elpop":
# elsym = at.get_elsymbol(atomic_number)
ax.set_ylabel(r"X$_{i}$/X$_{\rm element}$")
elif args.ionpoptype == "totalpop":
ax.set_ylabel(r"X$_{i}$/X$_{rm tot}$")
else:
raise AssertionError
else:
ax.set_ylabel(at.estimators.get_varname_formatted(seriestype))
if plotted_something:
ax.set_yscale(args.yscale)
if args.yscale == "log":
ymin, ymax = ax.get_ylim()
ymin = max(ymin, ymax / 1e10)
ax.set_ylim(bottom=ymin)
# make space for the legend
new_ymax = ymax * 10 ** (0.1 * math.log10(ymax / ymin))
if ymin > 0 and new_ymax > ymin and np.isfinite(new_ymax):
ax.set_ylim(top=new_ymax)
def plot_series(
ax: mplax.Axes,
startfromzero: bool,
variable: str | pl.Expr,
showlegend: bool,
estimators: pl.LazyFrame | pl.DataFrame,
args: argparse.Namespace,
nounits: bool = False,
**plotkwargs: t.Any,
) -> None:
"""Plot something like Te or TR."""
if isinstance(variable, pl.Expr):
colexpr = variable
else:
assert variable in estimators.collect_schema().names(), f"Variable {variable} not found in estimators"
colexpr = pl.col(variable)
variablename = colexpr.meta.output_name()
serieslabel = at.estimators.get_varname_formatted(variablename)
units_string = at.estimators.get_units_string(variablename)
if showlegend:
linelabel = serieslabel
if not nounits:
linelabel += units_string
else:
ax.set_ylabel(serieslabel + units_string)
linelabel = None
print(f"Plotting {variablename}")
series = (
estimators.group_by("plotpointid", maintain_order=True)
.agg(colexpr.mean(), pl.col("xvalue").mean())
.lazy()
.collect()
)
ylist = series[variablename].to_list()
xlist = series["xvalue"].to_list()
with contextlib.suppress(ValueError):
if min(ylist) == 0 or math.log10(max(ylist) / min(ylist)) > 2:
ax.set_yscale("log")
dictcolors = {
"Te": "red"
# 'heating_gamma': 'blue',
# 'cooling_adiabatic': 'blue'
}
if startfromzero:
# make a line segment from 0 velocity
xlist = [0.0, *xlist]
ylist = [ylist[0], *ylist]
xlist_filtered, ylist_filtered = at.estimators.apply_filters(xlist, ylist, args)
ax.plot(
xlist_filtered, ylist_filtered, linewidth=1.5, label=linelabel, color=dictcolors.get(variablename), **plotkwargs
)
def get_xlist(
xvariable: str, estimators: pl.LazyFrame, timestepslist: t.Any, groupbyxvalue: bool, args: t.Any
) -> tuple[list[float | int], list[int], list[list[int]], pl.LazyFrame]:
estimators = estimators.filter(pl.col("timestep").is_in(set(chain.from_iterable(timestepslist))))
if xvariable in {"cellid", "modelgridindex"}:
estimators = estimators.with_columns(xvalue=pl.col("modelgridindex"), plotpointid=pl.col("modelgridindex"))
elif xvariable == "timestep":
estimators = estimators.with_columns(xvalue=pl.col("timestep"), plotpointid=pl.col("timestep"))
elif xvariable == "time":
estimators = estimators.with_columns(xvalue=pl.col("time_mid"), plotpointid=pl.col("timestep"))
elif xvariable in {"velocity", "beta"}:
velcolumn = "vel_r_mid"
scalefactor = 1e5 if xvariable == "velocity" else 29979245800
estimators = estimators.with_columns(
xvalue=(pl.col(velcolumn) / scalefactor), plotpointid=pl.col("modelgridindex")
)
else:
assert xvariable in estimators.collect_schema().names()
estimators = estimators.with_columns(xvalue=pl.col(xvariable), plotpointid=pl.col("modelgridindex"))
# single valued line plot
if groupbyxvalue:
estimators = estimators.with_columns(plotpointid=pl.col("xvalue"))
if args.xmax > 0:
estimators = estimators.filter(pl.col("xvalue") <= args.xmax)
estimators = estimators.sort("plotpointid")
pointgroups = (
(
estimators.select(["plotpointid", "xvalue", "modelgridindex", "timestep"])
.group_by("plotpointid", maintain_order=True)
.agg(pl.col("xvalue").first(), pl.col("modelgridindex").first(), pl.col("timestep").unique())
)
.lazy()
.collect()
)
assert len(pointgroups) > 0, "No data found for x-axis variable"
return (
pointgroups["xvalue"].to_list(),
pointgroups["modelgridindex"].to_list(),
pointgroups["timestep"].to_list(),
estimators,
)
def plot_subplot(
ax: mplax.Axes,
timestepslist: list[list[int]],
xlist: list[float | int],
startfromzero: bool,
plotitems: list[t.Any],
mgilist: list[int],
modelpath: str | Path,
estimators: pl.LazyFrame,
args: argparse.Namespace,
**plotkwargs: t.Any,
) -> None:
"""Make plot from ARTIS estimators."""
# these three lists give the x value, modelgridex, and a list of timesteps (for averaging) for each plot of the plot
showlegend = False
legend_kwargs = {}
seriescount = 0
ylabel = None
sameylabel = True
seriesvars = [var for var in plotitems if isinstance(var, str | pl.Expr)]
seriescount = len(seriesvars)
for variable in seriesvars:
variablename = variable.meta.output_name() if isinstance(variable, pl.Expr) else variable
if ylabel is None:
ylabel = get_ylabel(variablename)
elif ylabel != get_ylabel(variablename):
sameylabel = False
break
for plotitem in plotitems:
if isinstance(plotitem, str | pl.Expr):
variablename = plotitem.meta.output_name() if isinstance(plotitem, pl.Expr) else plotitem
assert isinstance(variablename, str)
showlegend = seriescount > 1 or len(variablename) > 35 or not sameylabel
plot_series(
ax=ax,
startfromzero=startfromzero,
variable=plotitem,
showlegend=showlegend,
estimators=estimators,
args=args,
nounits=sameylabel,
**plotkwargs,
)
if showlegend and sameylabel and ylabel is not None:
ax.set_ylabel(ylabel)
else: # it's a sequence of values
seriestype, params = plotitem
if seriestype in {"initabundances", "initmasses"}:
showlegend = True
plot_init_abundances(
ax=ax,
xlist=xlist,
specieslist=params,
mgilist=mgilist,
modelpath=Path(modelpath),
seriestype=seriestype,
startfromzero=startfromzero,
args=args,
)
elif seriestype == "levelpopulation" or seriestype.startswith("levelpopulation_"):
showlegend = True
plot_levelpop(ax, xlist, seriestype, params, timestepslist, mgilist, modelpath, args=args)
elif seriestype in {"averageionisation", "averageexcitation"}:
showlegend = True
plot_average_ionisation_excitation(
ax,
xlist,
seriestype,
params,
timestepslist,
mgilist,
estimators,
modelpath,
startfromzero=startfromzero,
args=args,
**plotkwargs,
)
elif seriestype == "_ymin":
ax.set_ylim(bottom=params)
elif seriestype == "_ymax":
ax.set_ylim(top=params)
elif seriestype == "_yscale":
ax.set_yscale(params)
else:
showlegend = True
seriestype, ionlist = plotitem
if seriestype == "populations" and len(ionlist) > 2 and args.yscale == "log":
legend_kwargs["ncol"] = 2
plot_multi_ion_series(
ax=ax,
startfromzero=startfromzero,
seriestype=seriestype,
ionlist=ionlist,
estimators=estimators,
modelpath=modelpath,
args=args,
**plotkwargs,
)
ax.tick_params(right=True)
if showlegend and not args.nolegend:
ax.legend(loc="upper right", handlelength=2, frameon=False, numpoints=1, **legend_kwargs, markerscale=3)
def make_plot(
modelpath: Path | str,
timestepslist_unfiltered: list[list[int]],
estimators: pl.LazyFrame,
xvariable: str,
plotlist,
args: t.Any,
**plotkwargs: t.Any,
) -> str:
modelname = at.get_model_name(modelpath)
fig, axes = plt.subplots(
nrows=len(plotlist),
ncols=1,
sharex=True,
figsize=(
args.figscale * at.get_config()["figwidth"] * args.scalefigwidth,
args.figscale * at.get_config()["figwidth"] * 0.5 * len(plotlist),
),
layout="constrained",
# tight_layout={"pad": 0.2, "w_pad": 0.0, "h_pad": 0.0},
)
if len(plotlist) == 1:
axes = np.array([axes])
assert isinstance(axes, np.ndarray)
# ax.xaxis.set_minor_locator(ticker.MultipleLocator(base=5))
if not args.hidexlabel:
axes[-1].set_xlabel(
f"{at.estimators.get_varname_formatted(xvariable)}{at.estimators.get_units_string(xvariable)}"
)
xlist, mgilist, timestepslist, estimators = get_xlist(
xvariable=xvariable,
estimators=estimators,
timestepslist=timestepslist_unfiltered,
groupbyxvalue=not args.markersonly,
args=args,
)
startfromzero = (xvariable.startswith("velocity") or xvariable == "beta") and not args.markersonly
xmin = args.xmin if args.xmin >= 0 else min(xlist)
xmax = args.xmax if args.xmax > 0 else max(xlist)
if args.markersonly:
plotkwargs["linestyle"] = "None"
plotkwargs["marker"] = "."
plotkwargs["markersize"] = 3
plotkwargs["alpha"] = 0.5
# with no lines, line styles cannot distringuish ions
args.colorbyion = True
for ax, plotitems in zip(axes, plotlist, strict=False):
if xmin != xmax:
ax.set_xlim(left=xmin, right=xmax)
plot_subplot(
ax=ax,
timestepslist=timestepslist,
xlist=xlist,
plotitems=plotitems,
mgilist=mgilist,
modelpath=modelpath,
estimators=estimators,
startfromzero=startfromzero,
args=args,
**plotkwargs,
)
if len(set(mgilist)) == 1 and len(timestepslist[0]) > 1: # single grid cell versus time plot
figure_title = f"{modelname}\nCell {mgilist[0]}"
defaultoutputfile = "plotestimators_cell{modelgridindex:03d}.{format}"
if Path(args.outputfile).is_dir():
args.outputfile = str(Path(args.outputfile) / defaultoutputfile)
outfilename = str(args.outputfile).format(modelgridindex=mgilist[0], format=args.format)
else:
if args.multiplot:
timestep = f"ts{timestepslist[0][0]:02d}"
timedays = f"{at.get_timestep_time(modelpath, timestepslist[0][0]):.2f}d"
else:
timestepmin = min(timestepslist[0])
timestepmax = max(timestepslist[0])
timestep = f"ts{timestepmin:02d}-ts{timestepmax:02d}"
timedays = f"{at.get_timestep_time(modelpath, timestepmin):.2f}d-{at.get_timestep_time(modelpath, timestepmax):.2f}d"
figure_title = f"{modelname}\nTimestep {timestep} ({timedays})"
print("Plotting " + figure_title.replace("\n", " "))
defaultoutputfile = "plotestimators_{timestep}_{timedays}.{format}"
if Path(args.outputfile).is_dir():
args.outputfile = str(Path(args.outputfile) / defaultoutputfile)
assert isinstance(timestepslist[0], list)
outfilename = str(args.outputfile).format(timestep=timestep, timedays=timedays, format=args.format)
if not args.notitle:
axes[0].set_title(figure_title, fontsize=10)
print(f"Saving {outfilename} ...")
fig.savefig(outfilename, dpi=300)
if args.show:
plt.show()
else:
plt.close()
return outfilename
def addargs(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-modelpath", default=".", help="Paths to ARTIS folder (or virtual path e.g. codecomparison/ddc10/cmfgen)"
)
parser.add_argument(
"-modelgridindex", "-cell", "-mgi", type=int, default=None, help="Modelgridindex for time evolution plot"
)
parser.add_argument("-timestep", "-ts", nargs="?", help="Timestep number for internal structure plot")
parser.add_argument("-timedays", "-time", "-t", nargs="?", help="Time in days to plot for internal structure plot")
parser.add_argument("-timemin", type=float, help="Lower time in days")
parser.add_argument("-timemax", type=float, help="Upper time in days")
parser.add_argument("--multiplot", action="store_true", help="Make multiple plots for timesteps in range")
parser.add_argument("-x", help="Horizontal axis variable, e.g. cellid, velocity, timestep, or time")
parser.add_argument("-xmin", type=float, default=-1, help="Plot range: minimum x value")
parser.add_argument("-xmax", type=float, default=-1, help="Plot range: maximum x value")
parser.add_argument(
"-yscale", default="log", choices=["log", "linear"], help="Set yscale to log or linear (default log)"
)
parser.add_argument("--hidexlabel", action="store_true", help="Hide the bottom horizontal axis label")
parser.add_argument(
"--markersonly", action="store_true", help="Plot markers instead of lines (always set for 2D and 3D)"
)
parser.add_argument("-filtermovingavg", type=int, default=0, help="Smoothing length (1 is same as none)")
parser.add_argument(
"-filtersavgol",
nargs=2,
help="Savitzky-Golay filter. Specify the window_length and polyorder.e.g. -filtersavgol 5 3",
)
parser.add_argument("-format", "-f", default="pdf", choices=["pdf", "png"], help="Set format of output plot files")
parser.add_argument("--makegif", action="store_true", help="Make a gif with time evolution (requires --multiplot)")
parser.add_argument("--notitle", action="store_true", help="Suppress the top title from the plot")
parser.add_argument("-plotlist", type=list, default=[], help="Plot list (when calling from Python only)")
parser.add_argument(
"-ionpoptype",
default="elpop",
choices=["absolute", "totalpop", "elpop"],
help="Plot absolute ion populations, or ion populations as a fraction of total or element population",
)
parser.add_argument("--nolegend", action="store_true", help="Suppress the legend from the plot")
parser.add_argument(
"-figscale", type=float, default=1.0, help="Scale factor for plot area. 1.0 is for single-column"
)
parser.add_argument("-scalefigwidth", type=float, default=1.0, help="Scale factor for plot width.")
parser.add_argument("--show", action="store_true", help="Show plot before quitting")
parser.add_argument(
"-o", action="store", dest="outputfile", type=Path, default=Path(), help="Filename for PDF file"
)
parser.add_argument(
"--colorbyion", action="store_true", help="Populations plots colored by ion rather than element"
)
parser.add_argument(
"--classicartis", action="store_true", help="Flag to show using output from classic ARTIS branch"
)
parser.add_argument(
"-readonlymgi",
default=False,
choices=["alongaxis", "cone"], # plan to extend this to e.g. 2D slice
help="Option to read only selected mgi and choice of which mgi to select. Choose which axis with args.axis",
)
parser.add_argument(
"-axis",
default="+z",
choices=["+x", "-x", "+y", "-y", "+z", "-z"],
help="Choose an axis for use with args.readonlymgi. Hint: for negative use e.g. -axis=-z",
)
def main(args: argparse.Namespace | None = None, argsraw: Sequence[str] | None = None, **kwargs) -> None:
"""Plot ARTIS estimators."""
if args is None:
parser = argparse.ArgumentParser(formatter_class=at.CustomArgHelpFormatter, description=__doc__)
addargs(parser)
at.set_args_from_dict(parser, kwargs)
argcomplete.autocomplete(parser)
args = parser.parse_args([] if kwargs else argsraw)
modelpath = Path(args.modelpath)
modelname = at.get_model_name(modelpath)
if not args.timedays and not args.timestep and args.modelgridindex is not None:
args.timestep = f"0-{len(at.get_timestep_times(modelpath)) - 1}"
(timestepmin, timestepmax, args.timemin, args.timemax) = at.get_time_range(
modelpath, args.timestep, args.timemin, args.timemax, args.timedays
)
if args.readonlymgi:
args.sliceaxis = args.axis[1]
assert args.axis[0] in {"+", "-"}
args.positive_axis = args.axis[0] == "+"
axes = ["x", "y", "z"]
axes.remove(args.sliceaxis)
args.other_axis1 = axes[0]
args.other_axis2 = axes[1]
print(
f"Plotting estimators for '{modelname}' timesteps {timestepmin} to {timestepmax} "
f"({args.timemin:.1f} to {args.timemax:.1f}d)"
)
plotlist = args.plotlist or [
# [["initabundances", ["Fe", "Ni_stable", "Ni_56"]]],
# ['heating_dep', 'heating_coll', 'heating_bf', 'heating_ff',
# ['_yscale', 'linear']],
# ['cooling_adiabatic', 'cooling_coll', 'cooling_fb', 'cooling_ff',
# ['_yscale', 'linear']],
# [
# (pl.col("heating_coll") - pl.col("cooling_coll")).alias("collisional heating - cooling"),
# ["_yscale", "linear"],
# ],
# [['initmasses', ['Ni_56', 'He', 'C', 'Mg']]],
# ['heating_gamma/gamma_dep'],
# ["nne", ["_ymin", 1e5], ["_ymax", 1e10]],
["rho", ["_yscale", "log"], ["_ymin", 1e-16]],
["TR", ["_yscale", "linear"]], # , ["_ymin", 1000], ["_ymax", 15000]
# ["Te"],
# ["Te", "TR"],
[["averageionisation", ["Sr"]]],
# [["averageexcitation", ["Fe II", "Fe III"]]],
# [["populations", ["Sr90", "Sr91", "Sr92", "Sr94"]]],
[["populations", ["Sr I", "Sr II", "Sr III", "Sr IV"]]],
# [['populations', ['He I', 'He II', 'He III']]],
# [['populations', ['C I', 'C II', 'C III', 'C IV', 'C V']]],
# [['populations', ['O I', 'O II', 'O III', 'O IV']]],
# [['populations', ['Ne I', 'Ne II', 'Ne III', 'Ne IV', 'Ne V']]],
# [['populations', ['Si I', 'Si II', 'Si III', 'Si IV', 'Si V']]],
# [['populations', ['Cr I', 'Cr II', 'Cr III', 'Cr IV', 'Cr V']]],
# [['populations', ['Fe I', 'Fe II', 'Fe III', 'Fe IV', 'Fe V', 'Fe VI', 'Fe VII', 'Fe VIII']]],
# [['populations', ['Co I', 'Co II', 'Co III', 'Co IV', 'Co V', 'Co VI', 'Co VII']]],
# [['populations', ['Ni I', 'Ni II', 'Ni III', 'Ni IV', 'Ni V', 'Ni VI', 'Ni VII']]],
# [['populations', ['Fe II', 'Fe III', 'Co II', 'Co III', 'Ni II', 'Ni III']]],
# [['populations', ['Fe I', 'Fe II', 'Fe III', 'Fe IV', 'Fe V', 'Ni II']]],
# [['RRC_LTE_Nahar', ['Fe II', 'Fe III', 'Fe IV', 'Fe V']]],
# [['RRC_LTE_Nahar', ['Co II', 'Co III', 'Co IV', 'Co V']]],
# [['RRC_LTE_Nahar', ['Ni I', 'Ni II', 'Ni III', 'Ni IV', 'Ni V', 'Ni VI', 'Ni VII']]],
# [['Alpha_R / RRC_LTE_Nahar', ['Fe II', 'Fe III', 'Fe IV', 'Fe V', 'Ni III']]],
# [['gamma_NT', ['Fe I', 'Fe II', 'Fe III', 'Fe IV', 'Fe V', 'Ni II']]],
]
if args.readonlymgi:
if args.readonlymgi == "alongaxis":
print(f"Getting mgi along {args.axis} axis")
dfselectedcells = at.inputmodel.slice1dfromconein3dmodel.get_profile_along_axis(args=args)
elif args.readonlymgi == "cone":
print(f"Getting mgi lying within a cone around {args.axis} axis")
dfselectedcells = at.inputmodel.slice1dfromconein3dmodel.make_cone(args)
else:
msg = f"Invalid args.readonlymgi: {args.readonlymgi}"
raise ValueError(msg)
dfselectedcells = dfselectedcells[dfselectedcells["rho"] > 0]
args.modelgridindex = list(dfselectedcells["inputcellid"])
timesteps_included = list(range(timestepmin, timestepmax + 1))
if args.classicartis:
import artistools.estimators.estimators_classic
modeldata, _ = at.inputmodel.get_modeldata(modelpath)
estimatorsdict = artistools.estimators.estimators_classic.read_classic_estimators(modelpath, modeldata)
assert estimatorsdict is not None
estimators = pl.DataFrame([
{"timestep": ts, "modelgridindex": mgi, **estimvals} for (ts, mgi), estimvals in estimatorsdict.items()
]).lazy()
else:
estimators = at.estimators.scan_estimators(
modelpath=modelpath, modelgridindex=args.modelgridindex, timestep=tuple(timesteps_included)
)
assert estimators is not None
tmids = at.get_timestep_times(modelpath, loc="mid")
estimators = estimators.join(
pl.DataFrame({"timestep": range(len(tmids)), "time_mid": tmids})
.with_columns(pl.col("timestep").cast(pl.Int32))
.lazy(),
on="timestep",
how="left",
coalesce=True,
)
tswithdata = estimators.select("timestep").unique().collect().to_series()
for ts in reversed(timesteps_included):
if ts not in tswithdata:
timesteps_included.remove(ts)
print(f"ts {ts} requested but no data found. Removing.")
if not timesteps_included:
print("No timesteps with data are included")
return
assoc_cells, _ = at.get_grid_mapping(modelpath)
outdir = args.outputfile if (args.outputfile).is_dir() else Path()
if not args.readonlymgi and (args.modelgridindex is not None or args.x in {"time", "timestep"}):
# plot time evolution in specific cell
if not args.x:
args.x = "time"
assert isinstance(args.modelgridindex, int)
timestepslist_unfiltered = [[ts] for ts in timesteps_included]
if not assoc_cells.get(args.modelgridindex):
msg = f"cell {args.modelgridindex} is empty. no estimators available"
raise ValueError(msg)
make_plot(
modelpath=modelpath,
timestepslist_unfiltered=timestepslist_unfiltered,
estimators=estimators,
xvariable=args.x,
plotlist=plotlist,
args=args,
)
else:
# plot a range of cells in a time snapshot showing internal structure
if not args.x:
args.x = "velocity"
dfmodel, modelmeta = at.inputmodel.get_modeldata_polars(modelpath, derived_cols=["ALL"])
if args.x == "velocity" and modelmeta["vmax_cmps"] > 0.3 * 29979245800:
args.x = "beta"
dfmodel = dfmodel.filter(pl.col("vel_r_mid") <= modelmeta["vmax_cmps"]).rename({
colname: f"init_{colname}"
for colname in dfmodel.collect_schema().names()
if not colname.startswith("vel_") and colname not in {"inputcellid", "modelgridindex", "mass_g"}
})
estimators = estimators.join(dfmodel, on="modelgridindex", suffix="_initmodel").with_columns(
rho=pl.col("init_rho") * (modelmeta["t_model_init_days"] / pl.col("time_mid")) ** 3
)
if args.readonlymgi:
estimators = estimators.filter(pl.col("modelgridindex").is_in(args.modelgridindex))
if args.classicartis:
modeldata, _ = at.inputmodel.get_modeldata(modelpath)
allnonemptymgilist = [
modelgridindex
for modelgridindex in modeldata.index
if not estimators.filter(pl.col("modelgridindex") == modelgridindex)
.select("modelgridindex")
.lazy()
.collect()
.is_empty()
]
else:
allnonemptymgilist = [mgi for mgi, assocpropcells in assoc_cells.items() if assocpropcells]
estimators = estimators.filter(pl.col("modelgridindex").is_in(allnonemptymgilist)).filter(
pl.col("timestep").is_in(timesteps_included)
)
frames_timesteps_included = (
[[ts] for ts in range(timestepmin, timestepmax + 1)] if args.multiplot else [timesteps_included]
)
if args.makegif:
args.multiplot = True
args.format = "png"
outputfiles = []
for timesteps_included in frames_timesteps_included:
timestepslist_unfiltered = [timesteps_included] * len(allnonemptymgilist)
outfilename = make_plot(
modelpath=modelpath,
timestepslist_unfiltered=timestepslist_unfiltered,
estimators=estimators,
xvariable=args.x,
plotlist=plotlist,
args=args,
)
outputfiles.append(outfilename)
if len(outputfiles) > 1:
if args.makegif:
assert args.multiplot
assert args.format == "png"
import imageio.v2 as iio
gifname = outdir / f"plotestim_evolution_ts{timestepmin:03d}_ts{timestepmax:03d}.gif"
with iio.get_writer(gifname, mode="I", duration=1000) as writer:
for filename in outputfiles:
image = iio.imread(filename)
writer.append_data(image) # type: ignore[attr-defined]
print(f"Created gif: {gifname}")
elif args.format == "pdf":
at.merge_pdf_files(outputfiles)
if __name__ == "__main__":
main()
|
artis-mcrtREPO_NAMEartistoolsPATH_START.@artistools_extracted@artistools-main@artistools@estimators@plotestimators.py@.PATH_END.py
|
{
"filename": "test_propmptlayer_openai_chat.py",
"repo_name": "langchain-ai/langchain",
"repo_path": "langchain_extracted/langchain-master/libs/community/tests/integration_tests/llms/test_propmptlayer_openai_chat.py",
"type": "Python"
}
|
"""Test PromptLayer OpenAIChat API wrapper."""
from pathlib import Path
import pytest
from langchain_community.llms.loading import load_llm
from langchain_community.llms.promptlayer_openai import PromptLayerOpenAIChat
def test_promptlayer_openai_chat_call() -> None:
"""Test valid call to promptlayer openai."""
llm = PromptLayerOpenAIChat(max_tokens=10) # type: ignore[call-arg]
output = llm.invoke("Say foo:")
assert isinstance(output, str)
def test_promptlayer_openai_chat_stop_valid() -> None:
"""Test promptlayer openai stop logic on valid configuration."""
query = "write an ordered list of five items"
first_llm = PromptLayerOpenAIChat(stop="3", temperature=0) # type: ignore[call-arg]
first_output = first_llm.invoke(query)
second_llm = PromptLayerOpenAIChat(temperature=0) # type: ignore[call-arg]
second_output = second_llm.invoke(query, stop=["3"])
# Because it stops on new lines, shouldn't return anything
assert first_output == second_output
def test_promptlayer_openai_chat_stop_error() -> None:
"""Test promptlayer openai stop logic on bad configuration."""
llm = PromptLayerOpenAIChat(stop="3", temperature=0) # type: ignore[call-arg]
with pytest.raises(ValueError):
llm.invoke("write an ordered list of five items", stop=["\n"])
def test_saving_loading_llm(tmp_path: Path) -> None:
"""Test saving/loading an promptlayer OpenAPI LLM."""
llm = PromptLayerOpenAIChat(max_tokens=10) # type: ignore[call-arg]
llm.save(file_path=tmp_path / "openai.yaml")
loaded_llm = load_llm(tmp_path / "openai.yaml")
assert loaded_llm == llm
|
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@tests@integration_tests@llms@test_propmptlayer_openai_chat.py@.PATH_END.py
|
{
"filename": "_font.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/graph_objs/sankey/link/hoverlabel/_font.py",
"type": "Python"
}
|
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "sankey.link.hoverlabel"
_path_str = "sankey.link.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizesrc",
"style",
"stylesrc",
"textcase",
"textcasesrc",
"variant",
"variantsrc",
"weight",
"weightsrc",
}
# color
# -----
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
# colorsrc
# --------
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
# family
# ------
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans", "Droid Serif", "Droid Sans Mono", "Gravitas One",
"Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow",
"Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
# familysrc
# ---------
@property
def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `family`.
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"]
@familysrc.setter
def familysrc(self, val):
self["familysrc"] = val
# lineposition
# ------------
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
- A list or array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
# linepositionsrc
# ---------------
@property
def linepositionsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`lineposition`.
The 'linepositionsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["linepositionsrc"]
@linepositionsrc.setter
def linepositionsrc(self, val):
self["linepositionsrc"] = val
# shadow
# ------
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
# shadowsrc
# ---------
@property
def shadowsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `shadow`.
The 'shadowsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["shadowsrc"]
@shadowsrc.setter
def shadowsrc(self, val):
self["shadowsrc"] = val
# size
# ----
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
# sizesrc
# -------
@property
def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `size`.
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"]
@sizesrc.setter
def sizesrc(self, val):
self["sizesrc"] = val
# style
# -----
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
# stylesrc
# --------
@property
def stylesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `style`.
The 'stylesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["stylesrc"]
@stylesrc.setter
def stylesrc(self, val):
self["stylesrc"] = val
# textcase
# --------
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
# textcasesrc
# -----------
@property
def textcasesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `textcase`.
The 'textcasesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["textcasesrc"]
@textcasesrc.setter
def textcasesrc(self, val):
self["textcasesrc"] = val
# variant
# -------
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
# variantsrc
# ----------
@property
def variantsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `variant`.
The 'variantsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["variantsrc"]
@variantsrc.setter
def variantsrc(self, val):
self["variantsrc"] = val
# weight
# ------
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
# weightsrc
# ---------
@property
def weightsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `weight`.
The 'weightsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["weightsrc"]
@weightsrc.setter
def weightsrc(self, val):
self["weightsrc"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans", "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
"""
def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
lineposition=None,
linepositionsrc=None,
shadow=None,
shadowsrc=None,
size=None,
sizesrc=None,
style=None,
stylesrc=None,
textcase=None,
textcasesrc=None,
variant=None,
variantsrc=None,
weight=None,
weightsrc=None,
**kwargs,
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.sankey.link.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans", "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
Returns
-------
Font
"""
super(Font, self).__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.sankey.link.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.sankey.link.hoverlabel.Font`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("colorsrc", None)
_v = colorsrc if colorsrc is not None else _v
if _v is not None:
self["colorsrc"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("familysrc", None)
_v = familysrc if familysrc is not None else _v
if _v is not None:
self["familysrc"] = _v
_v = arg.pop("lineposition", None)
_v = lineposition if lineposition is not None else _v
if _v is not None:
self["lineposition"] = _v
_v = arg.pop("linepositionsrc", None)
_v = linepositionsrc if linepositionsrc is not None else _v
if _v is not None:
self["linepositionsrc"] = _v
_v = arg.pop("shadow", None)
_v = shadow if shadow is not None else _v
if _v is not None:
self["shadow"] = _v
_v = arg.pop("shadowsrc", None)
_v = shadowsrc if shadowsrc is not None else _v
if _v is not None:
self["shadowsrc"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
_v = arg.pop("sizesrc", None)
_v = sizesrc if sizesrc is not None else _v
if _v is not None:
self["sizesrc"] = _v
_v = arg.pop("style", None)
_v = style if style is not None else _v
if _v is not None:
self["style"] = _v
_v = arg.pop("stylesrc", None)
_v = stylesrc if stylesrc is not None else _v
if _v is not None:
self["stylesrc"] = _v
_v = arg.pop("textcase", None)
_v = textcase if textcase is not None else _v
if _v is not None:
self["textcase"] = _v
_v = arg.pop("textcasesrc", None)
_v = textcasesrc if textcasesrc is not None else _v
if _v is not None:
self["textcasesrc"] = _v
_v = arg.pop("variant", None)
_v = variant if variant is not None else _v
if _v is not None:
self["variant"] = _v
_v = arg.pop("variantsrc", None)
_v = variantsrc if variantsrc is not None else _v
if _v is not None:
self["variantsrc"] = _v
_v = arg.pop("weight", None)
_v = weight if weight is not None else _v
if _v is not None:
self["weight"] = _v
_v = arg.pop("weightsrc", None)
_v = weightsrc if weightsrc is not None else _v
if _v is not None:
self["weightsrc"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@graph_objs@sankey@link@hoverlabel@_font.py@.PATH_END.py
|
{
"filename": "build_py.py",
"repo_name": "numpy/numpy",
"repo_path": "numpy_extracted/numpy-main/numpy/distutils/command/build_py.py",
"type": "Python"
}
|
from distutils.command.build_py import build_py as old_build_py
from numpy.distutils.misc_util import is_string
class build_py(old_build_py):
def run(self):
build_src = self.get_finalized_command('build_src')
if build_src.py_modules_dict and self.packages is None:
self.packages = list(build_src.py_modules_dict.keys ())
old_build_py.run(self)
def find_package_modules(self, package, package_dir):
modules = old_build_py.find_package_modules(self, package, package_dir)
# Find build_src generated *.py files.
build_src = self.get_finalized_command('build_src')
modules += build_src.py_modules_dict.get(package, [])
return modules
def find_modules(self):
old_py_modules = self.py_modules[:]
new_py_modules = [_m for _m in self.py_modules if is_string(_m)]
self.py_modules[:] = new_py_modules
modules = old_build_py.find_modules(self)
self.py_modules[:] = old_py_modules
return modules
# XXX: Fix find_source_files for item in py_modules such that item is 3-tuple
# and item[2] is source file.
|
numpyREPO_NAMEnumpyPATH_START.@numpy_extracted@numpy-main@numpy@distutils@command@build_py.py@.PATH_END.py
|
{
"filename": "GW170817_snellius.py",
"repo_name": "ThibeauWouters/TurboPE-BNS",
"repo_path": "TurboPE-BNS_extracted/TurboPE-BNS-main/JS_estimate/GW170817_TaylorF2/varied_runs/GW170817_snellius.py",
"type": "Python"
}
|
import os
from jimgw.jim import Jim
from jimgw.single_event.detector import H1, L1, V1
from jimgw.single_event.likelihood import HeterodynedTransientLikelihoodFD
from jimgw.single_event.waveform import RippleTaylorF2
from jimgw.prior import Uniform, PowerLaw, Composite
import jax.numpy as jnp
import jax
import time
import numpy as np
jax.config.update("jax_enable_x64", True)
import shutil
import numpy as np
import matplotlib.pyplot as plt
import optax
import sys
sys.path.append("../")
import utils_plotting as utils
print(jax.devices())
################
### PREAMBLE ###
################
default_corner_kwargs = dict(bins=40,
smooth=1.,
show_titles=False,
label_kwargs=dict(fontsize=16),
title_kwargs=dict(fontsize=16),
color="blue",
# quantiles=[],
# levels=[0.9],
plot_density=True,
plot_datapoints=False,
fill_contours=True,
max_n_ticks=4,
min_n_ticks=3,
save=False)
params = {
"axes.labelsize": 30,
"axes.titlesize": 30,
"text.usetex": True,
"font.family": "serif",
}
plt.rcParams.update(params)
labels = [r'$M_c/M_\odot$', r'$q$', r'$\chi_1$', r'$\chi_2$', r'$\Lambda$', r'$\delta\Lambda$', r'$d_{\rm{L}}/{\rm Mpc}$',
r'$t_c$', r'$\phi_c$', r'$\iota$', r'$\psi$', r'$\alpha$', r'$\delta$']
naming = ['M_c', 'q', 's1_z', 's2_z', 'lambda_1', 'lambda_2', 'd_L', 't_c', 'phase_c', 'cos_iota', 'psi', 'ra', 'sin_dec']
data_path = "/home/twouters2/gw-datasets/GW170817/" # on snellius
start_runtime = time.time()
############
### BODY ###
############
### Data definitions
total_time_start = time.time()
gps = 1187008882.43
trigger_time = gps
fmin = 23
fmax = 2048
minimum_frequency = fmin
maximum_frequency = fmax
T = 128
duration = T
post_trigger_duration = 2
epoch = duration - post_trigger_duration
f_ref = fmin
tukey_alpha = 2 / (T / 2)
### Getting detector data
# This is our preprocessed data obtained from the TXT files at the GWOSC website (the GWF gave me NaNs?)
H1.frequencies = np.genfromtxt(f'{data_path}H1_freq.txt')
H1_data_re, H1_data_im = np.genfromtxt(f'{data_path}H1_data_re.txt'), np.genfromtxt(f'{data_path}H1_data_im.txt')
H1.data = H1_data_re + 1j * H1_data_im
L1.frequencies = np.genfromtxt(f'{data_path}L1_freq.txt')
L1_data_re, L1_data_im = np.genfromtxt(f'{data_path}L1_data_re.txt'), np.genfromtxt(f'{data_path}L1_data_im.txt')
L1.data = L1_data_re + 1j * L1_data_im
V1.frequencies = np.genfromtxt(f'{data_path}V1_freq.txt')
V1_data_re, V1_data_im = np.genfromtxt(f'{data_path}V1_data_re.txt'), np.genfromtxt(f'{data_path}V1_data_im.txt')
V1.data = V1_data_re + 1j * V1_data_im
# Load the PSD
H1.psd = H1.load_psd(H1.frequencies, psd_file = data_path + "GW170817-IMRD_data0_1187008882-43_generation_data_dump.pickle_H1_psd.txt")
L1.psd = L1.load_psd(L1.frequencies, psd_file = data_path + "GW170817-IMRD_data0_1187008882-43_generation_data_dump.pickle_L1_psd.txt")
V1.psd = V1.load_psd(V1.frequencies, psd_file = data_path + "GW170817-IMRD_data0_1187008882-43_generation_data_dump.pickle_V1_psd.txt")
### Define priors
# Internal parameters
Mc_prior = Uniform(1.18, 1.21, naming=["M_c"])
q_prior = Uniform(
0.125,
1.0,
naming=["q"],
transforms={"q": ("eta", lambda params: params["q"] / (1 + params["q"]) ** 2)},
)
s1z_prior = Uniform(-0.05, 0.05, naming=["s1_z"])
s2z_prior = Uniform(-0.05, 0.05, naming=["s2_z"])
lambda_1_prior = Uniform(0.0, 5000.0, naming=["lambda_1"])
lambda_2_prior = Uniform(0.0, 5000.0, naming=["lambda_2"])
dL_prior = Uniform(1.0, 75.0, naming=["d_L"])
# dL_prior = PowerLaw(1.0, 75.0, 2.0, naming=["d_L"])
t_c_prior = Uniform(-0.1, 0.1, naming=["t_c"])
phase_c_prior = Uniform(0.0, 2 * jnp.pi, naming=["phase_c"])
cos_iota_prior = Uniform(
-1.0,
1.0,
naming=["cos_iota"],
transforms={
"cos_iota": (
"iota",
lambda params: jnp.arccos(
jnp.arcsin(jnp.sin(params["cos_iota"] / 2 * jnp.pi)) * 2 / jnp.pi
),
)
},
)
psi_prior = Uniform(0.0, jnp.pi, naming=["psi"])
ra_prior = Uniform(0.0, 2 * jnp.pi, naming=["ra"])
sin_dec_prior = Uniform(
-1.0,
1.0,
naming=["sin_dec"],
transforms={
"sin_dec": (
"dec",
lambda params: jnp.arcsin(
jnp.arcsin(jnp.sin(params["sin_dec"] / 2 * jnp.pi)) * 2 / jnp.pi
),
)
},
)
prior_list = [
Mc_prior,
q_prior,
s1z_prior,
s2z_prior,
lambda_1_prior,
lambda_2_prior,
dL_prior,
t_c_prior,
phase_c_prior,
cos_iota_prior,
psi_prior,
ra_prior,
sin_dec_prior,
]
prior = Composite(prior_list)
# The following only works if every prior has xmin and xmax property, which is OK for Uniform and Powerlaw
bounds = jnp.array([[p.xmin, p.xmax] for p in prior.priors])
### Create likelihood object
# for reproducibility, still override
ref_params = {
'M_c': 1.19793583,
'eta': 0.24794374,
's1_z': 0.00220637,
's2_z': 0.05,
'lambda_1': 105.12916663,
'lambda_2': 0.0,
'd_L': 45.41592353,
't_c': 0.00220588,
'phase_c': 5.76822606,
'iota': 2.46158044,
'psi': 2.09118099,
'ra': 5.03335133,
'dec': 0.01679998
}
n_bins = 100
likelihood = HeterodynedTransientLikelihoodFD([H1, L1, V1], prior=prior, bounds=bounds, waveform=RippleTaylorF2(f_ref=f_ref), trigger_time=gps, duration=T, n_bins=n_bins, ref_params=ref_params)
print("Running with n_bins = ", n_bins)
# Local sampler args
eps = 1e-3
n_dim = 13
mass_matrix = jnp.eye(n_dim)
mass_matrix = mass_matrix.at[0,0].set(1e-5)
mass_matrix = mass_matrix.at[1,1].set(1e-4)
mass_matrix = mass_matrix.at[2,2].set(1e-3)
mass_matrix = mass_matrix.at[3,3].set(1e-3)
mass_matrix = mass_matrix.at[7,7].set(1e-5)
mass_matrix = mass_matrix.at[11,11].set(1e-2)
mass_matrix = mass_matrix.at[12,12].set(1e-2)
local_sampler_arg = {"step_size": mass_matrix * eps}
# Build the learning rate scheduler
n_loop_training = 400
n_epochs = 50
total_epochs = n_epochs * n_loop_training
start = int(total_epochs / 10)
start_lr = 1e-3
end_lr = 1e-5
power = 4.0
schedule_fn = optax.polynomial_schedule(
start_lr, end_lr, power, total_epochs-start, transition_begin=start)
scheduler_str = f"polynomial_schedule({start_lr}, {end_lr}, {power}, {total_epochs-start}, {start})"
# Create jim object
outdir_name = "./outdir/"
# jim = Jim(
# likelihood,
# prior,
# n_loop_training=n_loop_training,
# n_loop_production=30,
# n_local_steps=5,
# n_global_steps=400,
# n_chains=1000,
# n_epochs=n_epochs,
# learning_rate=schedule_fn,
# max_samples=50000,
# momentum=0.9,
# batch_size=50000,
# use_global=True,
# keep_quantile=0.0,
# train_thinning=10,
# output_thinning=30,
# local_sampler_arg=local_sampler_arg,
# stopping_criterion_global_acc = 0.15,
# outdir_name=outdir_name
# )
jim = Jim(
likelihood,
prior,
n_loop_training=400,
n_loop_production=20,
n_local_steps=10,
n_global_steps=300,
n_chains=1000,
n_epochs=100,
learning_rate=schedule_fn,
max_samples=50000,
momentum=0.9,
batch_size=50000,
use_global=True,
keep_quantile=0.0,
train_thinning=10,
output_thinning=30,
local_sampler_arg=local_sampler_arg,
stopping_criterion_global_acc = 0.20,
outdir_name=outdir_name
) # n_loops_maximize_likelihood = 2000, ## unused
### Heavy computation begins
jim.sample(jax.random.PRNGKey(41))
### Heavy computation ends
# === Show results, save output ===
# Print a summary to screen:
jim.print_summary()
outdir = outdir_name
# Save and plot the results of the run
# - training phase
name = outdir + f'results_training.npz'
print(f"Saving samples to {name}")
state = jim.Sampler.get_sampler_state(training=True)
chains, log_prob, local_accs, global_accs, loss_vals = state["chains"], state[
"log_prob"], state["local_accs"], state["global_accs"], state["loss_vals"]
local_accs = jnp.mean(local_accs, axis=0)
global_accs = jnp.mean(global_accs, axis=0)
np.savez(name, log_prob=log_prob, local_accs=local_accs,
global_accs=global_accs, loss_vals=loss_vals)
utils.plot_accs(local_accs, "Local accs (training)",
"local_accs_training", outdir)
utils.plot_accs(global_accs, "Global accs (training)",
"global_accs_training", outdir)
utils.plot_loss_vals(loss_vals, "Loss", "loss_vals", outdir)
utils.plot_log_prob(log_prob, "Log probability (training)",
"log_prob_training", outdir)
# - production phase
name = outdir + f'results_production.npz'
state = jim.Sampler.get_sampler_state(training=False)
chains, log_prob, local_accs, global_accs = state["chains"], state[
"log_prob"], state["local_accs"], state["global_accs"]
local_accs = jnp.mean(local_accs, axis=0)
global_accs = jnp.mean(global_accs, axis=0)
np.savez(name, chains=chains, log_prob=log_prob,
local_accs=local_accs, global_accs=global_accs)
utils.plot_accs(local_accs, "Local accs (production)",
"local_accs_production", outdir)
utils.plot_accs(global_accs, "Global accs (production)",
"global_accs_production", outdir)
utils.plot_log_prob(log_prob, "Log probability (production)",
"log_prob_production", outdir)
# Plot the chains as corner plots
utils.plot_chains(chains, "chains_production", outdir, truths=None)
# Save the NF and show a plot of samples from the flow
print("Saving the NF")
jim.Sampler.save_flow(outdir + "nf_model")
name = outdir + 'results_NF.npz'
chains = jim.Sampler.sample_flow(5_000)
np.savez(name, chains=chains)
# Final steps
# Finally, copy over this script to the outdir for reproducibility
shutil.copy2(__file__, outdir + "copy_script.py")
print("Saving the jim hyperparameters")
# Change scheduler from function to a string representation
try:
jim.hyperparameters["learning_rate"] = scheduler_str
jim.Sampler.hyperparameters["learning_rate"] = scheduler_str
jim.save_hyperparameters(outdir=outdir)
except Exception as e:
# Sometimes, something breaks, so avoid crashing the whole thing
print(f"Could not save hyperparameters in script: {e}")
print("Finished successfully")
end_runtime = time.time()
runtime = end_runtime - start_runtime
print(f"Time taken: {runtime} seconds ({(runtime)/60} minutes)")
print(f"Saving runtime")
with open(outdir + 'runtime.txt', 'w') as file:
file.write(str(runtime))
|
ThibeauWoutersREPO_NAMETurboPE-BNSPATH_START.@TurboPE-BNS_extracted@TurboPE-BNS-main@JS_estimate@GW170817_TaylorF2@varied_runs@GW170817_snellius.py@.PATH_END.py
|
{
"filename": "prepare_input.py",
"repo_name": "daniel-muthukrishna/astrorapid",
"repo_path": "astrorapid_extracted/astrorapid-master/astrorapid/prepare_input.py",
"type": "Python"
}
|
import numpy as np
from astrorapid.prepare_arrays import PrepareArrays
class PrepareInputArrays(PrepareArrays):
def __init__(self, passbands=('g', 'r'), contextual_info=('redshift',), bcut=True, zcut=None,
nobs=50, mintime=-70, maxtime=80, timestep=3.0):
PrepareArrays.__init__(self, passbands, contextual_info, nobs, mintime, maxtime, timestep)
self.bcut = bcut
self.zcut = zcut
def prepare_input_arrays(self, lightcurves):
nobjects = len(lightcurves)
X = np.zeros(shape=(nobjects, self.nfeatures, self.nobs))
timesX = np.zeros(shape=(nobjects, self.nobs))
objids_list = []
orig_lc = []
deleterows = []
trigger_mjds = []
for i, (objid, data) in enumerate(lightcurves.items()):
print("Preparing light curve {} of {}".format(i, nobjects))
redshift = data.meta['redshift']
b = data.meta['b']
trigger_mjd = data.meta['trigger_mjd']
# Make cuts
deleterows, deleted = self.make_cuts(data, i, deleterows, b, redshift, class_num=None, bcut=self.bcut,
zcut=self.zcut, pre_trigger=False)
if deleted:
continue
tinterp, len_t = self.get_t_interp(data)
timesX[i][0:len_t] = tinterp
orig_lc.append(data)
objids_list.append(objid)
trigger_mjds.append(trigger_mjd)
X = self.update_X(X, i, data, tinterp, len_t, objid, self.contextual_info, data.meta)
deleterows = np.array(deleterows)
if len(deleterows) > 0:
X = np.delete(X, deleterows, axis=0)
timesX = np.delete(timesX, deleterows, axis=0)
# Correct shape for keras is (N_objects, N_timesteps, N_passbands) (where N_timesteps is lookback time)
X = X.swapaxes(2, 1)
return X, orig_lc, timesX, objids_list, trigger_mjds
|
daniel-muthukrishnaREPO_NAMEastrorapidPATH_START.@astrorapid_extracted@astrorapid-master@astrorapid@prepare_input.py@.PATH_END.py
|
{
"filename": "alpha-gamma-approx.ipynb",
"repo_name": "pynucastro/pynucastro",
"repo_path": "pynucastro_extracted/pynucastro-main/docs/source/alpha-gamma-approx.ipynb",
"type": "Jupyter Notebook"
}
|
# Approximating alpha-capture
pynucastro can use rate approximations for $A(\alpha,\gamma)B$ and $A(\alpha,p)X(p,\gamma)B$,
combining them into a single effective rate by assuming that the protons and nucleus $X$ are in equilibrium.
```python
import pynucastro as pyna
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
```
Let's create a simple network that has both an $(\alpha, \gamma)$ and
$(\alpha, p)(p, \gamma)$ sequence.
```python
reaclib_library = pyna.ReacLibLibrary()
mylib = reaclib_library.linking_nuclei(["mg24", "al27", "si28", "p31", "s32", "he4", "p"])
pynet = pyna.PythonNetwork(libraries=[mylib])
```
```python
fig = pynet.plot(rotated=True, curved_edges=True)
```

```python
pynet.write_network("full_net.py")
```
```python
import full_net
```
## Integrating the full network
Now let's integrate this. We'll start with half ${}^{24}\mathrm{Mg}$ and half $\alpha$ by mass.
```python
rho = 1.e7
T = 3e9
X0 = np.zeros(full_net.nnuc)
X0[full_net.jhe4] = 0.5
X0[full_net.jmg24] = 0.5
Y0 = X0 / full_net.A
```
```python
tmax = 1.e-3
sol = solve_ivp(full_net.rhs, [0, tmax], Y0, method="BDF",
dense_output=True, args=(rho, T), rtol=1.e-6, atol=1.e-10)
```
```python
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(full_net.nnuc):
ax.loglog(sol.t, sol.y[i,:] * full_net.A[i], label=f"X({full_net.names[i].capitalize()})")
ax.legend()
ax.set_xlim(1.e-10, 1.e-3)
ax.set_ylim(1.e-12, 1)
fig.set_size_inches((10, 8))
```

## Approximate Version
Now we will approximate the rates, combining $(\alpha, \gamma)$ and
$(\alpha, p)(p, \gamma)$ into a single effective rate.
The routine `make_ap_pg_approx()` will find all of the rates that make up that sequence and create a
single `ApproximateRate` that captures the effective rate. The original rates will still be stored in the `ApproximateRate` object and will be evaluated to compute the needed approximation when the effective rate is evaluated.
```python
pynet.make_ap_pg_approx()
```
using approximate rate Mg24 + He4 ⟶ Si28 + 𝛾
using approximate rate Si28 ⟶ Mg24 + He4
using approximate rate Si28 + He4 ⟶ S32 + 𝛾
using approximate rate S32 ⟶ Si28 + He4
removing rate Mg24 + He4 ⟶ Si28 + 𝛾
removing rate Mg24 + He4 ⟶ p + Al27
removing rate Al27 + p ⟶ Si28 + 𝛾
removing rate Si28 ⟶ He4 + Mg24
removing rate Si28 ⟶ p + Al27
removing rate Al27 + p ⟶ He4 + Mg24
removing rate Si28 + He4 ⟶ S32 + 𝛾
removing rate Si28 + He4 ⟶ p + P31
removing rate P31 + p ⟶ S32 + 𝛾
removing rate S32 ⟶ He4 + Si28
removing rate S32 ⟶ p + P31
removing rate P31 + p ⟶ He4 + Si28
```python
pynet
```
P31 ⟶ He4 + Al27
Al27 + He4 ⟶ P31 + 𝛾
Mg24 + He4 ⟶ Si28 + 𝛾
Si28 ⟶ Mg24 + He4
Si28 + He4 ⟶ S32 + 𝛾
S32 ⟶ Si28 + He4
Since we no longer care about the ${}^{27}\mathrm{Al}$ and ${}^{31}\mathrm{P}$, we can remove them from the network. The `ApproximateRate` object still knows that these are the intermediate nucleus, but now they
won't explicitly appear as one of the nuclei in the network.
```python
pynet.remove_nuclei(["al27", "p31"])
```
looking to remove P31 ⟶ He4 + Al27
looking to remove Al27 + He4 ⟶ P31 + 𝛾
looking to remove P31 ⟶ He4 + Al27
looking to remove Al27 + He4 ⟶ P31 + 𝛾
Note that since no reactions consume protons after that removal, the protons are all removed from the network, reducing its size from 7 nuclei to 4
```python
print(pynet.network_overview())
```
He4
consumed by:
Mg24 + He4 ⟶ Si28 + 𝛾
Si28 + He4 ⟶ S32 + 𝛾
produced by:
Si28 ⟶ Mg24 + He4
S32 ⟶ Si28 + He4
Mg24
consumed by:
Mg24 + He4 ⟶ Si28 + 𝛾
produced by:
Si28 ⟶ Mg24 + He4
Si28
consumed by:
Si28 ⟶ Mg24 + He4
Si28 + He4 ⟶ S32 + 𝛾
produced by:
Mg24 + He4 ⟶ Si28 + 𝛾
S32 ⟶ Si28 + He4
S32
consumed by:
S32 ⟶ Si28 + He4
produced by:
Si28 + He4 ⟶ S32 + 𝛾
```python
fig = pynet.plot(rotated=True, curved_edges=True)
```

As we see above, the nuclei ${}^{27}\mathrm{Al}$ and ${}^{31}\mathrm{P}$ no longer appear in the network, but the links to them are still understood to the network. This reduces the size of the network, while still preserving those flows.
```python
pynet.write_network("approx_net.py")
```
```python
import approx_net
```
The `PythonNetwork` knows how to write out the code needed to evaluate the rate approximation. For instance, the evolution of ${}^{4}\mathrm{He}$ is determined as:
```python
print(pynet.full_ydot_string(pyna.Nucleus("he4")))
```
dYdt[jhe4] = (
-rho*Y[jhe4]*Y[jmg24]*rate_eval.Mg24_He4__Si28__approx
-rho*Y[jhe4]*Y[jsi28]*rate_eval.Si28_He4__S32__approx
+Y[jsi28]*rate_eval.Si28__Mg24_He4__approx
+Y[js32]*rate_eval.S32__Si28_He4__approx
)
And the rate approximations are computed as:
```python
r = pynet.get_rate("mg24_he4__si28__approx")
print(r.function_string_py())
```
@numba.njit()
def Mg24_He4__Si28__approx(rate_eval, tf):
r_ag = rate_eval.He4_Mg24__Si28__removed
r_ap = rate_eval.He4_Mg24__p_Al27__removed
r_pg = rate_eval.p_Al27__Si28__removed
r_pa = rate_eval.p_Al27__He4_Mg24__removed
rate = r_ag + r_ap * r_pg / (r_pg + r_pa)
rate_eval.Mg24_He4__Si28__approx = rate
where the 4 lines before the rate approximation is made are evaluating the original, unapproximated rates.
## Integrating the approximate network
Let's integrate this approximate net and compare to above
```python
rho = 1.e7
T = 3.e9
X0 = np.zeros(approx_net.nnuc)
X0[approx_net.jhe4] = 0.5
X0[approx_net.jmg24] = 0.5
Y0 = X0 / approx_net.A
```
```python
tmax = 1.e-3
approx_sol = solve_ivp(approx_net.rhs, [0, tmax], Y0, method="BDF",
dense_output=True, args=(rho, T), rtol=1.e-6, atol=1.e-10)
```
```python
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(approx_net.nnuc):
ax.loglog(approx_sol.t, approx_sol.y[i,:] * approx_net.A[i], label=f"X({approx_net.names[i].capitalize()})")
ax.legend()
ax.set_xlim(1.e-10, 1.e-3)
ax.set_ylim(1.e-12, 1)
fig.set_size_inches((10, 8))
```

## Comparison
Let's plot both on the same axes to see the comparison.
```python
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(approx_net.nnuc):
ax.loglog(approx_sol.t, approx_sol.y[i,:] * approx_net.A[i],
linestyle=":", color=f"C{i}")
idx = full_net.names.index(approx_net.names[i])
ax.loglog(sol.t, sol.y[idx,:] * full_net.A[idx],
label=f"X({full_net.names[idx].capitalize()})",
linestyle="-", color=f"C{i}")
ax.legend()
ax.set_xlim(1.e-10, 1.e-3)
ax.set_ylim(1.e-12, 1)
fig.set_size_inches((10, 8))
```

Here the dotted line is the approximate network. We see that the results agree well.
## No approximation
What if we just create a 4 nuclei network without the $(\alpha,p)(p,\gamma)$ links? How does this compare?
```python
newlib = reaclib_library.linking_nuclei(["he4", "mg24", "si28", "s32"])
newpynet = pyna.PythonNetwork(libraries=[newlib])
fig = newpynet.plot(rotated=True, curved_edges=True)
```

```python
newpynet.write_network("simple_net.py")
import simple_net
```
```python
rho = 1.e7
T = 3e9
X0 = np.zeros(simple_net.nnuc)
X0[simple_net.jhe4] = 0.5
X0[simple_net.jmg24] = 0.5
Y0 = X0 / simple_net.A
```
```python
simple_net.names == approx_net.names
```
True
```python
tmax = 1.e-3
simple_sol = solve_ivp(simple_net.rhs, [0, tmax], Y0, method="BDF",
dense_output=True, args=(rho, T), rtol=1.e-6, atol=1.e-10)
```
```python
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(approx_net.nnuc):
ax.loglog(approx_sol.t, approx_sol.y[i,:] * approx_net.A[i],
linestyle=":", color=f"C{i}")
idx = full_net.names.index(approx_net.names[i])
ax.loglog(sol.t, sol.y[idx,:] * full_net.A[idx],
label=f"X({full_net.names[idx].capitalize()})",
linestyle="-", color=f"C{i}")
idx = simple_net.names.index(approx_net.names[i])
ax.loglog(simple_sol.t, simple_sol.y[idx,:] * simple_net.A[idx],
linestyle="--", color=f"C{i}")
ax.legend()
ax.set_xlim(1.e-10, 1.e-3)
ax.set_ylim(1.e-12, 1)
fig.set_size_inches((10, 8))
```

Here we see all 3 networks. The full network (7 nuclei) is the solid lines. The approximate version of that is the dotted line. We see that they track reasonably well, especially when the abundance is high. The dashed line is the version of the network that has the same 4 nuclei as the approximate network, but with out approximating the $(\alpha, p)(p,\gamma)$ links, so we see that the ${}^{24}\mathrm{Mg}$ takes longer to burn.
|
pynucastroREPO_NAMEpynucastroPATH_START.@pynucastro_extracted@pynucastro-main@docs@source@alpha-gamma-approx.ipynb@.PATH_END.py
|
{
"filename": "point_source_cached.py",
"repo_name": "sibirrer/lenstronomy",
"repo_path": "lenstronomy_extracted/lenstronomy-main/lenstronomy/PointSource/point_source_cached.py",
"type": "Python"
}
|
__all__ = ["PointSourceCached"]
class PointSourceCached(object):
"""This class is the same as PointSource() except that it saves image and source
positions in cache.
This speeds-up repeated calls for the same source and lens model and avoids duplicating the lens equation solving.
Attention: cache needs to be deleted before calling functions with different lens and point source parameters.
"""
def __init__(self, point_source_model, save_cache=False):
self._model = point_source_model
self._save_cache = save_cache
def delete_lens_model_cache(self):
if hasattr(self, "_x_image"):
del self._x_image
if hasattr(self, "_y_image"):
del self._y_image
if hasattr(self, "_x_image_add"):
del self._x_image_add
if hasattr(self, "_y_image_add"):
del self._y_image_add
if hasattr(self, "_x_source"):
del self._x_source
if hasattr(self, "_y_source"):
del self._y_source
def set_save_cache(self, save_bool):
self._save_cache = save_bool
def update_lens_model(self, lens_model_class):
self._model.update_lens_model(lens_model_class)
def image_position(
self,
kwargs_ps,
kwargs_lens=None,
magnification_limit=None,
kwargs_lens_eqn_solver=None,
additional_images=False,
):
"""On-sky image positions.
:param kwargs_ps: keyword arguments of the point source model
:param kwargs_lens: keyword argument list of the lens model(s), only used when
requiring the lens equation solver
:param magnification_limit: float >0 or None, if float is set and additional
images are computed, only those images will be computed that exceed the
lensing magnification (absolute value) limit
:param kwargs_lens_eqn_solver: keyword arguments specifying the numerical
settings for the lens equation solver see LensEquationSolver() class for
details
:param additional_images: if True, solves the lens equation for additional
images
:type additional_images: bool
:return: image positions in x, y as arrays
"""
if additional_images and not self._model.additional_images:
# ignore cached parts if additional images
if (
not self._save_cache
or not hasattr(self, "_x_image_add")
or not hasattr(self, "_y_image_add")
):
self._x_image_add, self._y_image_add = self._model.image_position(
kwargs_ps,
kwargs_lens=kwargs_lens,
magnification_limit=magnification_limit,
kwargs_lens_eqn_solver=kwargs_lens_eqn_solver,
additional_images=additional_images,
)
return self._x_image_add, self._y_image_add
if (
not self._save_cache
or not hasattr(self, "_x_image")
or not hasattr(self, "_y_image")
):
self._x_image, self._y_image = self._model.image_position(
kwargs_ps,
kwargs_lens=kwargs_lens,
magnification_limit=magnification_limit,
kwargs_lens_eqn_solver=kwargs_lens_eqn_solver,
additional_images=additional_images,
)
return self._x_image, self._y_image
def source_position(self, kwargs_ps, kwargs_lens=None):
"""Original source position (prior to lensing)
:param kwargs_ps: point source keyword arguments
:param kwargs_lens: lens model keyword argument list (only used when required)
:return: x, y position
"""
if (
not self._save_cache
or not hasattr(self, "_x_source")
or not hasattr(self, "_y_source")
):
self._x_source, self._y_source = self._model.source_position(
kwargs_ps, kwargs_lens=kwargs_lens
)
return self._x_source, self._y_source
def image_amplitude(
self,
kwargs_ps,
kwargs_lens=None,
magnification_limit=None,
kwargs_lens_eqn_solver=None,
):
"""Image brightness amplitudes.
:param kwargs_ps: keyword arguments of the point source model
:param kwargs_lens: keyword argument list of the lens model(s), only used when
requiring the lens equation solver
:param magnification_limit: float >0 or None, if float is set and additional
images are computed, only those images will be computed that exceed the
lensing magnification (absolute value) limit
:param kwargs_lens_eqn_solver: keyword arguments specifying the numerical
settings for the lens equation solver see LensEquationSolver() class for
details
:return: array of image amplitudes
"""
x_pos, y_pos = self.image_position(
kwargs_ps,
kwargs_lens,
magnification_limit=magnification_limit,
kwargs_lens_eqn_solver=kwargs_lens_eqn_solver,
)
return self._model.image_amplitude(
kwargs_ps, kwargs_lens=kwargs_lens, x_pos=x_pos, y_pos=y_pos
)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
"""Intrinsic brightness amplitude of point source.
:param kwargs_ps: keyword arguments of the point source model
:param kwargs_lens: keyword argument list of the lens model(s), only used when
positions are defined in image plane and have to be ray-traced back
:return: brightness amplitude (as numpy array)
"""
return self._model.source_amplitude(kwargs_ps, kwargs_lens=kwargs_lens)
|
sibirrerREPO_NAMElenstronomyPATH_START.@lenstronomy_extracted@lenstronomy-main@lenstronomy@PointSource@point_source_cached.py@.PATH_END.py
|
{
"filename": "Long2pos_K_driver.py",
"repo_name": "Keck-DataReductionPipelines/MosfireDRP",
"repo_path": "MosfireDRP_extracted/MosfireDRP-master/drivers/Long2pos_K_driver.py",
"type": "Python"
}
|
# Help, bugs to: http://mosfire.googlecode.com
#
# Instructions
# 1. edit band = '' to band = 'Y' or 'J' or 'H' or 'K'
# e.g. band = 'J'
# 2. edit [709, 1350] to be the pixel values at the beginning and end
# of the long slit. Look at the raw data.
# 3. edit row_position to be a location where the standard star is not.
# 4. Decide if you want to use sky lines or Neon lamps for lambda calibration
# 5. Uncomment one line at a time and run mospy on the driver file
#
import os, time
import MOSFIRE
from MOSFIRE import Background, Combine, Detector, Flats, IO, Options, Rectify
from MOSFIRE import Wavelength, Longslit
import numpy as np
from matplotlib import pyplot as pl
try:
from astropy.io import fits as pf
except:
import pyfits as pf
np.seterr(all="ignore")
maskname = 'long2pos'
band = 'K'
flatops = Options.flat
waveops = Options.wavelength
# Note: for long2pos, the row position is ignored, and the middle point of the slit is used
longslit = {'yrange': [[1062,1188],[887,1010]], 'row_position': 0, 'mode':'long2pos'}
# SETUP FILES FOR DATES before June 10, 2015
#obsfiles_posC_narrow = ['Offset_-21_HIP85871_7.25.txt', 'Offset_-7_HIP85871_7.25.txt']
#targetCnarrow = "HIP85871_posC_narrow"
#obsfiles_posA_narrow = ['Offset_7_HIP85871_7.25.txt', 'Offset_21_HIP85871_7.25.txt']
#targetAnarrow = "HIP85871_posA_narrow"
#obsfiles_posC_wide = ['Offset_-14_HIP85871_7.25.txt','Offset_-7_HIP85871_7.25.txt']
#targetCwide = "HIP85871_posC_wide"
#obsfiles_posA_wide = ['Offset_14_HIP85871_7.25.txt','Offset_21_HIP85871_7.25.txt']
#targetAwide = "HIP85871_posA_wide"
# SETUP FILES for DATES after June 10,2015
obsfiles_posC_narrow = ['Offset_7_FS134_posC.txt','Offset_-7_FS134_PosC.txt']
targetCnarrow = "FS134_posC_narrow"
obsfiles_posA_narrow = ['Offset_7_FS134_posA.txt','Offset_-7_FS134_PosA.txt']
targetAnarrow = "FS134_posA_narrow"
# Argon files
argon = ['Ar.txt']
#Flats.handle_flats('Flat.txt', maskname, band, flatops, longslit = longslit)
#Flats.handle_flats('Flat.txt', maskname, band, flatops,lampOffList='FlatThermal.txt', longslit=longslit)
# Uses the argon calibration taken in the afternoon with long2pos for the wavelength calibration
#Wavelength.imcombine(argon, maskname, band, waveops)
#Wavelength.fit_lambda_interactively(maskname, band, argon, waveops, longslit=longslit, argon=True)
#Wavelength.fit_lambda(maskname, band, argon, argon, waveops, longslit=longslit)
#Wavelength.apply_lambda_simple(maskname, band, argon, waveops, longslit=longslit, smooth=True)
########### NARROW SLITS ############
# Long2POS: NARROW SLITS: use the -7 and -21 for posC and 7 and 21 for posA
obsfiles = obsfiles_posC_narrow
target = targetCnarrow
#IO.fix_long2pos_headers(obsfiles)
#Background.handle_background(obsfiles,
# 'lambda_solution_wave_stack_K_m150610_0168-0170.fits',
# maskname, band, waveops, plan=[["A","B"]], target=target)
redfiles = ["eps_" + file + ".fits" for file in obsfiles]
#update the "lambda_solution_wave_stack_K*.fits" file name
# to the output file name from the apply_lambda process above.
# Update the name of the first file in the offset file (use the full path name.
# e.g. "/Users/user1/MOSFIRE/DRP_CODE/DATA/2014may08/m130114_0451.fits",
#Rectify.handle_rectification(maskname, redfiles,
# "lambda_solution_wave_stack_K_m150610_0168-0170.fits",
# band,
# obsfiles,
# waveops, target=target)
obsfiles = obsfiles_posA_narrow
target = targetAnarrow
#IO.fix_long2pos_headers(obsfiles)
#Background.handle_background(obsfiles,
# 'lambda_solution_wave_stack_K_m150610_0168-0170.fits',
# maskname, band, waveops, plan=[["A","B"]], target=target)
redfiles = ["eps_" + file + ".fits" for file in obsfiles]
#update the "lambda_solution_wave_stack_K*.fits" file name
# to the output file name from the apply_lambda process above.
# Update the name of the first file in the offset file (use the full path name.
# e.g. "/Users/user1/MOSFIRE/DRP_CODE/DATA/2014may08/m130114_0451.fits",
Rectify.handle_rectification(maskname, redfiles,
"lambda_solution_wave_stack_K_m150610_0168-0170.fits",
band,
obsfiles,
waveops, target=target)
########### WIDE SLITS ############
# SPECTROPHOTOMETRIC Long2POS: THIS SECTION IS FOR THE REDUCTION OF THE WIDE SLITS.
#obsfiles = obsfiles_posC_wide
#target = targetCwide
#IO.fix_long2pos_headers(obsfiles)
#Background.handle_background(obsfiles,
# 'lambda_solution_wave_stack_H_m150428_0091-0091.fits',
# maskname, band, waveops, plan=[["A","B"]], target=target)
#obsfiles = obsfiles_posA_wide
#target = targetAwide
#IO.fix_long2pos_headers(obsfiles)
#Background.handle_background(obsfiles,
# 'lambda_solution_wave_stack_H_m150428_0091-0091.fits',
# maskname, band, waveops, plan=[["A","B"]], target=target)
# NEON
# Use neon for wavelength calibrations
#Wavelength.imcombine('Ne.txt', maskname, band, waveops)
#Wavelength.fit_lambda_interactively(maskname, band, 'Ne.txt', waveops, longslit=longslit, neon=True)
#Wavelength.fit_lambda(maskname, band, 'Ne.txt', 'Ne.txt', waveops, longslit=longslit)
#Wavelength.apply_lambda_simple(maskname, band, 'Ne.txt', waveops, longslit=longslit, smooth=True)
#print redfiles
#obsfiles = ['eps_off_-10.txt', 'eps_off_10.txt']
# Update the following line after the apply_lambda_simple step
#Longslit.go(maskname, band, obsfiles,
# 'lambda_solution_wave_stack_H_m150112_0199-0201.fits',
# waveops, longslit, extension='/Volumes/PromiseRAID/MOSFIRE/DRP_CODE/DATA/2015jan12/m150112_0199.fits')
|
Keck-DataReductionPipelinesREPO_NAMEMosfireDRPPATH_START.@MosfireDRP_extracted@MosfireDRP-master@drivers@Long2pos_K_driver.py@.PATH_END.py
|
{
"filename": "read_filter.py",
"repo_name": "tomasstolker/species",
"repo_path": "species_extracted/species-main/species/read/read_filter.py",
"type": "Python"
}
|
"""
Module with reading functionalities for filter profiles.
"""
import os
import warnings
from configparser import ConfigParser
from typing import Union, Tuple
import h5py
import numpy as np
from typeguard import typechecked
from scipy.interpolate import interp1d, InterpolatedUnivariateSpline
from species.data.filter_data.filter_data import add_filter_profile
from species.data.spec_data.spec_vega import add_vega
class ReadFilter:
"""
Class for reading a filter profile from the database.
"""
@typechecked
def __init__(self, filter_name: str) -> None:
"""
Parameters
----------
filter_name : str
Filter name as stored in the database. Filter names from
the SVO Filter Profile Service will be automatically
downloaded, stored in the database, and read from the
database.
Returns
-------
NoneType
None
"""
self.filter_name = filter_name
config_file = os.path.join(os.getcwd(), "species_config.ini")
config = ConfigParser()
config.read(config_file)
self.database = config["species"]["database"]
self.data_folder = config["species"]["data_folder"]
with h5py.File(self.database, "r") as hdf5_file:
# Check if the filter is found in 'r' mode
# because the 'a' mode is not possible when
# using multiprocessing
if f"filters/{self.filter_name}" in hdf5_file:
filter_found = True
else:
filter_found = False
if not filter_found:
with h5py.File(self.database, "a") as hdf5_file:
add_filter_profile(self.data_folder, hdf5_file, self.filter_name)
@typechecked
def get_filter(self) -> np.ndarray:
"""
Select a filter profile from the database.
Returns
-------
np.ndarray
Array with the wavelengths and filter transmission. The
array has 2 dimensions with the shape (n_wavelengths, 2).
"""
with h5py.File(self.database, "r") as hdf5_file:
data = np.asarray(hdf5_file[f"filters/{self.filter_name}"])
if data.shape[0] == 2 and data.shape[1] > data.shape[0]:
# Required for backward compatibility
data = np.transpose(data)
return data
@typechecked
def interpolate_filter(self) -> interp1d:
"""
Interpolate a filter profile with the `interp1d <https://
docs.scipy.org/doc/scipy/reference/generated/
scipy.interpolate.interp1d.html>`_ function from
``scipy.interpolate`` and linear kind of interpolation.
Returns
-------
scipy.interpolate.interp1d
Linearly interpolated filter profile.
"""
data = self.get_filter()
return interp1d(
data[:, 0],
data[:, 1],
kind="linear",
bounds_error=False,
fill_value=float("nan"),
)
@typechecked
def wavelength_range(
self,
) -> Tuple[Union[np.float32, np.float64], Union[np.float32, np.float64]]:
"""
Extract the wavelength range of the filter profile.
Returns
-------
float
Minimum wavelength (:math:`\\mu\\mathrm{m}`).
float
Maximum wavelength (:math:`\\mu\\mathrm{m}`).
"""
data = self.get_filter()
return data[0, 0], data[-1, 0]
@typechecked
def mean_wavelength(self) -> Union[np.float32, np.float64]:
"""
Calculate the weighted mean wavelength of the filter profile.
Returns
-------
float
Mean wavelength (:math:`\\mu\\mathrm{m}`).
"""
data = self.get_filter()
return np.trapz(data[:, 0] * data[:, 1], x=data[:, 0]) / np.trapz(
data[:, 1], x=data[:, 0]
)
@typechecked
def effective_wavelength(self) -> Union[np.float32, np.float64]:
"""
Calculate the effective wavelength of the filter profile.
The effective wavelength is calculated as the weighted
average based on the filter profile and the spectrum of Vega.
Returns
-------
float
Effective wavelength (:math:`\\mu\\mathrm{m}`).
"""
filter_profile = self.get_filter()
with h5py.File(self.database, "a") as hdf5_file:
if "spectra/calibration/vega" not in hdf5_file:
add_vega(self.data_folder, hdf5_file)
vega_spec = np.array(hdf5_file["spectra/calibration/vega"])
flux_interp = interp1d(
vega_spec[0,],
vega_spec[1,],
bounds_error=False,
fill_value="extrapolate",
)
flux_filter = flux_interp(filter_profile[:, 0])
return np.trapz(
filter_profile[:, 0] * filter_profile[:, 1] * flux_filter,
x=filter_profile[:, 0],
) / np.trapz(filter_profile[:, 1] * flux_filter, x=filter_profile[:, 0])
@typechecked
def filter_fwhm(self) -> float:
"""
Calculate the full width at half maximum (FWHM) of the filter
profile.
Returns
-------
float
Full width at half maximum (:math:`\\mu\\mathrm{m}`).
"""
data = self.get_filter()
spline = InterpolatedUnivariateSpline(
data[:, 0], data[:, 1] - np.max(data[:, 1]) / 2.0
)
root = spline.roots()
diff = root - self.mean_wavelength()
root1 = np.amax(diff[diff < 0.0])
root2 = np.amin(diff[diff > 0.0])
return root2 - root1
@typechecked
def effective_width(self) -> Union[np.float32, np.float64]:
"""
Calculate the effective width of the filter profile. The
effective width is equivalent to the horizontal size of a
rectangle with height equal to the maximum transmission and
with the same area as the one covered by the filter profile.
Returns
-------
float
Effective width (:math:`\\mu\\mathrm{m}`).
"""
data = self.get_filter()
return np.trapz(data[:, 1], x=data[:, 0]) / np.amax(data[:, 1])
@typechecked
def detector_type(self) -> str:
"""
Return the detector type.
Returns
-------
str
Detector type ('energy' or 'photon').
"""
with h5py.File(self.database, "r") as hdf5_file:
dset = hdf5_file[f"filters/{self.filter_name}"]
if "det_type" in dset.attrs:
det_type = dset.attrs["det_type"]
else:
warnings.warn(
f"Detector type not found for {self.filter_name}. "
"The database was probably created before the "
"detector type was introduced in species v0.3.1. "
"Assuming a photon-counting detector."
)
det_type = "photon"
return det_type
|
tomasstolkerREPO_NAMEspeciesPATH_START.@species_extracted@species-main@species@read@read_filter.py@.PATH_END.py
|
{
"filename": "_ticklen.py",
"repo_name": "plotly/plotly.py",
"repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/histogram2dcontour/colorbar/_ticklen.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class TicklenValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="ticklen", parent_name="histogram2dcontour.colorbar", **kwargs
):
super(TicklenValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
min=kwargs.pop("min", 0),
**kwargs,
)
|
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@histogram2dcontour@colorbar@_ticklen.py@.PATH_END.py
|
{
"filename": "mkran_forffa.py",
"repo_name": "desihub/LSS",
"repo_path": "LSS_extracted/LSS-main/scripts/mock_tools/mkran_forffa.py",
"type": "Python"
}
|
#standard python
import sys
import os
import shutil
import unittest
from datetime import datetime
import json
import numpy as np
import fitsio
import glob
import argparse
from astropy.table import Table,join,unique,vstack
from matplotlib import pyplot as plt
from desitarget.io import read_targets_in_tiles
from desitarget.mtl import inflate_ledger
from desitarget import targetmask
from desitarget.internal import sharedmem
from desimodel.footprint import is_point_in_desi
from desitarget import targetmask
import LSS.main.cattools as ct
import LSS.common_tools as common
import LSS.mocktools as mocktools
from LSS.globals import main
#import LSS.mkCat_singletile.fa4lsscat as fa
#from LSS.globals import main
if os.environ['NERSC_HOST'] == 'perlmutter':
scratch = 'PSCRATCH'
else:
print('NERSC_HOST is not cori or permutter but is '+os.environ['NERSC_HOST'])
sys.exit('NERSC_HOST not known (code only works on NERSC), not proceeding')
parser = argparse.ArgumentParser()
#parser.add_argument("--tracer", help="tracer type to be selected")
parser.add_argument("--veto",default='_imaging')
#parser.add_argument("--mockdir", help="directory when pota mock data is",default='/global/cfs/cdirs/desi/users/acarnero/y1mock/SecondGen/clustering/')
parser.add_argument("--base_dir", help="base directory for input/output",default='/global/cfs/cdirs/desi/survey/catalogs/Y1/mocks/SecondGenMocks/')
parser.add_argument("--random_dir",help="where to find the data randoms",default='/global/cfs/cdirs/desi/survey/catalogs/Y1/LSS/iron/LSScats/v0.6/')
parser.add_argument("--specdata_dir",help="where to find the spec data ",default='/global/cfs/cdirs/desi/survey/catalogs/Y1/LSS/iron/')
parser.add_argument("--minr", help="minimum number for random files",default=0,type=int)
parser.add_argument("--maxr", help="maximum for random files, default is all 18)",default=18,type=int)
parser.add_argument("--tracer", default = 'LRG')
parser.add_argument("--par", default = 'n',help='whether to run random steps in parallel or not')
parser.add_argument("--apply_HPmapcut", default = 'y')
#parser.add_argument("--remove_unassigned", default = 'y', help = 'set to n if dont want to include unassigned targets in catalog')
args = parser.parse_args()
print(args)
rm = int(args.minr)
rx = int(args.maxr)
notqso = ''
if args.tracer == 'all':
tracers = ['LRG','QSO','ELG_LOP']
else:
tracers = [args.tracer]
#if args.mockver == 'abacus2ffa':
# tracers = [args.tracer]
#ndattot = len(mock_data)
def splitGC(flroot,datran='.dat',rann=0):
import LSS.common_tools as common
from astropy.coordinates import SkyCoord
import astropy.units as u
app = 'clustering'+datran+'.fits'
if datran == '.ran':
app = str(rann)+'_clustering'+datran+'.fits'
fn = Table(fitsio.read(flroot+app))
c = SkyCoord(fn['RA']* u.deg,fn['DEC']* u.deg,frame='icrs')
gc = c.transform_to('galactic')
sel_ngc = gc.b > 0
outf_ngc = flroot+'NGC_'+app
common.write_LSS(fn[sel_ngc],outf_ngc)
outf_sgc = flroot+'SGC_'+app
common.write_LSS(fn[~sel_ngc],outf_sgc)
def apply_imaging_veto(ff,reccircmasks,ebits):
if reccircmasks is not None:
for maskfn in reccircmasks:
mask = common.maskcircandrec(ff,maskfn)
ff = ff[~mask]
if ebits is not None:
print('number before imaging mask '+str(len(ff)))
if ebits == 'lrg_mask':
sel = ff['lrg_mask'] == 0
ff = ff[sel]
else:
ff = common.cutphotmask(ff,ebits)
print('number after imaging mask '+str(len(ff)))
return ff
nproc = 9
for tracer in tracers:
out_data_froot = args.base_dir+tracer+'_ffa'+args.veto+'_'
if args.apply_HPmapcut == 'y':
out_data_froot += 'HPmapcut'
mainp = main(tracer,'iron','Y1')
nran = rx-rm
#if args.mkran == 'y':
def _mkran(rann):
tracerr = tracer
if tracer == 'ELG_LOP':
tracerr += 'notqso'
if tracer == 'ELG':
tracerr = 'ELG_LOPnotqso'
in_ran_fn = args.random_dir+tracerr+'_'+str(rann)+'_full_noveto.ran.fits' #all noveto have same ra,dec, tracer becomes important for LRG imaging veto
out_ran_fn = out_data_froot+str(rann)+'_full.ran.fits'
rcols = ['RA','DEC','TILELOCID','NOBS_G','NOBS_R','NOBS_Z','MASKBITS','TARGETID','NTILE','GOODHARDLOC','PHOTSYS']
if tracerr == 'LRG':
rcols.append('lrg_mask')
ran = Table(fitsio.read(in_ran_fn,columns=rcols))
ran['FRAC_TLOBS_TILES'] = 1.
print(len(ran),' random length before good loc cut')
goodtl = ran['GOODHARDLOC']#np.isin(ran['TILELOCID'],gtl)
ran = ran[goodtl]
print(len(ran),' random length after good loc cut')
if 'imaging' in args.veto:
ebits = mainp.ebits
reccircmasks = mainp.reccircmasks
ran = apply_imaging_veto(ran,reccircmasks,ebits)
if args.apply_HPmapcut == 'y':
nside = 256
lssmapdirout = args.random_dir+'/hpmaps/'
if tracer[:3] == 'BGS':
mapn = fitsio.read(lssmapdirout+'BGS_BRIGHT_mapprops_healpix_nested_nside'+str(nside)+'_N.fits')
maps = fitsio.read(lssmapdirout+'BGS_BRIGHT_mapprops_healpix_nested_nside'+str(nside)+'_S.fits')
else:
mapn = fitsio.read(lssmapdirout+'QSO_mapprops_healpix_nested_nside'+str(nside)+'_N.fits')
maps = fitsio.read(lssmapdirout+'QSO_mapprops_healpix_nested_nside'+str(nside)+'_S.fits')
mapcuts = mainp.mapcuts
ran = common.apply_map_veto_arrays(ran,mapn,maps,mapcuts,nside)
print('random veto '+str(rann)+' done')
common.write_LSS(ran,out_ran_fn)
inds = np.arange(rm,rx)
if args.par == 'y':
from multiprocessing import Pool
with Pool(processes=nproc) as pool:
res = pool.map(_mkran, inds)
else:
for rn in inds:#range(rm,rx):
_mkran(rn)
|
desihubREPO_NAMELSSPATH_START.@LSS_extracted@LSS-main@scripts@mock_tools@mkran_forffa.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "astropy/halotools",
"repo_path": "halotools_extracted/halotools-master/halotools/empirical_models/smhm_models/__init__.py",
"type": "Python"
}
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
from .behroozi10 import *
from .moster13 import *
from .zu_mandelbaum15 import *
|
astropyREPO_NAMEhalotoolsPATH_START.@halotools_extracted@halotools-master@halotools@empirical_models@smhm_models@__init__.py@.PATH_END.py
|
{
"filename": "beautiful_soup_transformer.py",
"repo_name": "langchain-ai/langchain",
"repo_path": "langchain_extracted/langchain-master/libs/community/langchain_community/document_transformers/beautiful_soup_transformer.py",
"type": "Python"
}
|
from typing import Any, Iterator, List, Sequence, Tuple, Union, cast
from langchain_core.documents import BaseDocumentTransformer, Document
class BeautifulSoupTransformer(BaseDocumentTransformer):
"""Transform HTML content by extracting specific tags and removing unwanted ones.
Example:
.. code-block:: python
from langchain_community.document_transformers import BeautifulSoupTransformer
bs4_transformer = BeautifulSoupTransformer()
docs_transformed = bs4_transformer.transform_documents(docs)
""" # noqa: E501
def __init__(self) -> None:
"""
Initialize the transformer.
This checks if the BeautifulSoup4 package is installed.
If not, it raises an ImportError.
"""
try:
import bs4 # noqa:F401
except ImportError:
raise ImportError(
"BeautifulSoup4 is required for BeautifulSoupTransformer. "
"Please install it with `pip install beautifulsoup4`."
)
def transform_documents(
self,
documents: Sequence[Document],
unwanted_tags: Union[List[str], Tuple[str, ...]] = ("script", "style"),
tags_to_extract: Union[List[str], Tuple[str, ...]] = ("p", "li", "div", "a"),
remove_lines: bool = True,
*,
unwanted_classnames: Union[Tuple[str, ...], List[str]] = (),
remove_comments: bool = False,
**kwargs: Any,
) -> Sequence[Document]:
"""
Transform a list of Document objects by cleaning their HTML content.
Args:
documents: A sequence of Document objects containing HTML content.
unwanted_tags: A list of tags to be removed from the HTML.
tags_to_extract: A list of tags whose content will be extracted.
remove_lines: If set to True, unnecessary lines will be removed.
unwanted_classnames: A list of class names to be removed from the HTML
remove_comments: If set to True, comments will be removed.
Returns:
A sequence of Document objects with transformed content.
"""
for doc in documents:
cleaned_content = doc.page_content
cleaned_content = self.remove_unwanted_classnames(
cleaned_content, unwanted_classnames
)
cleaned_content = self.remove_unwanted_tags(cleaned_content, unwanted_tags)
cleaned_content = self.extract_tags(
cleaned_content, tags_to_extract, remove_comments=remove_comments
)
if remove_lines:
cleaned_content = self.remove_unnecessary_lines(cleaned_content)
doc.page_content = cleaned_content
return documents
@staticmethod
def remove_unwanted_classnames(
html_content: str, unwanted_classnames: Union[List[str], Tuple[str, ...]]
) -> str:
"""
Remove unwanted classname from a given HTML content.
Args:
html_content: The original HTML content string.
unwanted_classnames: A list of classnames to be removed from the HTML.
Returns:
A cleaned HTML string with unwanted classnames removed.
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, "html.parser")
for classname in unwanted_classnames:
for element in soup.find_all(class_=classname):
element.decompose()
return str(soup)
@staticmethod
def remove_unwanted_tags(
html_content: str, unwanted_tags: Union[List[str], Tuple[str, ...]]
) -> str:
"""
Remove unwanted tags from a given HTML content.
Args:
html_content: The original HTML content string.
unwanted_tags: A list of tags to be removed from the HTML.
Returns:
A cleaned HTML string with unwanted tags removed.
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, "html.parser")
for tag in unwanted_tags:
for element in soup.find_all(tag):
element.decompose()
return str(soup)
@staticmethod
def extract_tags(
html_content: str,
tags: Union[List[str], Tuple[str, ...]],
*,
remove_comments: bool = False,
) -> str:
"""
Extract specific tags from a given HTML content.
Args:
html_content: The original HTML content string.
tags: A list of tags to be extracted from the HTML.
remove_comments: If set to True, the comments will be removed.
Returns:
A string combining the content of the extracted tags.
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, "html.parser")
text_parts: List[str] = []
for element in soup.find_all():
if element.name in tags:
# Extract all navigable strings recursively from this element.
text_parts += get_navigable_strings(
element, remove_comments=remove_comments
)
# To avoid duplicate text, remove all descendants from the soup.
element.decompose()
return " ".join(text_parts)
@staticmethod
def remove_unnecessary_lines(content: str) -> str:
"""
Clean up the content by removing unnecessary lines.
Args:
content: A string, which may contain unnecessary lines or spaces.
Returns:
A cleaned string with unnecessary lines removed.
"""
lines = content.split("\n")
stripped_lines = [line.strip() for line in lines]
non_empty_lines = [line for line in stripped_lines if line]
cleaned_content = " ".join(non_empty_lines)
return cleaned_content
async def atransform_documents(
self,
documents: Sequence[Document],
**kwargs: Any,
) -> Sequence[Document]:
raise NotImplementedError
def get_navigable_strings(
element: Any, *, remove_comments: bool = False
) -> Iterator[str]:
"""Get all navigable strings from a BeautifulSoup element.
Args:
element: A BeautifulSoup element.
remove_comments: If set to True, the comments will be removed.
Returns:
A generator of strings.
"""
from bs4 import Comment, NavigableString, Tag
for child in cast(Tag, element).children:
if isinstance(child, Comment) and remove_comments:
continue
if isinstance(child, Tag):
yield from get_navigable_strings(child, remove_comments=remove_comments)
elif isinstance(child, NavigableString):
if (element.name == "a") and (href := element.get("href")):
yield f"{child.strip()} ({href})"
else:
yield child.strip()
|
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@langchain_community@document_transformers@beautiful_soup_transformer.py@.PATH_END.py
|
{
"filename": "problem.py",
"repo_name": "hannorein/REBOUND",
"repo_path": "REBOUND_extracted/REBOUND-main/python_examples/dragforce/problem.py",
"type": "Python"
}
|
# Import the rebound module
import rebound
# Add particles
# We work in units where G=1.
sim = rebound.Simulation()
sim.add(m=1. ) # Test particle
sim.add(m=1e-3,x=1.,vy=1. ) # Planet
# Move particles so that the center of mass is (and stays) at the origin
sim.move_to_com()
# You can provide a function, written in python to REBOUND.
# This function gets called every time the forces are evaluated.
# Simple add any any additional (non-gravitational) forces to the
# particle accelerations. Here, we add a simple drag force. This
# will make the planet spiral into the star.
ps = sim.particles
def dragforce(reb_sim):
dragcoefficient = 1e-2
for p in ps:
p.ax += -dragcoefficient * p.vx
p.ay += -dragcoefficient * p.vy
p.az += -dragcoefficient * p.vz
# Tell rebound which function to call
sim.additional_forces = dragforce
# Integrate until t=100 (roughly 16 orbits at 1 AU)
sim.integrate(100.)
# Output something at the end (the planet will be at ~0.1 AU)
for p in ps:
print(p.x, p.y, p.z)
|
hannoreinREPO_NAMEREBOUNDPATH_START.@REBOUND_extracted@REBOUND-main@python_examples@dragforce@problem.py@.PATH_END.py
|
{
"filename": "_unselected.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/graph_objs/violin/_unselected.py",
"type": "Python"
}
|
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Unselected(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "violin"
_path_str = "violin.unselected"
_valid_props = {"marker"}
# marker
# ------
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.violin.unselected.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
color
Sets the marker color of unselected points,
applied only when a selection exists.
opacity
Sets the marker opacity of unselected points,
applied only when a selection exists.
size
Sets the marker size of unselected points,
applied only when a selection exists.
Returns
-------
plotly.graph_objs.violin.unselected.Marker
"""
return self["marker"]
@marker.setter
def marker(self, val):
self["marker"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
marker
:class:`plotly.graph_objects.violin.unselected.Marker`
instance or dict with compatible properties
"""
def __init__(self, arg=None, marker=None, **kwargs):
"""
Construct a new Unselected object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.violin.Unselected`
marker
:class:`plotly.graph_objects.violin.unselected.Marker`
instance or dict with compatible properties
Returns
-------
Unselected
"""
super(Unselected, self).__init__("unselected")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.violin.Unselected
constructor must be a dict or
an instance of :class:`plotly.graph_objs.violin.Unselected`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("marker", None)
_v = marker if marker is not None else _v
if _v is not None:
self["marker"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@graph_objs@violin@_unselected.py@.PATH_END.py
|
{
"filename": "test_tkmatrix.py",
"repo_name": "PlanetHunters/tkmatrix",
"repo_path": "tkmatrix_extracted/tkmatrix-master/tkmatrix/tests/test_tkmatrix.py",
"type": "Python"
}
|
import os
import shutil
import unittest
import lcbuilder.constants
import pytest
from lcbuilder.star.starinfo import StarInfo
from tkmatrix.tkmatrix_class import MATRIX
class TestsMatrix(unittest.TestCase):
def test_inject_one(self):
target = "TIC 220513363"
matrix = MATRIX(target, [1], lcbuilder.constants.SPOC_AUTHOR, ".", exposure_time=120)
inject_dir = None
try:
inject_dir, period_grid, radius_grid = matrix.inject(1, 5, 5, 1, 3, 3, 1)
self.assertEqual(10, len(os.listdir(inject_dir)))
self.assertEqual([1], matrix.search_input.sectors)
self.assertAlmostEqual(0.47, matrix.search_input.star_info.mass, 2)
self.assertAlmostEqual(0.44, matrix.search_input.star_info.mass_min, 2)
self.assertAlmostEqual(0.5, matrix.search_input.star_info.mass_max, 2)
self.assertAlmostEqual(0.18, matrix.search_input.star_info.radius, 2)
self.assertAlmostEqual(0.076, matrix.search_input.star_info.radius_min, 3)
self.assertAlmostEqual(0.284, matrix.search_input.star_info.radius_max, 3)
self.assertEqual("TIC 220513363", matrix.object_info.mission_id())
self.assertEqual("TIC 220513363", matrix.search_input.target)
self.assertAlmostEqual(0.47, matrix.search_input.mstar.value, 2)
self.assertAlmostEqual(0.44, matrix.search_input.mstar_min.value, 2)
self.assertAlmostEqual(0.5, matrix.search_input.mstar_max.value, 2)
self.assertAlmostEqual(0.18, matrix.search_input.rstar.value, 2)
self.assertAlmostEqual(0.076, matrix.search_input.rstar_min.value, 3)
self.assertAlmostEqual(0.284, matrix.search_input.rstar_max.value, 3)
self.assertEqual(".", matrix.search_input.dir)
matrix.recovery(inject_dir, 5, detrend_ws=0, oversampling=0.1)
matrix.plot_results(target, inject_dir)
self.assertEqual(9, len(os.listdir(inject_dir)))
finally:
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
def test_inject_one_preserve(self):
target = "TIC 220513363"
matrix = MATRIX(target, [1], lcbuilder.constants.SPOC_AUTHOR, ".", True, exposure_time=120)
inject_dir = None
try:
inject_dir, period_grid, radius_grid = matrix.inject(1, 5, 5, 1, 3, 3, 1)
matrix.recovery(inject_dir, 5, detrend_ws=0, oversampling=0.1)
matrix.plot_results(target, inject_dir)
self.assertEqual(10, len(os.listdir(inject_dir)))
finally:
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
def test_inject_four(self):
target = "TIC 220513363"
matrix = MATRIX(target, [1], lcbuilder.constants.SPOC_AUTHOR, ".", exposure_time=120)
inject_dir = None
try:
inject_dir, period_grid, radius_grid = matrix.inject(1, 5, 5.1, 2, 3, 3.1, 2)
self.assertEqual(13, len(os.listdir(inject_dir)))
finally:
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
def test_inject_multiphase(self):
target = "TIC 220513363"
matrix = MATRIX(target, [1], lcbuilder.constants.SPOC_AUTHOR, ".", exposure_time=120)
inject_dir = None
try:
inject_dir, period_grid, radius_grid = matrix.inject(2, 5, 5, 1, 3, 3, 1)
self.assertEqual(11, len(os.listdir(inject_dir)))
finally:
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
def test_inject_inputs(self):
target = "TIC 305048087"
matrix = MATRIX(target, [2], lcbuilder.constants.SPOC_AUTHOR, ".", exposure_time=120)
inject_dir = None
with(pytest.raises(AssertionError)):
inject_dir, period_grid, radius_grid = matrix.inject(2, 5, 5.1, 2, 3, 3.1, "ho")
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
with(pytest.raises(AssertionError)):
inject_dir, period_grid, radius_grid = matrix.inject(2, 5, 5.1, 2, 3, 3.1, -0.1)
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
with(pytest.raises(AssertionError)):
inject_dir, period_grid, radius_grid = matrix.inject(2, 5, 5.1, 2, 3, -3.1, 2)
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
with(pytest.raises(AssertionError)):
inject_dir, period_grid, radius_grid = matrix.inject(2, 5, 5.1, 2, -3, 3.1, 2)
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
with(pytest.raises(AssertionError)):
inject_dir, period_grid, radius_grid = matrix.inject(2, 5, 5.1, -2, 3, 3.1, 2)
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
with(pytest.raises(AssertionError)):
inject_dir, period_grid, radius_grid = matrix.inject(2, 5, -5.1, 2, 3, 3.1, 2)
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
with(pytest.raises(AssertionError)):
inject_dir, period_grid, radius_grid = matrix.inject(2, -5, 5.1, 2, 3, 3.1, 2)
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
with(pytest.raises(AssertionError)):
inject_dir, period_grid, radius_grid = matrix.inject(-2, 5, 5.1, 2, 3, 3.1, 2)
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
def test_inject_dir(self):
inject_dir1 = None
inject_dir2 = None
target = "TIC 305048087"
matrix = MATRIX(target, [2], lcbuilder.constants.SPOC_AUTHOR, ".", exposure_time=120)
try:
inject_dir1, period_grid, radius_grid = matrix.inject(2, 5, 5, 1, 3, 3, 1)
self.assertTrue(os.path.isdir(inject_dir1))
inject_dir2, period_grid, radius_grid = matrix.inject(2, 5, 5, 1, 3, 3, 1)
self.assertTrue(os.path.isdir(inject_dir2))
finally:
if inject_dir1 is not None:
shutil.rmtree(inject_dir1, ignore_errors=True)
if inject_dir2 is not None:
shutil.rmtree(inject_dir2, ignore_errors=True)
def test_star_info(self):
target = "TIC 220513363"
star_info = StarInfo(target, (0.2, 0.5), 2000, 1.2, None, None, 0.5, 0.1, 0.2, 0.7, 0.15, 0.05, None, None)
matrix = MATRIX(target, [1], lcbuilder.constants.SPOC_AUTHOR, ".", False, star_info, exposure_time=120)
inject_dir = None
try:
inject_dir, period_grid, radius_grid = matrix.inject(1, 5, 5, 1, 3, 3, 1)
self.assertEqual(10, len(os.listdir(inject_dir)))
self.assertEqual((0.2, 0.5), matrix.search_input.star_info.ld_coefficients)
self.assertEqual(2000, matrix.search_input.star_info.teff)
self.assertAlmostEqual(0.7, matrix.search_input.star_info.mass)
self.assertAlmostEqual(0.55, matrix.search_input.star_info.mass_min)
self.assertAlmostEqual(0.75, matrix.search_input.star_info.mass_max)
self.assertAlmostEqual(0.5, matrix.search_input.star_info.radius)
self.assertAlmostEqual(0.4, matrix.search_input.star_info.radius_min)
self.assertAlmostEqual(0.7, matrix.search_input.star_info.radius_max)
finally:
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
matrix = MATRIX(target, [1], lcbuilder.constants.SPOC_AUTHOR, ".", exposure_time=120)
inject_dir = None
try:
inject_dir, period_grid, radius_grid = matrix.inject(1, 5, 5, 1, 3, 3, 1)
self.assertEqual(10, len(os.listdir(inject_dir)))
self.assertEqual((0.1258, 0.235), matrix.search_input.star_info.ld_coefficients)
self.assertEqual(31000.0, matrix.search_input.star_info.teff)
self.assertAlmostEqual(0.47, matrix.search_input.star_info.mass)
self.assertAlmostEqual(0.44, matrix.search_input.star_info.mass_min)
self.assertAlmostEqual(0.5, matrix.search_input.star_info.mass_max)
self.assertAlmostEqual(0.18, matrix.search_input.star_info.radius)
self.assertAlmostEqual(0.076, matrix.search_input.star_info.radius_min)
self.assertAlmostEqual(0.284, matrix.search_input.star_info.radius_max)
finally:
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
def test_inject_grids(self):
target = "TIC 220513363"
matrix = MATRIX(target, [1], lcbuilder.constants.SPOC_AUTHOR, ".", exposure_time=120)
inject_dir = None
period_grid_expected = [1, 2, 3, 8, 20]
radius_grid_expected = [1.1, 1.4, 2, 2.5]
try:
inject_dir, period_grid, radius_grid = matrix.inject(1, 5, 5.1, 2, 3, 3.1, 2, period_grid=period_grid_expected,
radius_grid=radius_grid_expected)
self.assertEqual(29, len(os.listdir(inject_dir)))
self.assertEqual(period_grid_expected, period_grid)
self.assertEqual(radius_grid_expected, radius_grid)
finally:
if inject_dir is not None:
shutil.rmtree(inject_dir, ignore_errors=True)
if __name__ == '__main__':
unittest.main()
|
PlanetHuntersREPO_NAMEtkmatrixPATH_START.@tkmatrix_extracted@tkmatrix-master@tkmatrix@tests@test_tkmatrix.py@.PATH_END.py
|
{
"filename": "rayleigh_spectral_input.py",
"repo_name": "geodynamics/Rayleigh",
"repo_path": "Rayleigh_extracted/Rayleigh-main/pre_processing/rayleigh_spectral_input.py",
"type": "Python"
}
|
#!/usr/bin/env python3
#
# Copyright (C) 2018 by the authors of the RAYLEIGH code.
#
# This file is part of RAYLEIGH.
#
# RAYLEIGH is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# RAYLEIGH is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with RAYLEIGH; see the file LICENSE. If not see
# <http://www.gnu.org/licenses/>.
#
import numpy as np
import scipy.special as scisp
import funcsigs
import math
def compute_plms(lm_max, costheta):
"""
Compute the normalized spherical harmonics up to degree and order `lm_max` and colocation points `costheta`.
"""
# FIXME: this will blow up rapidly because of its naive use of math.factorial
plms = np.zeros((lm_max+1, lm_max+1, len(costheta)))
for l in range(lm_max+1):
for m in range(l+1):
norm = np.sqrt(((2.*l+1.)/(4.*np.pi))*(float(math.factorial(l-m))/float(math.factorial(l+m))))
plms[m,l,:] = norm*scisp.lpmv(m,l,costheta)
return plms
def compute_gamma(n_r):
"""
Compute the Chebyshev colocation points (zero-crossing of degree n_r).
"""
return np.asarray([np.pi*(2*k + 1)/2./n_r for k in range(n_r)])
def compute_tns(n_max, gamma):
"""
Compute Chebyshev polynomials up to degree `n_max` at colocation points `gamma`.
"""
return np.asarray([np.cos(j*gamma) for j in range(n_max+1)])
def dealias_m2g(m_max):
"""
Return the dealiased number of grid points.
"""
g = int(3*(m_max + 1)/2)
return g
def dealias_g2m(g):
"""
Return the dealiased maximum order/degree.
"""
m_max = int((2*g - 1)/3)
if m_max < 0: m_max = 0
return m_max
def radial_extents(rmin=None, rmax=None, aspect_ratio=None, shell_depth=None):
"""
Return rmin and rmax if they aren't set using aspect_ratio and shell_depth.
"""
if rmax is None:
if shell_depth is None or aspect_ratio is None:
raise Exception("Must supply shell_depth and aspect_ratio if rmax is not set.")
rmax = shell_depth/(1.-aspect_ratio)
if rmin is None:
if aspect_ratio is None:
raise Exception("Must supply aspect_ratio if rmin is not set.")
rmin = rmax*aspect_ratio
return rmin, rmax
def swapwrite(vals,fd,byteswap=False):
"""
Write to file handle fd with the option of byteswapping.
"""
# this is a tidied up copy of post_processing/rayleigh_diagnostics.py
# reproduced here to avoid dependency on post_processing and to tidy it up without conflict
# FIXME: unify python routines to avoid this duplication
valsout = vals
if byteswap: valsout = vals.newbyteorder()
valsout.tofile(fd)
def swapread(fd,dtype='float64',count=1,byteswap=False):
"""
Read from file handle fd with the option of byteswapping.
"""
# this is a tidied up copy of post_processing/rayleigh_diagnostics.py
# reproduced here to avoid dependency on post_processing and to tidy it up without conflict
# FIXME: unify python routines to avoid this duplication
vals = np.fromfile(fd, dtype=dtype, count=count)
if byteswap: vals.byteswap()
return vals
def check_byteswap(fd):
"""
Check endianess of file fd by reading an integer 314 and testing it matches.
Returns True if byteswapping is necessary.
"""
# this is a tidied up copy of post_processing/rayleigh_diagnostics.py
# reproduced here to avoid dependency on post_processing and to tidy it up without conflict
# FIXME: unify python routines to avoid this duplication
chk = np.fromfile(fd, dtype='int32', count=1)
if (chk == 314): return False
return True
class SpectralInput(object):
"""
Rayleigh class describing and writing generic spectral input for boundary/initial conditions.
"""
version = 1
lm_max = None
n_max = None
indices = None
coeffs = None
def __init__(self, n_theta=None, n_r=None, \
lm_max=None, n_max=None):
"""
Optional arguments:
- `n_theta` : Number of co-latitudinal grid points.
Ignored if `lm_max` is supplied.
If this or `lm_max` is supplied a multidimensional coefficient array is allocated, otherwise a sparse list structure will be used.
- `n_r` : Number of radial grid point.
Ignored if `n_max` is supplied.
- `lm_max` : Maximum Legendre order and degree.
If this or `n_theta` is supplied a multidimensional coefficient array is allocated, otherwise a sparse list structure will be used.
- `n_max` : Maximum Chebyshev polynomial degree.
Ignored if `lm_max` is not supplied.
Assumed to be 0 if not supplied.
"""
self.lm_max = lm_max
self.n_max = n_max
if self.lm_max is None and n_theta is None:
# no dimensions provided so just set up a 1-D sparse storage to add modes to
self.indices = []
self.coeffs = np.zeros((0,), dtype='complex')
else:
# dimensions provided, set up a (n,l,m) array of coefficients
if self.lm_max is None: self.lm_max = dealias_g2m(n_theta)
if self.n_max is None:
if n_r is None:
self.n_max = 0
else:
self.n_max = dealias_g2m(n_r)
self.coeffs = np.zeros((self.n_max+1, self.lm_max+1, self.lm_max+1), dtype='complex')
def add_mode(self, coeff, n=None, l=None, m=None, mode='add'):
"""
Add a mode coefficient to the class.
The coefficient (`coeff`) may be scalar, a list or 1-D array, or a multi-dimensional array (indexed by [l, m] in 2-D or [n, l,
m] in 3-D).
If `coeff` is scalar or a list/1-D array, corresponding lists of indices for `l` and `m` must be provided. If `n` is not provided it is
assumed to be 0.
If `coeff` is a multi-dimensional array, `l`, `m` and `n` are ignored and the entries are assumed to be indexed by [l, m]
(assiuming n=0) or [n, l, m] in increasing order from 0.
Optional arguments:
- `n` : A list of Chebyshev n modes corresponding to the values in `coeff`.
Assumed to be 0 if not supplied. Ignored if `coeff` is 2- or 3-D.
- `l` : A list of Legendre function degrees corresponding to the values in `coeff`.
Ignored if `coeff` is 2- or 3-D.
- `m` : A list of Legendre function orders corresponding to the values in `coeff`.
Ignored if `coeff` is 2- or 3-D.
- `mode` : How coefficients are added, either "replace", which overwrites, or "add", which adds, to existing entries.
"""
if np.ndim(coeff) > 3:
raise Exception("Don't know how to deal with coefficients of specified dimensions (({})).".format(",".join(map(str,coeff.shape))))
def check_args(coeff, l, m, n):
"""Check arguments are consistent with scalar or list addition."""
# Check the necessary arguments have been supplied
if l is None or m is None: raise Exception("Specify l and m (n will be assumed to be 0 if not supplied).")
# Elevate scalars to lists/arrays
if np.isscalar(l): l = [l]
if np.isscalar(m): m = [m]
if n is None:
n = [0]*len(l)
else:
if np.isscalar(n): n = [n]
if np.isscalar(coeff): coeff = [coeff]
coeff = np.asarray(coeff, dtype='complex')
# Check lengths and indices
if not len(l) == len(m) == len(n) == len(coeff): raise Exception("Length of l, m, n (if supplied) and coeff lists must match.")
for i in range(len(l)):
if n[i] < 0 or l[i] < 0 or m[i] < 0: raise Exception("All indicies must be non-negative.")
if m[i] > l[i]: raise Exception("At i = {0}, m[i] ({1}) > l[i] ({2}), which is not allowed".format(i, m[i], l[i]))
return coeff, l, m, n
def check_dims(coeff):
"""Check dimensions are consistent with multi-dimensional addition."""
# we assume we've been given a full array of coefficients
# and that if ndim is 2, n dependence has been dropped
# i.e. l, m and n are ignored
if not (l is None and m is None and n is None):
raise Warning("l, m and n arguments will be ignored for rank > 1 arrays (assumed to be ordered).")
coeff = np.asarray(coeff, dtype='complex')
# Get dimensions of coeff
l_maxp1, m_maxp1 = coeff.shape[-2:]
# Fix 2-D arrays to be 3-D
n_maxp1 = 1
if np.ndim(coeff) == 3:
n_maxp1 = coeff.shape[0]
else:
coeff = coeff.reshape((1,)+coeff.shape)
return coeff, l_maxp1, m_maxp1, n_maxp1
# first, the case where lm_max hasn't been supplied to the class so arrays are 1-D
if np.ndim(self.coeffs) == 1:
# lists to store new entries
newi = []
newc = []
# multi-dimensional coeffs
if np.ndim(coeff) > 1:
# we assume we've been given a full array of coefficients
# and that if ndim is 2, n dependence has been dropped
# i.e. l, m and n are ignored
coeff, l_maxp1, m_maxp1, n_maxp1 = check_dims(coeff)
for mj in range(m_maxp1):
for lj in range(mj, l_maxp1):
for nj in range(n_maxp1):
nlm = (nj, lj, mj)
i = None
try:
i = self.indices.index(nlm)
except ValueError:
pass
if i is None:
newi.append(nlm)
newc.append(coeff[nlm])
else:
if mode == 'replace':
self.coeffs[i] = coeff[nlm]
elif mode == 'add':
self.coeffs[i] += coeff[nlm]
else:
raise Exception("Unknown addition mode ({}).".format(mode,))
# scalar and 1-D lists/arrays
else:
# use l, m and n to locate coeffs in array
coeff, l, m, n = check_args(coeff, l, m, n)
for j in range(len(l)):
nlm = (n[j], l[j], m[j])
i = None
try:
i = self.indices.index(nlm)
except ValueError:
pass
if i is None:
newi.append(nlm)
newc.append(coeff[j])
else:
if mode == 'replace':
self.coeffs[i] = coeff[j]
elif mode == 'add':
self.coeffs[i] += coeff[j]
else:
raise Exception("Unknown addition mode ({}).".format(mode,))
# if there are new entries to add, add them now (doesn't matter what the mode is)
if len(newc) > 0:
self.indices += newi
self.coeffs = np.append(self.coeffs, np.asarray(newc, dtype='complex'))
else:
# multi-dimensional coeffs
if np.ndim(coeff) > 1:
coeff, l_maxp1, m_maxp1, n_maxp1 = check_dims(coeff)
if n_maxp1 > self.coeffs.shape[0] \
or l_maxp1 > self.coeffs.shape[1] \
or m_maxp1 > self.coeffs.shape[2]:
raise Exception("Number of coefficients exceed dimensions set by lm_max and n_max.")
if mode == 'replace':
self.coeffs[:n_maxp1, :l_maxp1, :m_maxp1] = coeff
elif mode == 'add':
self.coeffs[:n_maxp1, :l_maxp1, :m_maxp1] += coeff
# scalar and 1-D lists/arrays
else:
# use l, m and n to locate coeffs in array
coeff, l, m, n = check_args(coeff, l, m, n)
for j in range(len(l)):
if l[j] > self.lm_max or m[j] > self.lm_max or n[j] > self.n_max:
raise Exception("Specified index exceeds lm_max or n_max, (n,l,m)=({},{},{})".format(str(n[j]), str(l[j]), str(m[j])))
if mode == 'replace':
self.coeffs[n[j], l[j], m[j]] = coeff[j]
elif mode == 'add':
self.coeffs[n[j], l[j], m[j]] += coeff[j]
else:
raise Exception("Unknown addition mode ({}).".format(mode,))
def transform_from_rtp_function(self, func, func_kwargs={}, \
n_theta=None, n_phi=None, n_r=None, \
rmin=None, rmax=None, shell_depth=None, aspect_ratio=None, \
mode='replace'):
"""
Transform the provided function of spherical coordinates (radius, theta, phi) into Chebyshev/spherical harmonics (n, l, m).
The provided function (`func(theta, phi, radius, ...)`) should accept any combination (including none) of the input parameters:
- `theta` : co-latitude
- `phi` : longitude
- `radius` : radius
These arguments must be named following this scheme.
Optional arguments:
- `func_kwargs` : Supply a dictionary of additional keyword arguments to `func`.
Cannot contain keys for `theta`, `phi`, or `radius`.
- `n_theta` : Specify the number of co-latitudinal grid points.
Set based on `lm_max` if not provided and `func` is a function of `theta`.
Ignored if `func` is not a function of `theta`.
- `n_phi` : Specify the number of longitudinal grid points.
Set based on `n_theta` if not provided and `func` is a function of `phi`.
Ignored if `func` is not a function of `phi`.
- `n_r` : Specify the number of radial grid points.
Set based on `n_max` if not provided and `func` is a function of `radius`.
Ignored if `func` is not a function of `radius`.
- `rmin` : Specify the minimum radius.
Ignored if `func` is not a function of `radius`.
- `rmax` : Specify the maximum radius.
Ignored if `func` is not a function of `radius`.
- `shell_depth` : Specify the shell depth.
Ignored if `rmax` and either `rmin` or `aspect_ratio` are supplied.
- `aspect_ratio` : Specify the aspect ratio.
Ignored if `rmax` and `rmin` are supplied.
- `mode` : How coefficients are added, either "replace", which overwrites,
or "add", which adds, to existing entries
of the same order and degree.
"""
func_param = funcsigs.signature(func).parameters
# check what our function is a function of
func_theta = False
if 'theta' in func_param: func_theta = True
func_phi = False
if 'phi' in func_param: func_phi = True
func_radius = False
if 'radius' in func_param: func_radius = True
# sanity check that nothing we want to set has been set by the user
for k in ('theta', 'phi', 'radius'):
if k in func_kwargs:
raise Exception("'{}' supplied in func_kwargs. You probably didn't mean to do this.".format((k,)))
# some sanity checks that we have enough info for the radial domain
if func_radius:
rmin, rmax = radial_extents(rmin, rmax, aspect_ratio, shell_depth)
else:
rmin = None
rmax = None
# work out the number of points...
if func_theta or func_phi:
# theta (co-latitude)
if n_theta is None:
if self.lm_max is None:
raise Exception("Cannot evaluate n_theta (or n_phi) unless lm_max is set. Supply n_theta or set lm_max.")
n_theta = dealias_m2g(self.lm_max)
# phi (longitude)
if n_phi is None:
if func_phi:
n_phi = n_theta*2
else:
n_phi = 1
if not func_theta: n_theta = 1
else:
n_theta = 1
n_phi = 1
if func_radius:
# radius (if we care about it)
if n_r is None:
if self.n_max is None:
raise Exception("Cannot evaluate n_r unless n_max is set. Supply n_r or set n_max.")
n_r = dealias_m2g(self.n_max)
else:
n_r = 1
# get Legendre Gauss integration points and weights
# (we do this regardless of whether func_theta is true)
costheta, legweights = np.polynomial.legendre.leggauss(n_theta)
# set up Chebyshev integration points
# (we do this regardless of whether func_radius is true)
gamma = compute_gamma(n_r)
theta, phi, rx, radius = [None]*4
if func_theta:
# set up co-latitudinal colocation points
theta = np.arccos(costheta)
if func_phi:
# set up longitudinal colocation points
phi = np.linspace(0, 2*np.pi, n_phi+1)[:-1]
if func_radius:
# set up radial colocation points
rx = np.cos(gamma)
# rescale to physical space
radius = (rx-rx[-1])*(rmax-rmin)/(rx[0]-rx[-1]) + rmin
# evaluate the function
try:
# set up a (2/3D) grid of points to evaluate the function at
# hopefully most efficient if function is vectorized
coord = [None]*3
if func_theta: coord[0] = theta
if func_phi: coord[1] = phi
if func_radius: coord[2] = radius
thetag, phig, radiusg = np.meshgrid(*coord)
coordg = {}
coordg.update(func_kwargs)
if func_theta: coordg['theta'] = thetag
if func_phi: coordg['phi'] = phig
if func_radius: coordg['radius'] = radiusg
data_rtp = func(**coordg).transpose()
except:
# more annoying but maybe more forgiving...
data_rtp = np.zeros((n_r, n_theta, n_phi))
coordg = {}
coordg.update(func_kwargs)
for t in range(n_theta):
if func_theta: coordg['theta'] = theta[t]
for p in range(n_phi):
if func_phi: coordg['phi'] = phi[p]
for r in range(n_r):
if func_radius: coordg['radius'] = radius[r]
data_rtp[r,t,p] = func(**coordg)
self.transform_from_rtp_data(data_rtp, \
gamma=gamma, costheta=costheta, weights=legweights, \
mode=mode)
def transform_from_rtp_data(self, data_rtp, \
gamma=None, costheta=None, weights=None, \
mode='replace'):
"""
Transform the provided array in spherical coordinates [radius, theta, phi] into Chebyshev/spherical harmonics (n, l, m).
The provided array (`data_rtp`) must be indexed in [radius, theta, phi] in that order (radius, co-latitude, longitude).
It is assumed that the data is
distributed in a structured grid in a spherical shell following an appropriate distribution of points: Chebyshev zero points in
radius, Legendre-Gauss quadrature points in theta, and evenly spaced in phi. Optional arguments may be supplied to describe the
grid and integration weights.
Optional arguments:
- `gamma` : Chebyshev colocation points in [-1,1]. Dimension must match data_rtp.shape[0].
- `costheta` : Colocation points in [-1,1] (cosine of co-latitude). Dimension must match data_rtp.shape[1].
- `weights` : Integration weights. Dimension must match data_rtp.shape[1].
- `mode` : How coefficients are added, either "replace", which overwrites, or "add", which adds, to existing entries.
"""
n_r = data_rtp.shape[0]
n_theta = data_rtp.shape[1]
n_phi = data_rtp.shape[2]
# work out lm_max, l_max, m_max & n_max
lm_max = self.lm_max
if lm_max is None: lm_max = dealias_g2m(n_theta)
l_max = min(lm_max, dealias_g2m(n_theta))
m_max = min(lm_max, dealias_g2m(n_phi))
n_max = self.n_max
if n_max is None: n_max = dealias_g2m(n_r)
n_max = min(n_max, dealias_g2m(n_r))
# get Legendre Gauss integration points and weights
if costheta is None or weights is None:
if costheta is not None:
raise Exception("Supplied weights but not costheta.")
if weights is not None:
raise Exception("Supplied costheta but not weights.")
costheta, weights = np.polynomial.legendre.leggauss(n_theta)
else:
if len(costheta) != n_theta or len(weights) != n_theta:
raise Exception("If supplied, length of costheta and weights must match input n_theta (data_rtp.shape[1]).")
# set up Chebyshev integration points
if gamma is None:
gamma = compute_gamma(n_r)
else:
if len(gamma) != n_r:
raise Exception("If supplied, length of gamma must match input n_r (data_rtp.shape[0]).")
# Fourier transform: phi -> m
data_rtm = np.fft.rfft(data_rtp)/n_phi
data_rtm[:,:,1:] = 2.*data_rtm[:,:,1:]
# compute the spherical harmonics
plms = compute_plms(lm_max, costheta)
data_rlm = np.zeros((n_r, l_max+1, m_max+1), dtype='complex')
# Legendre transform: theta -> l
for l in range(l_max+1):
for m in range(min(l+1, m_max+1)):
for r in range(n_r):
data_rlm[r, l, m] = sum(2.*np.pi*data_rtm[r, :, m]*plms[m, l, :]*weights)
# compute the Chebyshev polynomials
tns = compute_tns(n_max, gamma)
data_nlm = np.zeros((n_max+1, l_max+1, m_max+1), dtype='complex')
# Chebyshev transform: radius -> n
for l in range(l_max+1):
for m in range(min(l+1, m_max+1)):
for n in range(n_max+1):
data_nlm[n, l, m] = (2./n_r)*sum(data_rlm[:, l, m]*tns[n, :])
self.add_mode(data_nlm, mode=mode)
def inverse_transform(self, n_theta=None, n_phi=None, n_r=None):
"""
Inverse transform back to (r, theta, phi) space from the stored [n, l, m] coefficients.
"""
if np.ndim(self.coeffs)==3:
n_max = self.n_max
lm_max = self.lm_max
data_nlm = self.coeffs
else:
n,l,m = zip(*self.indices)
n_max = max(n)
lm_max = max(l)
m_max = max(m)
if m_max > lm_max: raise Exception("Found m_max > lm_max. This should not happen.")
data_nlm = np.zeros((n_max+1, lm_max+1, lm_max+1), dtype='complex')
# FIXME: not the most efficient way of handling this but makes code below easier
# (with lots of potential multiplying by zeros below)
for i, nlm in enumerate(self.indices):
data_nlm[nlm] = self.coeffs[i]
# work out the number of points...
# theta (co-latitude)
if n_theta is None: n_theta = dealias_m2g(lm_max)
# phi (longitude)
if n_phi is None: n_phi = n_theta*2
# radius
if n_r is None: n_r = dealias_m2g(n_max)
# get Legendre Gauss integration points and weights and compute the harmonics
costheta, legweights = np.polynomial.legendre.leggauss(n_theta)
plms = compute_plms(lm_max, costheta)
phis = np.linspace(0, 2*np.pi, n_phi+1)[:-1]
# set up Chebyshev integration points and compute the polynomials
gamma = compute_gamma(n_r)
tns = compute_tns(n_max, gamma)
# Perform the inverse transform
data_rtp = np.zeros((n_r, n_theta, n_phi))
for r in range(n_r):
for l in range(lm_max+1):
for m in range(l+1):
data_rlm = sum(tns[:,r]*data_nlm[:,l,m]) - 0.5*data_nlm[0,l,m]
for p, phi in enumerate(phis):
data_rtp[r,:,p] += (data_rlm.real*np.cos(m*phi) - data_rlm.imag*np.sin(m*phi))*plms[m,l,:]
return data_rtp
def sort(self):
"""
Order the coefficients in column-major ordering, i.e. given indices (n,l,m), n varies fastest then l then m.
Only affects sparsely stored coefficients as densely stored values are automatically ordered.
"""
if np.ndim(self.coeffs)==1:
order = [j[0] for j in sorted(enumerate(self.indices), key=lambda x: x[1][::-1])]
self.coeffs = self.coeffs[order]
self.indices = [self.indices[i] for i in order]
def write(self, filename, byteswap=False):
"""
Write spectral coefficients to file `filename`.
Optional arguments:
- byteswap: byte swap the data being written to switch endianness (default: False)
"""
# FIXME: byteswap currently does nothing
fd = open(filename, 'wb')
if np.ndim(self.coeffs)==1:
# sparsely stored coefficients (requires larger header)
self.sort()
header = np.ndarray((4+3*len(self.indices)),dtype='int32')
header[0] = 314 # endian tag
header[1] = self.version # file version (hard-coded above)
header[2] = 0 # mode
header[3] = len(self.indices)
header[4:] = [i for nlm in zip(*self.indices) for i in nlm]
swapwrite(header, fd, byteswap)
swapwrite(self.coeffs.real, fd, byteswap)
swapwrite(self.coeffs.imag, fd, byteswap)
else:
flatcoeffs = np.asarray([self.coeffs[n,l,m] for m in range(self.lm_max+1) \
for l in range(m,self.lm_max+1) \
for n in range(self.n_max+1)])
header = np.ndarray((5), dtype='int32')
header[0] = 314 # endian tag
header[1] = self.version # file version (hard-coded above)
header[2] = 1 # mode
header[3] = self.n_max
header[4] = self.lm_max
swapwrite(header, fd, byteswap)
swapwrite(flatcoeffs.real, fd, byteswap)
swapwrite(flatcoeffs.imag, fd, byteswap)
fd.close()
def read(self, filename, mode='add'):
"""
Read spectral coefficients from file `filename`. Assumed to be in spectral input format.
Optional arguments:
- mode: either 'add' to or 'replace' existing coefficients (default: 'add')
"""
fd = open(filename, 'rb')
bs = check_byteswap(fd)
version = swapread(fd,dtype='int32',count=1,byteswap=bs)[0]
fmode = swapread(fd,dtype='int32',count=1,byteswap=bs)[0]
if fmode == 0:
f_n_lmn = swapread(fd,dtype='int32',count=1,byteswap=bs)[0]
f_ns = swapread(fd,dtype='int32',count=f_n_lmn,byteswap=bs)
f_ls = swapread(fd,dtype='int32',count=f_n_lmn,byteswap=bs)
f_ms = swapread(fd,dtype='int32',count=f_n_lmn,byteswap=bs)
elif fmode == 1:
f_n_max = swapread(fd,dtype='int32',count=1,byteswap=bs)[0]
f_lm_max = swapread(fd,dtype='int32',count=1,byteswap=bs)[0]
f_n_lmn = int((f_n_max+1)*(f_lm_max+1)*(f_lm_max+2)/2)
f_flatindices = [(n,l,m) for m in range(f_lm_max+1) \
for l in range(m,f_lm_max+1) \
for n in range(f_n_max+1)]
f_ns, f_ls, f_ms = [i for i in zip(*f_flatindices)]
else:
raise Exception("Unknown file mode in read: {:d}".format(fmode,))
f_flatcoeffs = swapread(fd,dtype='float64',count=f_n_lmn,byteswap=bs).astype('complex')
f_flatcoeffs.imag = swapread(fd,dtype='float64',count=f_n_lmn,byteswap=bs)
self.add_mode(f_flatcoeffs, n=f_ns, l=f_ls, m=f_ms, mode=mode)
def main(fformat=None, n_theta=None, lm_max=None, n_r=None, n_max=None, n_phi=None, \
rmin=None, rmax=None, aspect_ratio=None, shell_depth=None, \
modes=None, expressions=None, filename=None):
"""
Main function to process and write spectral input to file.
"""
if fformat == "dense":
l_lm_max = lm_max
if lm_max is None and n_theta is None: l_lm_max = 0
si = SpectralInput(n_theta=n_theta, lm_max=l_lm_max, n_r=n_r, n_max=n_max)
elif fformat == "sparse":
si = SpectralInput()
else:
raise Exception("Unknown file format: {:s}".format(fformat,))
# deal with individual modes
if modes is not None:
for index, coeff in modes:
si.add_mode(coeff, n=index[0], l=index[1], m=index[2])
# deal with any expressions provided
if expressions is not None:
import ast, os
# from https://stackoverflow.com/questions/39379331/python-exec-a-code-block-and-eval-the-last-line
def exec_then_eval(theta=None, phi=None, radius=None, \
rmin=None, rmax=None, aspect_ratio=None, shell_depth=None, \
code=None):
block = ast.parse(code, mode='exec')
# assumes last node is an expression
last = ast.Expression(block.body.pop().value)
_globals = {'theta':theta, 'phi':phi, 'radius':radius,\
'rmin':rmin, 'rmax':rmax, \
'aspect_ratio':aspect_ratio, 'shell_depth':shell_depth}
_locals = {}
exec(compile(block, '<string>', mode='exec'), _globals, _locals)
return eval(compile(last, '<string>', mode='eval'), _globals, _locals)
func_kwargs = {'rmin':rmin, 'rmax':rmax, 'aspect_ratio':aspect_ratio, 'shell_depth':shell_depth}
for expr in expressions:
func_kwargs['code'] = expr
func_args = []
if expr.find('theta') >= 0: func_args.append("theta")
if expr.find('phi') >= 0: func_args.append("phi")
if expr.find('radius') >= 0:
func_args.append("radius")
if func_kwargs['rmin'] is None or func_kwargs['rmax'] is None:
func_kwargs['rmin'], func_kwargs['rmax'] = radial_extents(rmin, rmax, aspect_ratio, shell_depth)
func_argstr, exec_argstr = "", ""
if len(func_args) > 0:
func_argstr = ", ".join([fa+"=None" for fa in func_args])+", "
exec_argstr = ", ".join([fa+"="+fa for fa in func_args])+", "
# from https://stackoverflow.com/questions/1409295/set-function-signature-in-python
func_str = "def func({:s}**kwargs):".format(func_argstr)+os.linesep+\
" return exec_then_eval({:s}**kwargs)".format(exec_argstr)+os.linesep
_globals, _locals = {'exec_then_eval': exec_then_eval}, {}
exec(compile(func_str, '<string>', mode='exec'), _globals, _locals)
func = _locals["func"]
si.transform_from_rtp_function(func, n_theta=n_theta, n_r=n_r, \
rmin=rmin, rmax=rmax, aspect_ratio=aspect_ratio, shell_depth=shell_depth,
func_kwargs=func_kwargs)
si.write(filename)
###################################
# main script below #
###################################
if __name__ == "__main__":
import argparse
import re, os
def parse_mode(modein):
modestr = " ".join(modein)
# regular expression to split up values string into a list
# the list may be comma(,), semicolon(;), space ( ) or newline (\n) delimited
# if the list is of bracketed items (e.g. tuples) then any delimiters within
# the brackets are preserved
# brackets may be (), [] or {}
#NODE EXPLANATION
#--------------------------------------------------------------------------------
# (?: group, but do not capture (1 or more times
# (matching the most amount possible)):
#--------------------------------------------------------------------------------
# [^,; \n([{] any character except: ',', ';', ' ',
# '\n' (newline), '(', '[', '{'
#--------------------------------------------------------------------------------
# | OR
#--------------------------------------------------------------------------------
# \( '('
#--------------------------------------------------------------------------------
# [^)]* any character except: ')' (0 or more
# times (matching the most amount
# possible))
#--------------------------------------------------------------------------------
# \) ')'
#--------------------------------------------------------------------------------
# | OR
#--------------------------------------------------------------------------------
# \[ '['
#--------------------------------------------------------------------------------
# [^]]* any character except: ']' (0 or more
# times (matching the most amount
# possible))
#--------------------------------------------------------------------------------
# \] ']'
#--------------------------------------------------------------------------------
# | OR
#--------------------------------------------------------------------------------
# \{ '{'
#--------------------------------------------------------------------------------
# [^}]* any character except: '}' (0 or more
# times (matching the most amount
# possible))
#--------------------------------------------------------------------------------
# \} '}'
#--------------------------------------------------------------------------------
# )+ end of grouping
# - from http://rick.measham.id.au/paste/explain.pl
r = re.compile(r'(?:[^,; '+os.linesep+'([{]|\([^)]*\)|\[[^]]*\]|\{[^}]*\})+')
modelist = r.findall(modestr)
for index in modelist[:min(3,len(modelist)-1)]:
if not index.isdigit():
raise argparse.ArgumentTypeError("Expected non-negative integer as index, not {:s}.".format(index,))
modecoeff = complex(modelist[-1])
modeindex = [0]*3
if len(modelist) == 2:
# interpret this as a Chebyshev mode, with only radial dependence
# the first entry is then interpretted as a mode index (int) and the second the coefficient value (complex)
modeindex[0] = int(modelist[0])
elif len(modelist) == 3:
# interpret this as a spherical mode, with only (theta, phi) dependence
# the first two entries are l and m and the third the coefficient value (complex)
modeindex[1:] = [int(index) for index in modelist[:2]]
elif len(modelist) == 4:
# interpret this as a mode with both radial and spherical dependence
# the first three entries are n, l and m and the fourth the coefficient value (complex)
modeindex[:] = [int(index) for index in modelist[:3]]
else:
raise argparse.ArgumentTypeError("Expected 2 (radial), 3 (spherical) or 4 (radial & spherical) arguments describing a mode, "
"got {:d} ({:s}).".format(len(modelist), modestr))
return (tuple(modeindex), modecoeff)
epilog = '''
EXAMPLES
To write a single constant mode, (n,l,m)=(0,0,0), with coefficient 1.+0.j,
to the file `example` run:
> %(prog)s -m 0 0 0 1.+0.j -o example
or:
> %(prog)s -m 0 0 1.+0.j -o example
where n is assumed to be 0 when not supplied, or:
> %(prog)s -m 0 1.+0.j -o example
where (l,m) is assumed to be (0,0) when not supplied.
To write spectral input matching the Christensen et al. 2001 hydrodynamic
benchmark initial condition to the file `example`, run:
> %(prog)s -ar 0.35 -sd 1.0 -nt 96 -nr 64 -o example \\
-e 'import numpy as np; x = 2*radius - rmin - rmax;
rmax*rmin/radius - rmin + 210*0.1*(1 - 3*x*x + 3*(x**4) - x**6)*(np.sin(theta)**4)*np.cos(4*phi)/np.sqrt(17920*np.pi)'
'''
parser = argparse.ArgumentParser( \
description="""Generate generic spectral input for Rayleigh.""", epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("-m", "--mode", nargs='+', type=str, dest='modes', metavar='mode', default=[], action='append', required=False,
help='''Add a mode to the spectral input. This should be formatted as "-m index coefficient"
where index is either 1, 2 or 3 integers depending on the desired mode (see below).
The coefficient should be parseable as a complex number.
For a pure Chebyshev mode supply 1 integer as the n index followed by the coefficient value,
e.g. "-m 0 1.+1.j".
For a purely spherical harmonic mode supply 2 integers representing the l and m degree and order
respectively, followed by the coefficient value, e.g. "-m 0 0 1.+1.j".
For a mode with both radial and spherical dependence supply 3 integers representing n, l and m Chebyshev
index and spherical harmonic degree and order respectively, followed by the coefficient value,
e.g. "-m 0 0 0 1.+1.j".
All three examples here add the coefficient 1.+1.j to the mode (n,l,m) = (0,0,0). Multiple modes can
be added by using "-m index coefficient" repeatedly.''')
parser.add_argument("-e", "--expr", type=str, dest='expressions', metavar='expr', default=None, action='append', required=False,
help='''Transform the given expression into Chebyshev-spectral space. The expression can depend on any
combination (or none) of the variables `radius`, `theta` (co-latitude), `phi` (longitude).
In addition it may use `rmin`, `rmax`, `aspect_ratio` and
`shell_depth`. The expression should return the field value at the given radius, theta and phi.
It may be vectorized to process multiple radii, thetas and phis at once. If multiple expressions are
supplied their modes will be added. Similarly any modes supplied (-m) will be added.''')
parser.add_argument("-rn", "--rmin", type=float, dest='rmin', default=None, action='store', required=False,
help='''Supply the minimum radius of the domain. Required if transforming from an expression that depends on
radius and `aspect_ratio` is not supplied along with either `rmax` or `shell_depth`. Ignored if no
expression supplied (-e) or the expression does not depend on radius.''')
parser.add_argument("-rx", "--rmax", type=float, dest='rmax', default=None, action='store', required=False,
help='''Supply the maximum radius of the domain. Required if transforming from an expression that depends on
radius and `aspect_ratio` and `shell_depth` are not supplied. Ignored if no
expression supplied (-e) or the expression does not depend on radius.''')
parser.add_argument("-sd", "--shell_depth", type=float, dest='shell_depth', default=None, action='store', required=False,
help='''Supply the shell depth of the domain. Required if transforming from an expression that depends on
radius and `rmax` is not supplied. Ignored if no
expression supplied (-e) or the expression does not depend on radius.''')
parser.add_argument("-ar", "--aspect_ratio", type=float, dest='aspect_ratio', default=None, action='store', required=False,
help='''Supply the shell depth of the domain. Required if transforming from an expression that depends on
radius and `rmax` and `rmin` are not supplied. Ignored if no
expression supplied (-e) or the expression does not depend on radius.''')
parser.add_argument("-nt", "--n_theta", type=int, dest='n_theta', default=None, action='store', required=False,
help='''Specify the number of co-latitudinal grid points. Required if `lm_max` is not supplied and either
a dense format is requested or an expression that depends on theta is supplied.''')
parser.add_argument("-np", "--n_phi", type=int, dest='n_phi', default=None, action='store', required=False,
help='''Specify the number of longitudinal grid points. Not required. Set from `n_theta` if not
supplied.''')
parser.add_argument("-nr", "--n_r", type=int, dest='n_r', default=None, action='store', required=False,
help='''Specify the number of radial grid points. Required if an expression that depends on radius is
supplied and n_max is not specified.''')
parser.add_argument("-lm", "--lm_max", type=int, dest='lm_max', default=None, action='store', required=False,
help='''Specify the maximum Legendre order and degree. Required if `n_theta` is not supplied and either a
dense format is requested or an expression that depends on theta is supplied.''')
parser.add_argument("-nm", "--n_max", type=int, dest='n_r', default=None, action='store', required=False,
help='''Specify the maximum Chebyshev polynomial degree. Required if an expression that depends on radius is
supplied.''')
parser.add_argument("-f", "--format", type=str, choices=["dense", "sparse"], dest='fformat', default="sparse", action='store', required=False,
help='''Storage format, either `dense` or `sparse`. Defaults to `%(default)s`.''')
parser.add_argument("-o", "--output", type=str, dest='filename', required=True, action='store',
help='''Specify the filename of the output file.''')
args = parser.parse_args()
dargs = vars(args)
dargs['modes'] = [parse_mode(mode) for mode in args.modes]
main(**dargs)
|
geodynamicsREPO_NAMERayleighPATH_START.@Rayleigh_extracted@Rayleigh-main@pre_processing@rayleigh_spectral_input.py@.PATH_END.py
|
{
"filename": "LTE_module.py",
"repo_name": "claude-bertout/SLIM2",
"repo_path": "SLIM2_extracted/SLIM2-main/LTE_module.py",
"type": "Python"
}
|
"""
Module name : LTE_module
This module computes the LTE electron density and level populations for
known total number density and temperature distribution.
Solar composition is assumed.
Electron donor metals taken into account: C, Si, Fe, Mg, Ni, Cr, Ca, Na, K.
Caution: only one ionization level of the above elements (plus H and He)
is taken into account.
The derivation follows Gray (Stellar photospheres, p. 181 ff.)
"""
import numpy as np
# import matplotlib.pyplot as plt
import csv
from constants import k, saha_cst, tau_cst
import import_parameters as prm
import import_atomic_data as adat
# global atom, ion_level, a_weight, abund, lambda0, el_ev, eu_ev, gl, gu, flu, Aul, log_gf, ion_level_l, ion_level_u
# ----------------------------------------
def boltzmann_ratio(gb, ga, eb, ea, temp):
# ------------------------------------
"""
solves the Boltzman equation.
"""
exponent = -(eb - ea) / (k * temp)
ratio = (gb / ga) * np.exp(exponent)
# print(f"Boltzmann exponent = {exponent}, ea = {ea}, ga = {ga}, eb = {eb}, gb = {gb}, ratio = {ratio}")
return ratio
# ----------------------------
def polyn_approx(g0, a, temp):
# ------------------------
"""
polynomial approximation for the partition function of various ions.
accurate to better than 4 percent for a temperature range
from 3537° to 20160° K
See Bolton, C.T., 1970, ApJ 161, 1187-88
"""
theta = 5040 / temp
ap_sum = 0.0
for i in range(len(a)):
ap_sum += a[i] * np.log(theta) ** i
return g0 + np.exp(ap_sum)
# -------------------------------------------
def Bolton_partition_function(element, temp):
# ---------------------------------------
"""
returns the approximate partition function of ions
contained in file partition_function_data.txt
"""
f = prm.file_location + 'input_data/Bolton_partition_functions.txt'
csv_reader = csv.reader(open(f), delimiter=' ')
last_line_number = adat.row_count(f)
for line in csv_reader:
if csv_reader.line_num < last_line_number:
a = []
ion = str(line[0]).casefold()
if ion == element.casefold():
g0 = float(line[1])
a_coef_number = int(line[2])
for lx in range(a_coef_number):
a.append(float(line[3 + lx]))
if 3500 < temp < 21000:
part_fcn = polyn_approx(g0, a, temp)
else:
part_fcn = g0
return part_fcn
else:
pass
else:
print('Warning - from Bolton partition function: ion not found')
return 1.0
# -----------------------------------------
def Gray_partition_function(element, temp):
# -------------------------------------
"""
returns the approximate partition function of ions
contained in file partition_function_data.txt
Caution: temp is forced to the validity interval 2500<temp<25000.
"""
f = prm.file_location + 'input_data/Gray_partition_functions.txt'
csv_reader = csv.reader(open(f), delimiter=' ')
last_line_number = adat.row_count(f)
theta = np.linspace(0.2, 2.0, 10)
th_min = theta[0]
th_max = theta[-1]
th = np.divide(5040, temp)
th = np.where(th > th_min, th, th_min)
th = np.where(th < th_max, th, th_max)
for line in csv_reader:
if line[0] == '#':
pass
elif csv_reader.line_num < last_line_number:
pf = []
ion = str(line[0]).casefold()
# print(f"from Gray: ion = {ion}") if prm.lte_debug_mode else None
if ion == element.casefold():
atomic_number = float(line[1])
ionization_level = float(line[2])
print(f"ion = {ion}, atomic_number = {atomic_number}, ionization_level = {ionization_level}") \
if prm.lte_debug_mode else None
for lx in range(10):
pf.append(float(line[3 + lx]))
log_g0 = float(line[-1])
log_part_fcn = np.interp(th, theta, pf)
part_fcn = 10.0 ** log_part_fcn
print(f"Grey partition function = {part_fcn}, log_g0 = {log_g0}") \
if prm.lte_debug_mode else None
return part_fcn
else:
pass
else:
print(f"Warning - from Gray partition function: {element} not found")
return 1.0
# ---------------------------------
def saha_phi(atom, eii, ei, temp):
# -----------------------------
"""
solves the temperature-dependent part phi(T) of the Saha equation
N1*ne/N0 = Phi(T) for 'atom';
returns the LTE ratio of atoms N_ii in ionization state i+1
to atoms N_i in state i given the partition functions u1 = U(i),
u2 = U(i+1), the temperature temp in kelvins, the ionization energies eii
and ei in eV of the higher and lower ionization levels.
The result must be divided by the electron density ne in cm-3 to get N1/N0
Caution: valid temperature range is 2500 < temp < 25000.
Alternative form:
I = eii - ei
theta = 5040.0/temp
phi = 1.2020e9 * (u1/u2) * theta**(-2.5) * 10**(-theta * I) / (k_B * temp)
"""
print(f"entering saha_phi with atom = {atom}, eii = {eii}, ei = {ei}, temp = {temp}") \
if prm.lte_debug_mode else None
u1 = Gray_partition_function(atom + '_i', temp)
u2 = Gray_partition_function(atom + '_ii', temp)
phi = ((2.0 * u2) / u1) * (saha_cst * temp) ** 1.5 * np.exp(-(eii - ei) / (k * temp))
print(f"saha_phi - u1 = {u1}, u2 = {u2}, ei = {ei}, eii = {eii}, phi = {phi}") \
if prm.lte_debug_mode else None
return phi
# ----------------------------------------
def saha_phi_prime(atom, eiii, eii, temp):
# ------------------------------------
"""
solves the temperature-dependent part phi(T) of the Saha equation
N1*ne/N0 = Phi(T) for 'atom';
returns the LTE ratio of atoms N_iii in ionization state i+2
to atoms N_ii in state i+1 given the partition functions u2 = U(ii),
u3 = U(iii), the temperature temp in kelvins, the ionization energies eii
and ei in eV of the higher and lower ionization levels.
The result must be divided by the electron density ne in cm-3 to get N1/N0
Caution: valid temperature range is 2500 < temp < 25000.
Alternative form:
I = eiii - eii
theta = 5040.0 / temp
phi_prime = 1.2020e9 * (u2 / u3) * theta ** (-2.5) * 10 ** (-theta * I) / (k_B * temp)
"""
print(f"entering saha_phi_prime with ion = {atom}, eiii = {eiii}, eii = {eii}, temp = {temp}") \
if prm.lte_debug_mode else None
u2 = Gray_partition_function(atom + '_ii', temp)
u3 = Gray_partition_function(atom + '_iii', temp)
phi_prime = ((2.0 * u3) / u2) * (saha_cst * temp) ** 1.5 * np.exp(-(eiii - eii) / (k * temp))
print(f"saha_phi - u2 = {u2}, u3 = {u3}, eii = {eii}, eiii = {eiii}, phi_prime = {phi_prime}") \
if prm.lte_debug_mode else None
return phi_prime
# --------------------------------------------
def iter_loop(nt, el_nbr, ratio, na_over_nhs):
# ----------------------------------------
"""
iterate over the electron density ne
"""
print(f"entering iter_loop - na_over_nhs \n {na_over_nhs}") \
if prm.lte_debug_mode else None
print(f"ratio \n {ratio}") if prm.lte_debug_mode else None
ne = np.sqrt(nt)
new_ne = ne
niter = 0
niter_max = 1000
# num = np.zeros(el_nbr)
# denum = np.zeros(el_nbr)
# mu_denum = 0.0
# pr1 = np.zeros(el_nbr)
# pr2 = np.zeros(el_nbr)
corr = 1.0
while corr > prm.frac and niter < niter_max:
niter += 1
# sigma_top = 0.0
# sigma_bottom = 0.0
ne = new_ne
print(f"iteration {iter} - ne = {ne}") if prm.lte_debug_mode else None
num = [(ratio[iel] / ne) / (1.0 + (ratio[iel] / ne)) for iel in range(el_nbr)]
pr1 = np.multiply(num, na_over_nhs)
sigma_top = pr1.sum()
if prm.lte_debug_mode:
print(f"num \n {num}")
print(f"np.shape(num) = {np.shape(num)}")
print(f"na_over_nhs \n {na_over_nhs}")
print(f"np.shape(na_over_nhs) = {np.shape(na_over_nhs)}")
print(f"pr1 \n {pr1}")
print(f"np.shape(pr1) = {np.shape(pr1)}")
print(f"sigma_top = {sigma_top}")
denum = np.add(num, 1)
pr2 = np.multiply(denum, na_over_nhs)
sigma_bottom = pr2.sum()
new_ne = nt * np.divide(sigma_top, sigma_bottom)
if prm.lte_debug_mode:
print(f"pr2 \n {pr2}")
print(f"np.shape(pr2) = {np.shape(pr2)}")
print(f"sigma_bottom = {sigma_bottom}")
print(f"new_ne = {new_ne}\n")
corr = np.abs(new_ne - ne) / ne
print(f"corr = {corr}") if prm.lte_debug_mode else None
print(f"ne iteration ended after {niter} steps") if prm.lte_debug_mode else None
if niter >= niter_max:
print('no convergence in iter_loop for ne (LTE module)')
exit()
return ne
# -----------------------
def populations(nt, temp):
# -------------------
"""
returns the number ne of electrons per cm3 and the atomic abundances of the elements
under investigation for temperature vector temp, as well as the populations of the first three
ionization levels of these (except when the 3rd level partition functions are not given in Gray).
We assume for the computation of ne an atomic gas made up of the mix 'elements'
with total number density vector nt.
Solar abundances and LTE conditions are also assumed for the population computations.
The transcendental equation for ne is solved in a straightforward iterative way,
in iter_loop, starting with ne = sqrt(nt).
The mean molecular weight mu of the gas mixture considered is also returned.
NB. nt is the total number (ions + electrons) of particles per cm-3, so the gas pressure
is pg = nt * kT
Caution: only the first ionization stage is included here. Slight departures over exact
result at temp < 5000K. The code was tested against Tabelle 4.7.3, Seite 154 in
Unsöld & Baschek's Der Neue Kosmos 4. Auflage
"""
# read atomic data ordered in increasing weight
element_list = np.array(['H', 'He', 'C', 'N', 'O', 'Na', 'Mg', 'Al', 'Si', 'S', 'K', 'Ca', 'Cr', 'Fe', 'Ni'])
el_nbr = len(element_list)
atoms = np.array(range(el_nbr), dtype='str')
atomic_numbers = np.zeros(el_nbr)
weights = np.zeros(el_nbr)
g0s = np.zeros(el_nbr)
g1s = np.zeros(el_nbr)
log_a12s = np.zeros(el_nbr)
na_over_nhs = np.zeros(el_nbr)
ion_energ = np.zeros((el_nbr, 3))
ion_wavel = np.zeros((el_nbr, 3))
ratio_0 = np.zeros((el_nbr, prm.idr))
# ratio_1 = np.zeros((el_nbr, prm.idr))
# n0_over_nt = np.zeros((el_nbr, prm.idr))
# n1_over_nt = np.zeros((el_nbr, prm.idr))
# n2_over_nt = np.zeros((el_nbr, prm.idr))
iel = -1
# read all elements in element_list above to compute ne
for element in element_list:
iel += 1
atoms[iel], atomic_numbers[iel], weights[iel], g0s[iel], g1s[iel], log_a12s[iel], na_over_nhs[iel], \
ion_energ[iel, 0], ion_wavel[iel, 0], ion_energ[iel, 1], ion_wavel[iel, 1], \
ion_energ[iel, 2], ion_wavel[iel, 2] = adat.read_atomic_data(element)
if prm.lte_debug_mode:
print(f"iel = {iel}, atoms[{iel}] = {atoms[iel]}")
print(f"{element}, g0s[{iel}] = {g0s[iel]}, g1s[{iel}] = {g1s[iel]}, ion_energ = {ion_energ[iel, :]}, "
f"ion_wavel = {ion_wavel[iel, :]}")
# compute Saha ratios 1-0
for i in range(prm.idr):
ratio_0[iel, i] = saha_phi(element, ion_energ[iel, 0], 0.0, temp[i])
print(f"element = {element}, iel = {iel}, Saha ratio[{iel},:] \n{ratio_0[iel, :]}") \
if prm.lte_debug_mode else None
at_weight = weights * na_over_nhs
at_metals = np.delete(at_weight, [0, 1])
if prm.lte_debug_mode:
print(f"at_weight \n{at_weight}")
print(f"at_metals \n{at_metals}")
# mean atomic weight
wei = weights.sum()
mu_num = at_weight.sum()
mu_metals = at_metals.sum()
mu_denum = na_over_nhs.sum()
print(f"wei = {wei}, mu_num = {mu_num}, mu_metals = {mu_metals}, mu_denum = {mu_denum}") \
if prm.lte_debug_mode else None
ne = np.zeros(prm.idr)
mu = np.zeros(prm.idr)
for i in range(prm.idr):
# iterate over electron density
ne[i] = iter_loop(nt[i], el_nbr, ratio_0[:, i], na_over_nhs)
# compute mean molecular weight
mu[i] = at_weight.sum() / (na_over_nhs.sum() * (1.0 + ne[i] / nt[i]))
print(f"ne/nt[{i}] = {ne[i] / nt[i]}, mu[{i}] = {mu[i]}") if prm.lte_debug_mode else None
iel = -1
# reset the arrays to zero
atoms = np.array(range(el_nbr), dtype='str')
atomic_numbers = np.zeros(el_nbr)
weights = np.zeros(el_nbr)
g0s = np.zeros(el_nbr)
g1s = np.zeros(el_nbr)
log_a12s = np.zeros(el_nbr)
na_over_nhs = np.zeros(el_nbr)
ion_energ = np.zeros((el_nbr, 3))
ion_wavel = np.zeros((el_nbr, 3))
ratio_0 = np.zeros((el_nbr, prm.idr))
ratio_1 = np.zeros((el_nbr, prm.idr))
n0_over_nt = np.zeros((el_nbr, prm.idr))
n1_over_nt = np.zeros((el_nbr, prm.idr))
n2_over_nt = np.zeros((el_nbr, prm.idr))
# now compute the LTE level populations for the computed lines
# recall that prm.elements are tuples (element_abbreviation, number_of_computed_lines_for_that_element)
print('From populations') if prm.lte_debug_mode else None
for elem, nlines in prm.elements:
iel += 1
atoms[iel], atomic_numbers[iel], weights[iel], g0s[iel], g1s[iel], log_a12s[iel], na_over_nhs[iel], \
ion_energ[iel, 0], ion_wavel[iel, 0], ion_energ[iel, 1], ion_wavel[iel, 1], \
ion_energ[iel, 2], ion_wavel[iel, 2] = adat.read_atomic_data(elem)
print(atoms[iel], atomic_numbers[iel], weights[iel], g0s[iel], g1s[iel], log_a12s[iel], na_over_nhs[iel],
ion_energ[iel, 0], ion_wavel[iel, 0], ion_energ[iel, 1], ion_wavel[iel, 1],
ion_energ[iel, 2], ion_wavel[iel, 2]) if prm.lte_debug_mode else None
if prm.lte_debug_mode:
print(f"iel = {iel}, atoms[{iel}] = {atoms[iel]}")
print(f"{elem}, g0s[{iel}] = {g0s[iel]}, g1s[{iel}] = {g1s[iel]}, ion_energ = {ion_energ[iel, :]}"
f", ion_wavel = {ion_wavel[iel, :]}")
population_dict = {}
ielement = -1
for eleme, nlines in prm.elements:
print(f"eleme = {eleme}, nlines = {nlines}") if prm.lte_debug_mode else None
ielement += 1
# compute Saha ratios
for i in range(prm.idr):
ratio_0[ielement, i] = saha_phi(eleme, ion_energ[ielement, 0], 0.0, temp[i]) / ne[i]
n0_over_nt[ielement, i] = 1.0 / (ratio_0[ielement, i] + 1)
if ion_energ[ielement, 1] != 0.0:
ratio_1[ielement, i] = saha_phi_prime(eleme, ion_energ[ielement, 1], ion_energ[ielement, 0],
temp[i]) / ne[i]
n0_over_nt[ielement, i] = 1.0 / (1 + ratio_0[ielement, i] * (1.0 + ratio_1[ielement, i])) # OK
n1_over_nt[ielement, i] = 1.0 / (1.0 / ratio_0[ielement, i] + ratio_1[ielement, i] + 1) # OK
else:
n1_over_nt[ielement, i] = 1.0 - n0_over_nt[ielement, i]
# the population dictionary contains the populations in the neutral ground state and first ionization level
# ground state for each element. Provision is made for the population in the second ionization level
# but is not used here.
population_dict.update({eleme: [n0_over_nt[ielement, :], n1_over_nt[ielement, :],
n2_over_nt[ielement, :]]})
print(population_dict) if prm.lte_debug_mode else None
return ne / nt, mu, g0s, g1s, population_dict
# -------------------------------------
def lte_tau(atom, ion_level, abund, lambda0, gl, gu, el_ev, eu_ev, flu, nt, temp):
# ---------------------------------
"""
returns the radial optical depths of the computed lines based on LTE level populations
"""
# global atom, ion_level, a_weight, abund, lambda0, el_ev, eu_ev, gl, gu, flu, Aul, log_gf, ion_level_l, ion_level_u
# use the Saha equation to compute equilibrium electron density and level population ratios
ne, mu, g0s, g1s, population_dict = populations(nt, temp)
print(f"Entering lte.tau for atom {atom} -- g0s = {g0s}, g1s = {g1s}") if prm.lte_debug_mode else None
tau = np.zeros((prm.nline, prm.idr))
nl = np.zeros((prm.nline, prm.idr))
nu = np.zeros((prm.nline, prm.idr))
nx_over_nt = np.zeros((prm.nline, 3), object) # holds population dictionary above
nl_over_nt = np.zeros(prm.nline, object)
nu_over_nt = np.zeros(prm.nline, object)
# use populations returned from abundances to compute the radial part taur of optical depth
index = -1
for element in population_dict.keys():
# print(element)
index += 1
nx_over_nt[index, :] = population_dict.get(element)
if prm.lte_debug_mode:
print(f"el = {element}, lambda = {lambda0[index]}, prm.line_range[{index}] = {prm.line_range[index]}")
nl_over_n0 = np.zeros(prm.idr, object)
nu_over_nl = np.zeros(prm.idr, object)
for lx in prm.line_range[index]:
print(f"lx = {lx}, index = {index}, prm.line_range[{index}] = {prm.line_range[index]}") \
if prm.lte_debug_mode else None
g0 = g0s[index]
print(f"g0s[{index}] = {g0s[index]}") if prm.lte_debug_mode else None
print(f"g1s[{index}] = {g1s[index]}") if prm.lte_debug_mode else None
if ion_level[lx] == 0:
if g0 != 0:
print(f"{element} loop. lx = {lx}, index = {index}, g0 = {g0}") if prm.lte_debug_mode else None
nl_over_n0[lx] = boltzmann_ratio(gl[lx], g0, el_ev[lx], 0.0, temp)
nu_over_nl[lx] = boltzmann_ratio(gu[lx], gl[lx], eu_ev[lx], el_ev[lx], temp)
print(f"boltzmann ratio({gl[lx], g0, el_ev[lx]}, 0) \n{nl_over_n0[lx]}") \
if prm.lte_debug_mode else None
print(f"boltzmann ratio({gu[lx], gl[lx], eu_ev[lx], el_ev[lx]}) \n{nu_over_nl[lx]}") \
if prm.lte_debug_mode else None
nl_over_nt[lx] = nx_over_nt[index, 0] * nl_over_n0[lx]
nu_over_nt[lx] = nx_over_nt[index, 0] * nu_over_nl[lx] * nl_over_n0[lx]
else:
print("element without g0 value. Abort.")
exit()
else:
print(f"ion_level[{lx}] = {ion_level[lx]}, element = {element}") if prm.lte_debug_mode else None
# nl_over_n0 = 1.0 for resonance lines
print(f"{element} loop. lx = {lx}, index = {index}, g0 = {g0}") if prm.lte_debug_mode else None
nl_over_nt[lx] = nx_over_nt[index, 1] # pop in first ionization state ground level
nu_over_nt[lx] = boltzmann_ratio(gu[lx], gl[lx], eu_ev[lx], el_ev[lx], temp) * nx_over_nt[index, 1]
print(f"boltzmann ratio({gu[lx], gl[lx], eu_ev[lx], el_ev[lx]}) \n{nu_over_nt[lx]}") \
if prm.lte_debug_mode else None
if prm.lte_debug_mode:
print(f"nl_over_nt[{lx}] \n{nl_over_nt[lx]}")
print(f"nu_over_nt[{lx}] \n{nu_over_nt[lx]}")
n_elem = nt * abund[lx]
print(f"n_element \n{n_elem}") if prm.lte_debug_mode else None
for i in range(prm.idr):
nl[lx, i] = nl_over_nt[lx][i] * n_elem[i]
nu[lx, i] = nu_over_nt[lx][i] * n_elem[i]
if prm.lte_debug_mode:
print(f"lx = {lx} \nnl[{lx}] \n {nl[lx, :]} \nnu[{lx}] \n{nu[lx, :]}")
print(f"abund[{lx}] = {abund[lx]}")
# tau is Eq. 4.7.29 in Ünsold & Bascheck's "Der Neue Kosmos" without the phi(nu) profile function.
# m = u, n = l. We do not assume negligible stimulated emission in the following.
tau[lx, :] = tau_cst * flu[lx] * nl[lx, :] * (1.0 - (nu[lx, :] / gu[lx]) / (nl[lx, :] / gl[lx]))
return ne, nl, nu, mu, tau
|
claude-bertoutREPO_NAMESLIM2PATH_START.@SLIM2_extracted@SLIM2-main@LTE_module.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "astropy/halotools",
"repo_path": "halotools_extracted/halotools-master/halotools/empirical_models/__init__.py",
"type": "Python"
}
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .model_defaults import *
from .model_helpers import *
from .factories import *
from .assembias_models import *
from .phase_space_models import *
from .component_model_templates import *
from .sfr_models import *
from .occupation_models import *
from .smhm_models import *
from .composite_models import *
from .abunmatch import *
from .ia_models import *
|
astropyREPO_NAMEhalotoolsPATH_START.@halotools_extracted@halotools-master@halotools@empirical_models@__init__.py@.PATH_END.py
|
{
"filename": "MakeFakeImage.py",
"repo_name": "jah1994/PyTorchDIA",
"repo_path": "PyTorchDIA_extracted/PyTorchDIA-master/MakeFakeImage.py",
"type": "Python"
}
|
import numpy as np
def make_noiseless_image(shape, positions, fluxes, sky, psf_sigma):
"""
Make one image.
"""
fluxes_in_stamp = []
img = np.zeros(shape)
img += sky
nx, ny = shape
xg, yg = np.meshgrid(range(nx), range(ny))
for pos, f in zip(positions, fluxes):
#print(pos[0], pos[1])
kernel = np.exp(-0.5 * ((xg - pos[0]) ** 2 + (yg - pos[1]) ** 2)
/ psf_sigma ** 2)
#img += f * kernel / (2. * np.pi * psf_sigma ** 2) ## original line - doesn't guarantee kernel normalised ###
kernel /= np.sum(kernel) # normalise kernel
#print('kernel sum:', np.sum(kernel))
img += f * kernel
#if 19 < pos[0] < img.shape[0] - 19 and 19 < pos[1] < img.shape[1] - 19:
# fluxes_in_stamp.append(f)
#img += f*(kernel/np.sum(kernel))
#print('f', f)
#print('kernel sum', np.sum(kernel))
#print('sum', np.sum(img))
#stop = input()
return img, fluxes_in_stamp
def MakeFake(N, size, n_sources, psf_sigma, sky, positions, fluxes, shifts):
'''
N: Number of images
size: image axis length (assumed to be square)
n_sources: Number of sources
psf_sigma: std of gaussian psf profile
sky: sky level (ADU)
'''
#np.random.seed()
shape = (size, size)
# positions
#positions_x = np.random.uniform(0, size, (n_sources,1))
#positions_y = np.random.uniform(0, size, (n_sources,1))
#positions = np.hstack((positions_x, positions_y))
# fluxes
#F = np.random.uniform(10**(-9), 10**(-4.5), n_sources)
#fluxes = F**(-2./3.)
## relocate the brightest source to the image centre
centre = np.int(size/2)
F_max_index = np.where(fluxes == np.max(fluxes))
#print(shifts[0], shifts[1])
positions[F_max_index] = np.array([[centre + shifts[0], centre + shifts[1]]])
#F_min_index = np.where(fluxes == np.min(fluxes))
#positions[F_min_index] = np.array([[centre, centre]])
# F_max / total flux in image (the 104 x 104 region used for the inference)
print('Max flux:', np.max(fluxes))
print('Frac for 142x142 image:', np.max(fluxes) / np.sum(fluxes))
for n in range(N):
img, fluxes_in_stamp = make_noiseless_image(shape, positions, fluxes, sky, psf_sigma)
#F_frac = np.max(fluxes_in_stamp) / np.sum(fluxes_in_stamp)
F_frac = np.max(fluxes) / np.sum(fluxes)
return img, F_frac
|
jah1994REPO_NAMEPyTorchDIAPATH_START.@PyTorchDIA_extracted@PyTorchDIA-master@MakeFakeImage.py@.PATH_END.py
|
{
"filename": "_line.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/layout/shape/_line.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class LineValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="line", parent_name="layout.shape", **kwargs):
super(LineValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Line"),
data_docs=kwargs.pop(
"data_docs",
"""
color
Sets the line color.
dash
Sets the dash style of lines. Set to a dash
type string ("solid", "dot", "dash",
"longdash", "dashdot", or "longdashdot") or a
dash length list in px (eg "5px,10px,2px,2px").
width
Sets the line width (in px).
""",
),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@layout@shape@_line.py@.PATH_END.py
|
{
"filename": "_ids.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/table/_ids.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class IdsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="ids", parent_name="table", **kwargs):
super(IdsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@table@_ids.py@.PATH_END.py
|
{
"filename": "_marker.py",
"repo_name": "plotly/plotly.py",
"repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/graph_objs/choroplethmap/selected/_marker.py",
"type": "Python"
}
|
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Marker(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "choroplethmap.selected"
_path_str = "choroplethmap.selected.marker"
_valid_props = {"opacity"}
# opacity
# -------
@property
def opacity(self):
"""
Sets the marker opacity of selected points.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["opacity"]
@opacity.setter
def opacity(self, val):
self["opacity"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
opacity
Sets the marker opacity of selected points.
"""
def __init__(self, arg=None, opacity=None, **kwargs):
"""
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.choroplethmap.
selected.Marker`
opacity
Sets the marker opacity of selected points.
Returns
-------
Marker
"""
super(Marker, self).__init__("marker")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.choroplethmap.selected.Marker
constructor must be a dict or
an instance of :class:`plotly.graph_objs.choroplethmap.selected.Marker`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
|
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@graph_objs@choroplethmap@selected@_marker.py@.PATH_END.py
|
{
"filename": "bedrock_anthropic_callback.py",
"repo_name": "langchain-ai/langchain",
"repo_path": "langchain_extracted/langchain-master/libs/community/langchain_community/callbacks/bedrock_anthropic_callback.py",
"type": "Python"
}
|
import threading
from typing import Any, Dict, List, Union
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.outputs import LLMResult
MODEL_COST_PER_1K_INPUT_TOKENS = {
"anthropic.claude-instant-v1": 0.0008,
"anthropic.claude-v2": 0.008,
"anthropic.claude-v2:1": 0.008,
"anthropic.claude-3-sonnet-20240229-v1:0": 0.003,
"anthropic.claude-3-5-sonnet-20240620-v1:0": 0.003,
"anthropic.claude-3-5-sonnet-20241022-v2:0": 0.003,
"anthropic.claude-3-haiku-20240307-v1:0": 0.00025,
}
MODEL_COST_PER_1K_OUTPUT_TOKENS = {
"anthropic.claude-instant-v1": 0.0024,
"anthropic.claude-v2": 0.024,
"anthropic.claude-v2:1": 0.024,
"anthropic.claude-3-sonnet-20240229-v1:0": 0.015,
"anthropic.claude-3-5-sonnet-20240620-v1:0": 0.015,
"anthropic.claude-3-5-sonnet-20241022-v2:0": 0.015,
"anthropic.claude-3-haiku-20240307-v1:0": 0.00125,
}
def _get_anthropic_claude_token_cost(
prompt_tokens: int, completion_tokens: int, model_id: Union[str, None]
) -> float:
"""Get the cost of tokens for the Claude model."""
if model_id not in MODEL_COST_PER_1K_INPUT_TOKENS:
raise ValueError(
f"Unknown model: {model_id}. Please provide a valid Anthropic model name."
"Known models are: " + ", ".join(MODEL_COST_PER_1K_INPUT_TOKENS.keys())
)
return (prompt_tokens / 1000) * MODEL_COST_PER_1K_INPUT_TOKENS[model_id] + (
completion_tokens / 1000
) * MODEL_COST_PER_1K_OUTPUT_TOKENS[model_id]
class BedrockAnthropicTokenUsageCallbackHandler(BaseCallbackHandler):
"""Callback Handler that tracks bedrock anthropic info."""
total_tokens: int = 0
prompt_tokens: int = 0
completion_tokens: int = 0
successful_requests: int = 0
total_cost: float = 0.0
def __init__(self) -> None:
super().__init__()
self._lock = threading.Lock()
def __repr__(self) -> str:
return (
f"Tokens Used: {self.total_tokens}\n"
f"\tPrompt Tokens: {self.prompt_tokens}\n"
f"\tCompletion Tokens: {self.completion_tokens}\n"
f"Successful Requests: {self.successful_requests}\n"
f"Total Cost (USD): ${self.total_cost}"
)
@property
def always_verbose(self) -> bool:
"""Whether to call verbose callbacks even if verbose is False."""
return True
def on_llm_start(
self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
) -> None:
"""Print out the prompts."""
pass
def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
"""Print out the token."""
pass
def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
"""Collect token usage."""
if response.llm_output is None:
return None
if "usage" not in response.llm_output:
with self._lock:
self.successful_requests += 1
return None
# compute tokens and cost for this request
token_usage = response.llm_output["usage"]
completion_tokens = token_usage.get("completion_tokens", 0)
prompt_tokens = token_usage.get("prompt_tokens", 0)
total_tokens = token_usage.get("total_tokens", 0)
model_id = response.llm_output.get("model_id", None)
total_cost = _get_anthropic_claude_token_cost(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
model_id=model_id,
)
# update shared state behind lock
with self._lock:
self.total_cost += total_cost
self.total_tokens += total_tokens
self.prompt_tokens += prompt_tokens
self.completion_tokens += completion_tokens
self.successful_requests += 1
def __copy__(self) -> "BedrockAnthropicTokenUsageCallbackHandler":
"""Return a copy of the callback handler."""
return self
def __deepcopy__(self, memo: Any) -> "BedrockAnthropicTokenUsageCallbackHandler":
"""Return a deep copy of the callback handler."""
return self
|
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@langchain_community@callbacks@bedrock_anthropic_callback.py@.PATH_END.py
|
{
"filename": "mag.md",
"repo_name": "tamarervin/SolAster",
"repo_path": "SolAster_extracted/SolAster-main/mkdocs/docs/calcs/mag.md",
"type": "Markdown"
}
|
# Calculation of Solar Magnetic Observables
Using HMI magnetograms, we are able to calculate magnetic observables that
both correlate with each other as well as the velocity features. This shows
how the magnetic activity is driving the radial velocity variations.
## Filling Factor
**Disk averaged filling factors of sunspots and plage which gives
the percentage of magnetically active pixels.**
The filling factor is a calculation of the percentage of active pixels on the solar
surface at any one time. We calculate three different factors: $f_{spot}$, $f_{bright}$,
and $f$. These are the filling factors due to sunspots, faculae/network, and the total
filling factor which is the sum of the two.
We return the filling factor as a percentage:
$f = \frac{1}{N_{pix}} \sum_{ij} W_{ij} * 100$
```python
def filling_factor(mu, mmap, active, fac_inds, spot_inds, mu_cutoff=0.3):
"""
function to calculate filling factor
Parameters
----------
mu: array of mu (cosine theta) values
mmap: UNCORRECTED Sunpy map object (Magnetogram)
active: weights array where active pixels have weight = 1
fac_inds: array of indices where faculae are detected
spot_inds: array of indices where sunspots are detected
mu_cutoff: minimum mu cutoff value
Returns
-------
f_bright: filling factor (%) for bright areas (faculae)
f_spot: filling factor (%) for dark areas (sunspots)
f_total: filling factor (%) for timestamp
"""
# get good mu values
good_mu = np.where(mu > mu_cutoff)
# get number of pixels
npix = len(mmap.data[good_mu])
# faculae
faculae = np.zeros(mmap.data.shape)
faculae[fac_inds] = 1.
f_bright = np.sum(faculae) / npix * 100
# sunspots
spots = np.zeros(mmap.data.shape)
spots[spot_inds] = 1.
f_spot = np.sum(spots) / npix * 100
# get filling factor
f_total = np.sum(active) / npix * 100
return f_bright, f_spot, f_total
```
## Unsigned Magnetic Flux
**The disc-averaged, line-of-sight unsigned (unpolarized) magnetic flux of the Sun.**
$|\hat{B_{obs}}| = \frac{\sum_{ij} |B_{obs, ij}| I_{ij}} {\sum_{ij} I_{ij}}$
```python
def unsigned_flux(map_mag_obs, imap):
"""
calculate unsigned magnetic flux
Parameters
----------
map_mag_obs: corrected observed magnetic field strength Sunpy map object (Magnetogram)
imap: UNCORRECTED Sunpy map object (Intensitygram)
Returns
-------
unsign_flux: unsigned magnetic flux
"""
unsign_flux = np.nansum(np.abs(map_mag_obs.data) * imap.data) / np.nansum(imap.data)
return np.abs(unsign_flux)
```
## Area Based Magnetic Observables
In addition to the unsigned flux and filling factor calculations described above, we calculate
these quantities with an eye for what types of regions are causing variations in magnetic
activity. The calculations for area thresholded regions is outlined below.
### Area Thresholded Filling Factor
```python
def area_filling_factor(active, area, mu, mmap, fac_inds, athresh=20, mu_cutoff=0.3):
"""
calculate filling factor for regions thresholded by area
- differentiate between large and small regions
- differentiate between plage (large) and network (small) bright regions
Parameters
----------
active: weights array where active pixels have weight = 1
area: area of each active region weighted by its intensity
mu: array of mu (cosine theta) values
mmap: UNCORRECTED Sunpy map object (Magnetogram)
fac_inds: array of indices where faculae are detected
athresh: area threshold value between large and small regions (in uHem)
mu_cutoff: minimum mu cutoff value for usable data
Returns
-------
f_small: filling factor (%) for small magnetically active regions
f_large: filling factor (%) for large magnetically active regions
f_network: filling factor (%) for network (small, bright magnetically active) regions
f_plage: filling factor (%) for plage (large, bright magnetically active) regions
f_nonconv: filling factor (%) for regions that do not suppress convective blueshift
"""
# get good mu values
good_mu = np.where(mu > mu_cutoff)
# get number of pixels
npix = len(mmap.data[good_mu])
# get quiet pixels
quiet = 1 - active
# get filling factor for 'small' magnetic features
small = np.zeros(mmap.data.shape)
small_inds = np.logical_and(active > 0.5, area < athresh)
small[small_inds] = 1.
f_small = np.nansum(small) / npix * 100
# get filling factor for 'large' magnetic features
large = np.zeros(mmap.data.shape)
large_inds = np.logical_and(active > 0.5, area > athresh)
large[large_inds] = 1.
f_large = np.nansum(large) / npix * 100
# get filling factor for network (small, faculae regions)
network = np.zeros(mmap.data.shape)
network_inds = np.logical_and(small > 0.5, fac_inds > 0.5)
network[network_inds] = 1.
f_network = np.nansum(network) / npix * 100
# get filling factor for plage (large, faculae regions)
plage = np.zeros(mmap.data.shape)
plage_inds = np.logical_and(large > 0.5, fac_inds > 0.5)
plage[plage_inds] = 1.
f_plage = np.nansum(plage) / npix * 100
# get filling factor for small, non-convective regions
nonconv = np.zeros(mmap.data.shape)
nonconv_inds = np.logical_and(quiet > 0.5, small > 0.5)
nonconv[nonconv_inds] = 1.
f_nonconv = np.nansum(nonconv) / npix * 100
return f_small, f_large, f_network, f_plage, f_nonconv
```
### Area Thresholded Unsigned Flux
```python
def area_unsigned_flux(map_mag_obs, imap, area, active, athresh=20):
"""
calculate the magnetic flux for different regions based on area cut
and magnetic activitiy
Parameters
----------
map_mag_obs: corrected observed magnetic field strength Sunpy map object (Magnetogram)
imap: UNCORRECTED Sunpy map object (Intensitygram)
area: area of each active region weighted by its intensity
active: weights array where active pixels have weight = 1
Returns
-------
quiet_flux: magnetic flux of quiet-Sun regions
ar_flux: magnetic flux of active regions
conv_flux: magnetic flux of regions that suppress convective blueshift
pol_flux: magnetic flux of polarized regions
pol_conv_flux: magnetic flux of polarized regions that suppress the convective blueshift
"""
# get data arrays
i_data = imap.data
m_data = map_mag_obs.data
mabs_data = np.abs(m_data)
quiet = 1 - active
# get large regions array
large = np.zeros(m_data.shape)
large_inds = np.logical_and(active > 0.5, area > athresh)
large[large_inds] = 1.
# calculate relevant fluxes
quiet_flux = np.nansum(mabs_data * i_data * quiet) / np.nansum(i_data * quiet)
ar_flux = np.nansum(mabs_data * i_data * active) / np.nansum(i_data * active)
conv_flux = np.nansum(mabs_data * i_data * large) / np.nansum(i_data * large)
pol_flux = np.nansum(m_data * i_data) / np.nansum(i_data)
pol_conv_flux = np.nansum(m_data * i_data * large) / np.nansum(i_data * large)
return quiet_flux, ar_flux, conv_flux, pol_flux, pol_conv_flux
```
|
tamarervinREPO_NAMESolAsterPATH_START.@SolAster_extracted@SolAster-main@mkdocs@docs@calcs@mag.md@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "plotly/plotly.py",
"repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/isosurface/colorbar/tickfont/__init__.py",
"type": "Python"
}
|
import sys
from typing import TYPE_CHECKING
if sys.version_info < (3, 7) or TYPE_CHECKING:
from ._weight import WeightValidator
from ._variant import VariantValidator
from ._textcase import TextcaseValidator
from ._style import StyleValidator
from ._size import SizeValidator
from ._shadow import ShadowValidator
from ._lineposition import LinepositionValidator
from ._family import FamilyValidator
from ._color import ColorValidator
else:
from _plotly_utils.importers import relative_import
__all__, __getattr__, __dir__ = relative_import(
__name__,
[],
[
"._weight.WeightValidator",
"._variant.VariantValidator",
"._textcase.TextcaseValidator",
"._style.StyleValidator",
"._size.SizeValidator",
"._shadow.ShadowValidator",
"._lineposition.LinepositionValidator",
"._family.FamilyValidator",
"._color.ColorValidator",
],
)
|
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@isosurface@colorbar@tickfont@__init__.py@.PATH_END.py
|
{
"filename": "11818_pils_maxlen.py",
"repo_name": "shreeyesh-biswal/Rvalue_3D",
"repo_path": "Rvalue_3D_extracted/Rvalue_3D-main/Codes/M-class/AR_11818/11818_pils_maxlen.py",
"type": "Python"
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 5 22:55:01 2022
@author: shreeyeshbiswal
"""
import os
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
AR = "11818"
core_dir = "/home/shreeyeshbiswal/IDLWorkspace/Dataset_PF/"
base_dir = "/home/shreeyeshbiswal/IDLWorkspace/Dataset_PF/AR_" + AR
dir_list = sorted(os.listdir(base_dir))
n = len(dir_list)
m = 10 # values per file
tot_len_matrix = np.zeros(shape=(n,m))
max_len_matrix = np.zeros(shape=(n,m))
abs_flx_matrix = np.zeros(shape=(n,m))
index = np.arange(0,n)
height = np.arange(0,m)*0.36
P2 = 'Maximum Length of PILs (Mm); AR '+ AR
colorbarticks = [0, 30, 60, 90, 120, 150]
cbar_min = 0
cbar_max = 150
flare_time = 138.27
for i in range(0,n):
Time_tag = dir_list[i]
Time = Time_tag[0:19]
Hour = Time[11:13]
print(Time)
dir = "/home/shreeyeshbiswal/IDLWorkspace/Dataset_PF/AR_" + AR + "/" + Time_tag
os.chdir(dir)
# the if-else statement takes care of missing data
if len(os.listdir(dir)) != 0:
mpils = np.loadtxt("PF_ext_mpils_" + Time + ".dat")
print(np.shape(mpils))
tot_len_matrix[i,:] = mpils[:,0]
max_len_matrix[i,:] = mpils[:,1]
abs_flx_matrix[i,:] = mpils[:,2]
print(Hour)
else:
tot_len_matrix[i,:] = np.nan
max_len_matrix[i,:] = np.nan
abs_flx_matrix[i,:] = np.nan
print("Empty directory")
os.chdir(core_dir)
x = np.arange(0,n)
figure(figsize=(10,10), dpi=100000)
figure, axs = plt.subplots(10)
figure.set_figheight(15)
figure.set_figwidth(9)
cm = plt.cm.get_cmap('afmhot')
mpl.rc('xtick', labelsize=13)
# Plot
sc = axs[0].scatter(x, max_len_matrix[:,9], c = max_len_matrix[:,9], vmin=cbar_min, vmax=cbar_max, s=10, cmap=cm)
for i in range(0,m):
axs[i].scatter(x, max_len_matrix[:,9-i], c = max_len_matrix[:,9-i], vmin=cbar_min, vmax=cbar_max, s=10, cmap=cm)
for i in range(0,m):
axs[i].set_ylim([cbar_min, cbar_max])
plt.setp(plt.gcf().get_axes(), xticks=[], yticks=[]);
axs[9].tick_params(axis='x', labelsize=16)
axs[9].set_xticks(np.arange(0,n,24))
# Hide the ylims of individual boxes
for i in range(0,m):
axs[i].set_yticks([])
# Show heights in the altitude
heightfont = 16
for i in range(0,m):
max_alt = (m-1)*0.36
altitude = max_alt-(i*0.36)
alt_str = "{:.2f}".format(altitude)
axs[i].set_ylabel(alt_str + ' ', fontsize = heightfont, rotation = 0)
# Show flare occurence in dotted lines
for i in range(0,m):
axs[i].axvline(x = flare_time, ymin = 0, ymax = 1, linestyle = '--', color = 'k', alpha=0.40)# Show heights in the altitude
# Orient the text
st = dir_list[0]
start_time = st[0:4] + '/' + st[5:7] + '/' + st[8:10] + '/' + st[11:13] + ':' + st[14:16]
axs[0].text(-18, (cbar_max + (0.35*(cbar_max - cbar_min))), P2, fontsize=23)
axs[5].text(-42, cbar_min + 0.5*(cbar_max - cbar_min), 'Height (Mm)', rotation = 90, fontsize=18)
axs[9].text(19, (cbar_min - (0.65*(cbar_max - cbar_min))), 'Time after ' + start_time + ' (hrs)', rotation = 0, fontsize=18)
figure.subplots_adjust(right=0.8)
cbar_ax = figure.add_axes([0.85, 0.15, 0.05, 0.7])
cbar_ax.tick_params(labelsize=16)
figure.colorbar(sc, cax=cbar_ax, ticks=colorbarticks)
plt.subplots_adjust(wspace=0.5, hspace=0)
plt.show()
mpl.rcParams.update(mpl.rcParamsDefault)
|
shreeyesh-biswalREPO_NAMERvalue_3DPATH_START.@Rvalue_3D_extracted@Rvalue_3D-main@Codes@M-class@AR_11818@11818_pils_maxlen.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "msiebert1/UCSC_spectral_pipeline",
"repo_path": "UCSC_spectral_pipeline_extracted/UCSC_spectral_pipeline-master/spectral_reduction/tmath/wombat/__init__.py",
"type": "Python"
}
|
HOPSIZE=20
from .getch import getch
from .inputter import inputter
from .inputter_single import inputter_single
from .inputter_single_mix import inputter_single_mix
from .yesno import yesno
from .airtovac import airtovac
from .wommkatmdisp import wommkatmdisp
from .womhop import womhop
from .womrdhop import womrdhop
from .wombuf import wombuf
from .womrpl import womrpl
from .womwpl import womwpl
from .womplot import womplot
from .womapl import womapl
from .waveparse import waveparse
from .wommkbb import wommkbb
from .womrdfits import womrdfits
from .wshow import wshow
from .womwaverange import womwaverange
from .womget_element import womget_element
from .womcho import womcho
from .womashrebinselector import womashrebinselector
from .womscipyrebinselector import womscipyrebinselector
from .womrebindriver import womrebindriver
from .womply import womply
from .womrebin_tform import womrebin_tform
from .womashrebin import womashrebin
from .womscipyrebin import womscipyrebin
from .womstat import womstat
from .womexam import womexam
from .womsmo import womsmo
from .womplotlog import womplotlog
from .womscale import womscale
from .womscale2match import womscale2match
from .womscalemany import womscalemany
from .womredshift import womredshift
from .womblueshift import womblueshift
from .womms import womms
from .womfnuflam import womfnuflam
from .womlup import womlup
from .wombluen import wombluen
from .womrelvel import womrelvel
from .womxshift import womxshift
from .womyshift import womyshift
from .womzap import womzap
from .womcomselector import womcomselector
from .womcmwselector import womcmwselector
from .womcom3selector import womcom3selector
from .womcommanyselector import womcommanyselector
from .womcommanywselector import womcommanywselector
from .womcom import womcom
from .womjoin import womjoin
from .womreddening import womreddening
from .womheader import womheader
from .getmswave import getmswave
from .womrmsfits import womrmsfits
from .womwfits import womwfits
from .filtermag import filtermag
from .filterconv import filterconv
from .womfilters import womfilters
from .womirfilters import womirfilters
from .womhertz import womhertz
from .womsqr import womsqr
from .womsqrt import womsqrt
from .womblo import womblo
from .onclick import onclick
from .womspl import womspl
from .womvelcho import womvelcho
from .womint import womint
from .gauss import gauss
from .gauss_cont import gauss_cont
from .womgau import womgau
from .womwavescale import womwavescale
from .womhelp import womhelp
from .get_screen_size import get_screen_size
from .womcat import womcat
|
msiebert1REPO_NAMEUCSC_spectral_pipelinePATH_START.@UCSC_spectral_pipeline_extracted@UCSC_spectral_pipeline-master@spectral_reduction@tmath@wombat@__init__.py@.PATH_END.py
|
{
"filename": "extensions.py",
"repo_name": "tensorflow/tensorflow",
"repo_path": "tensorflow_extracted/tensorflow-master/tensorflow/python/ops/numpy_ops/tests/extensions.py",
"type": "Python"
}
|
# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Extensions such as `jit`, `grad`, `logsumexp`, etc."""
import bisect
import contextlib
import copy
import functools
import string
import sys
import threading
import numpy as np
import six
from tensorflow.python.compiler.xla import xla
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.eager.polymorphic_function import polymorphic_function
from tensorflow.python.framework import config
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import device_spec
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import indexed_slices
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor as tensor_lib
from tensorflow.python.framework import tensor_conversion_registry
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import array_ops_stack
from tensorflow.python.ops import clip_ops
from tensorflow.python.ops import control_flow_assert
from tensorflow.python.ops import custom_gradient
from tensorflow.python.ops import gen_bitwise_ops
from tensorflow.python.ops import gen_collective_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import special_math_ops
from tensorflow.python.ops import stateless_random_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import while_loop
import tensorflow.python.ops.numpy_ops.tests.np_wrapper as tf_np
from tensorflow.python.ops.parallel_for import control_flow_ops as pfor_ops
from tensorflow.python.tpu import tpu
from tensorflow.python.tpu.ops import tpu_ops
from tensorflow.python.util import nest
_int_dtype_lower_bounds = [
-2**63, -2**31, -2**15, -2**7, 0, 2**7, 2**15, 2**31, 2**64
]
_int_dtypes = [
dtypes.int64,
dtypes.int32,
dtypes.int16,
dtypes.int8,
dtypes.uint8,
dtypes.uint16,
dtypes.uint32,
dtypes.uint64,
]
_tf_nn_APIs = {
1: [nn_ops.conv1d, nn_ops.conv1d_transpose],
2: [nn_ops.conv2d_v2, nn_ops.conv2d_transpose],
3: [nn_ops.conv3d_v2, nn_ops.conv3d_transpose],
}
remat = custom_gradient.recompute_grad
def most_precise_int_dtype(x):
if not isinstance(x, six.integer_types) or isinstance(x, bool):
return None
i = bisect.bisect_right(_int_dtype_lower_bounds, x)
if i in (0, len(_int_dtype_lower_bounds)):
raise ValueError("Integer %s is out of bounds" % x)
assert len(_int_dtype_lower_bounds) == len(_int_dtypes) + 1
return _int_dtypes[i - 1]
def _canonicalize_jit_arg(x): # pylint: disable=missing-function-docstring
if isinstance(x, tf_np.ndarray):
return x
try:
# We need to convert `int` to the most precise dtype, otherwise the dtype
# of the result may be different from numpy's. For example, when a binary
# op takes in a Python integer 5 and an array of uint32, numpy will pick
# uint32 as 5's dtype, while tf.convert_to_tensor will choose int32 which
# will cause the two arguments to be promoted to int64. We pick uint8
# here, which will be promoted to uint32 by the binary op.
# Note that we prefer unsigned int to signed int when both are equally
# precise. For example, for 5, we pick uint8 instead of int8. There is no
# reason to prefer one to the other, because for each there is a case
# where the behavior diverges from numpy. If we prefer signed int,
# consider the case where the first operand is 5 and the second is
# 2**64-1. Numpy picks uint64 as the result dtype, but because we choose a
# signed type for 5 such as int8, the result type will be float64. On the
# other hand, if we prefer unsigned int, consider the case where the first
# operand is 2**31-1 and the second is -1. Numpy will pick int32, but
# because we choose uint32 for 2*32-1, the result will be int64. The root
# of the problem is that `jit` converts `int` to tensors (hence committing
# to a dtype) too early, when we don't have enough information about the
# jitted function (e.g. which subset of the arguments should be promoted
# together using np.result_type). tf.function doesn't have this problem
# because it doesn't convert `int` to tensors. jax.jit doesn't have this
# problem because it converts `int` to "int tracer" which doesn't commit
# to a dtype.
# TODO(wangpeng): Revisit this design and see whether we can improve `jit`
# and tf.function.
dtype = most_precise_int_dtype(x)
if dtype is None and isinstance(x, float):
dtype = tf_np.default_float_type()
return ops.convert_to_tensor(value=x, dtype=dtype)
except (TypeError, ValueError):
return x
def _canonicalize_jit_arguments(inp):
"""Canonicalize arguments to be used for jit.
Args:
inp: a nested structure of arguments to be canonicalized (i.e. to be
converted to Tensors). Only tf_np.ndarray and things accepted by
`tf.convert_to_tensor` will be converted.
Returns:
The canonicalized version.
"""
return nest.map_structure(_canonicalize_jit_arg, inp)
def _tf_to_np(inp):
def f(x):
if isinstance(x, indexed_slices.IndexedSlices):
return tf_np.asarray(x)
else:
return x
return nest.map_structure(f, inp)
def stop_gradient(x):
def static_stop_gradient(x):
# `tf.stop_gradient` is a no-op for non-Tensor. Returning the original type
# allows it to be used in the conditional without Autograph, if static. For
# example:
# `if fastmath.stop_gradient(5) > 4:`
return array_ops.stop_gradient(x) if tensor_util.is_tensor(x) else x
return _tf_to_np(nest.map_structure(static_stop_gradient, x))
def custom_grad(f_vjp, f_original=None):
"""Decorator to define a function with a custom gradient.
This function is very similar to `tf.custom_gradient`. See the documentation
of `tf.custom_gradient` for detailed usage.
The differences with `tf.custom_gradient` are:
- All arguments and results are tf_np.ndarrays instead of tensors.
- The `grad_fn` returned by `f_vjp` accepts and returns nested structures,
unlike that in `tf.custom_gradient` which only accepts and returns lists.
Args:
f_vjp: the same as the `f` argument of `tf.custom_gradient`. Note that all
inputs and outputs of `f_vjp` and of the `grad_fn` function it returns can
be nested structures.
f_original: (optional) not used.
Returns:
The same as `tf.custom_gradient`.
"""
del f_original
@custom_gradient.custom_gradient
def tf_f(*tf_args, **tf_kwargs):
np_args = _tf_to_np(tf_args)
np_kwargs = _tf_to_np(tf_kwargs)
np_y, np_vjp = f_vjp(*np_args, **np_kwargs)
tf_y = np_y
def tf_vjp(*flat_tf_dy):
tf_dy = nest.pack_sequence_as(tf_y, flat_tf_dy)
np_dy = _tf_to_np(tf_dy)
np_dx = np_vjp(np_dy)
return nest.flatten(np_dx)
return tf_y, tf_vjp
def np_f(*args, **kwargs):
return _tf_to_np(tf_f(*args), **kwargs)
return np_f
def vjp(f, *primals, has_aux=False):
"""Returns the result and the VJP function of `f`.
This function returns the result and the vector-Jacobian-product (VJP)
function of `f`.
Args:
f: a function from (nested structures of) tf_np.ndarrays to a (nested
structure of) tf_np.ndarray. If `has_aux` is True, it should return an
extra output.
*primals: the inputs to be fed to `f`.
has_aux: if True, the second output of `f` will be regarded as an auxiliary,
non-differentiable output that will be ignored by the VJP function.
Returns:
A pair `(y, vjpfun)` if `has_aux` is False; a tuple `(y, vjpfun, aux)`
otherwise. `y` and `aux` are the outputs of `f`, i.e. `y, aux =
f(*primals)`. `vjpfun` is a function `dx = vjpfun(dy)`, where `dy` is the
cotengents of `y`, having the same structures, shapes and dtypes as
`y`. `dx` is the cotengents of `x`, having the same structures, shapes and
dtypes as `x`.
"""
with backprop.GradientTape(persistent=True) as tape:
tape.watch(nest.flatten(primals))
outputs = f(*primals)
if has_aux:
np_out, aux = outputs
else:
np_out = outputs
def _vjp(dy):
tf_dx = tape.gradient(np_out, primals, output_gradients=dy)
return _tf_to_np(tf_dx)
if has_aux:
ret = (np_out, _vjp, aux)
else:
ret = (np_out, _vjp)
return ret
# TODO(wangpeng): match JAX's handling of kwargs and non-ndarray args
def grad(f, has_aux=False):
"""Returns a function that computes gradient of f.
Gradients can only be computed through numpy and tensorflow operations and not
through python float operations and values.
Args:
f: a function of type (params, *args) -> scalar. 'params' can be a nested
structure (made of lists and tuples) of ndarrays and the gradient is
evaluated against it. `scalar` is a scalar ndarray.
has_aux: bool, indicates whether fun returns a pair where the first element
is considered the output of the mathematical function to be differentiated
and the second element is auxiliary data.
Returns:
A gradient function of type (params, *args) -> gradients, where the result
'gradients' has the same structure and shapes as 'params'.
"""
def check_loss_shape(np_loss):
if not isinstance(np_loss, tf_np.ndarray):
raise ValueError(
"The result of the function to take gradient must be an ndarray.")
if not np_loss.shape.is_compatible_with([]):
raise ValueError(
"The result of the function to take gradient must be a scalar.")
def _f(params, *args):
"""The gradient function to be returned."""
with backprop.GradientTape() as g:
g.watch(nest.flatten(params))
outputs = f(params, *args)
if has_aux:
np_loss, aux = outputs
else:
np_loss = outputs
check_loss_shape(np_loss)
tf_grads = g.gradient(np_loss, params)
if has_aux:
res = (tf_grads, aux)
else:
res = tf_grads
return _tf_to_np(res)
return _f
def _record_result_type(recorder, f):
"""A decorator that records some information about the function.
Args:
recorder: a function of signature `(args, kwargs, res) -> res`.
f: the original function.
Returns:
A transformed function that calls the original function and then the
recorder afterwards.
"""
def wrapper(*args, **kwargs):
res = f(*args, **kwargs)
res = recorder(args, kwargs, res)
return res
return wrapper
def jit(f,
static_argnums=(),
xla_forced_compile=False,
input_signature=None,
autograph=False,
experimental_compile=False):
"""Returns a function that runs a trace-compiled version of `f`.
A trace-compiled version of a function `f` has the same behavior as `f` (when
called with the same "static arguments", see below), but runs faster because
the whole computation is compiled into a computation graph once which is
reused for subsequent executions.
The trace compilation happens lazily, when the returned function is called for
the first time. The compiled function may not be cached implicitly and
multiple calls to `jit` may not share the compiled function (see below for
"static" vs "dynamic" arguments).
Args:
f: a function that takes any positional arguments `args` and any keyword
arguments `kwargs`. `ndarray`s and things accepted by
`tf.convert_to_tensor` in `args` and `kwargs` will be treated as 'dynamic
arguments' in the sense that calling the function with different values
for these arguments will not cause retracing. In contrast, arguments of
other types in `args` and `kwargs` are treated as 'static arguments' and
calling the function with different values of them will cause
re-compiling. Positional arguments whose positions are in `static_argnums`
are always treated as static arguments.
static_argnums: a tuple of positions of arguments that will be treated as
static arguments. Note that as aforementioned, any arguments that were not
convertible to tensor will also be static.
xla_forced_compile: if true, it will use XLA to force-compile the graph.
This requires that the function only contain ops that are XLA
compatible. It will compile the entire function into a single XLA op.
input_signature: a list of `tf.TensorSpec`, as the input signature to
control tracing behavior. See the
[doc](https://www.tensorflow.org/api_docs/python/tf/function]) of
`tf.function` for details.
autograph: whether to use autograph to convert Python constructs such as
`if` and `while` to their TensorFlow counterparts. See the
[doc](https://www.tensorflow.org/api_docs/python/tf/function]) of
`tf.function` for details.
experimental_compile: the `experimental_compile` flag for `tf.function`. See
the [doc](https://www.tensorflow.org/api_docs/python/tf/function]) of
`tf.function` for details. This is the recommended way to turn on XLA for
tf.function, but unlike xla_forced_compile, it doesn't force-compile the
entire function into a single XLA op.
Returns:
A trace-compiled version of f.
"""
@polymorphic_function.function(
input_signature=input_signature,
autograph=autograph,
experimental_compile=experimental_compile,
)
def _tf_f(*args, **kwargs):
"""Accelerated function with tensor inputs/outputs."""
np_args = _tf_to_np(args)
kwargs = {k: _tf_to_np(v) for k, v in kwargs.items()}
if xla_forced_compile:
# Use list for mutability
output_is_list = [False]
output_is_empty = [False]
output_structure = [None]
def recorder(args, kwargs, res):
del args, kwargs
# Workaround b/121383831
output_is_list[0] = isinstance(res, list)
# If outputs are empty, xla.compile returns an `Operation`, which we
# don't want.
if nest.flatten(res):
output_is_empty[0] = False
output_structure[0] = None
else:
output_is_empty[0] = True
# Without deepcopy, xla.compile will change output_structure[0] to a
# list of `Operation`.
output_structure[0] = copy.deepcopy(res)
return res
f_ = _record_result_type(recorder, f)
np_out = xla.compile(lambda: f_(*np_args, **kwargs))
# Workaround b/121383831
if output_is_empty[0]:
np_out = output_structure[0]
elif (isinstance(np_out, list) and len(np_out) == 1 and
not output_is_list[0]):
np_out = np_out[0]
else:
np_out = f(*np_args, **kwargs)
return np_out
def _f(*args, **kwargs):
args = [
_canonicalize_jit_arguments(arg) if i not in static_argnums else arg
for i, arg in enumerate(args)
]
kwargs = {k: _canonicalize_jit_arguments(v) for k, v in kwargs.items()}
tf_out = _tf_f(*args, **kwargs)
return _tf_to_np(tf_out)
_f.tf_function = _tf_f
return _f
def eval_on_shapes(f, static_argnums=(), allow_static_outputs=False):
"""Returns a function that evaluates `f` given input shapes and dtypes.
It transforms function `f` to a function that performs the same computation as
`f` but only on shapes and dtypes (a.k.a. shape inference).
Args:
f: the function to be transformed.
static_argnums: see documentation of `jit`.
allow_static_outputs: whether to allow non-array outputs. If True, non-array
outputs (e.g. Python integers) will be returned as-is; otherwise, they
will be converted to ndarrays, and then specs of those ndarrays will be
returned.
Returns:
A function whose input arguments can be either the same as `f`'s or only
their shapes/dtypes represented by `tf.TensorSpec`, and whose return values
are `tf.TensorSpec`s with the same nested structure as `f`'s return
values. If `allow_static_outputs` is True, when `f` returns some non-array
outputs (e.g. Python integers), the converted function will return them
as-is instead of returning `tf.TensorSpec`s for them.
"""
def abstractify(args):
def _abstractify(x):
x = _canonicalize_jit_arg(x)
if isinstance(x, (tensor_lib.Tensor, tf_np.ndarray)):
return tensor_lib.TensorSpec(x.shape, x.dtype)
else:
return x
new_args = []
for i, arg in enumerate(args):
if i in static_argnums:
new_args.append(arg)
else:
new_args.append(nest.map_structure(_abstractify, arg))
return new_args
if allow_static_outputs:
# When `tf_f` below is called (via get_concrete_function) with the same
# arugments (after abstraction), the Python function `f` won't be run, so we
# need this python_outputs_map to retrieve the Python outputs we've seen
# before that correspond the arguments.
python_outputs_map = {}
def recorder(args, kwargs, res):
# Since the get_concrete_function below only uses positional args, we also
# only positional args here.
del args, kwargs
def is_tensor_like(x):
if hasattr(x, "_type_spec"):
return True # x is a CompositeTensor
return isinstance(x, (tf_np.ndarray, tensor_lib.Tensor))
py_values = nest.map_structure(
lambda x: None if is_tensor_like(x) else x, res
)
key = id(ops.get_default_graph())
python_outputs_map[key] = py_values
# Set non-tensor outputs to None to avoid tf.function calling
# tf.convert_to_tensor on them.
res = nest.map_structure(
lambda x: None if not is_tensor_like(x) else x, res
)
return res
f = _record_result_type(recorder, f)
# TODO(wangpeng): tf.function could add a knob to turn off materializing the
# graph, so that we don't waste computation and memory when we just want
# shape inference.
tf_f = jit(f, static_argnums=static_argnums).tf_function
# pylint: disable=missing-docstring
def f_return(*args):
def to_tensor_spec(x):
if isinstance(x, tensor_lib.Tensor):
return tensor_lib.TensorSpec(x.shape, x.dtype)
else:
return x
new_args = abstractify(args)
cfun = tf_f.get_concrete_function(*new_args)
res = cfun.structured_outputs
res = nest.map_structure(to_tensor_spec, res)
if allow_static_outputs:
key = id(cfun.graph)
py_values = python_outputs_map[key]
# We can also call tf.get_static_value on structured_outputs to retrieve
# the Python values, but since we'll need to use python_outputs_map to
# record "which outputs are static?" anyway, we choose to directly store
# the Python values in python_outputs_map.
res = nest.map_structure(
lambda x, python_value: x if python_value is None else python_value,
res,
py_values,
)
return res
# Provides access to `tf_f` for testing purpose.
f_return._tf_function = tf_f # pylint: disable=protected-access
return f_return
def _index_update_helper(updater, x, idx, y):
x = tf_np.asarray(x)
y = tf_np.asarray(y)
# TODO(b/164251540): Remove this expensive manual broadcasting once
# tf.raw_ops.tensor_strided_slice_update and tf.tensor_scatter_nd_update
# support broadcasting.
y = array_ops.broadcast_to(y, array_ops.shape_v2(x[idx]))
return updater(x, idx, y)
# pylint: disable=protected-access
def index_update(x, idx, y):
"""Pure equivalent of `x[idx] = y`.
Returns the value of x that would result from the NumPy-style indexed
assignment `x[idx] = y`. Because it's a pure function, `x` itself won't be
changed.
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, integers, slice objects,
ellipses, ndarrays with integer dtypes, or a tuple of the above.
y: the array of updates. `y` must be broadcastable to the shape of the array
that would be returned by `x[idx]`.
Returns:
The updated version of `x`.
"""
return _index_update_helper(tf_np.ndarray._with_index_update, x, idx, y)
def index_add(x, idx, y):
"""Pure equivalent of `x[idx] += y`.
Returns the value of x that would result from the NumPy-style indexed
assignment `x[idx] += y`. Because it's a pure function, `x` itself won't be
changed.
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, integers, slice objects,
ellipses, ndarrays with integer dtypes, or a tuple of the above.
y: the array of updates. `y` must be broadcastable to the shape of the array
that would be returned by `x[idx]`.
Returns:
The updated version of `x`.
"""
return _index_update_helper(tf_np.ndarray._with_index_add, x, idx, y)
def index_min(x, idx, y):
"""Pure equivalent of `x[idx] = minimum(x[idx], y)`.
Returns the value of x that would result from the NumPy-style indexed
assignment `x[idx] = minimum(x[idx], y)`. Because it's a pure function, `x`
itself won't be changed.
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, integers, slice objects,
ellipses, ndarrays with integer dtypes, or a tuple of the above.
y: the array of updates. `y` must be broadcastable to the shape of the array
that would be returned by `x[idx]`.
Returns:
The updated version of `x`.
"""
return _index_update_helper(tf_np.ndarray._with_index_min, x, idx, y)
def index_max(x, idx, y):
"""Pure equivalent of `x[idx] = maximum(x[idx], y)`.
Returns the value of x that would result from the NumPy-style indexed
assignment `x[idx] = maximum(x[idx], y)`. Because it's a pure function, `x`
itself won't be changed.
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, integers, slice objects,
ellipses, ndarrays with integer dtypes, or a tuple of the above.
y: the array of updates. `y` must be broadcastable to the shape of the array
that would be returned by `x[idx]`.
Returns:
The updated version of `x`.
"""
return _index_update_helper(tf_np.ndarray._with_index_max, x, idx, y)
# pylint: enable=protected-access
def logsumexp(x, axis=None, keepdims=None):
"""Computes log(sum(exp(elements across dimensions of a tensor))).
Reduces `x` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
This function is more numerically stable than log(sum(exp(input))). It avoids
overflows caused by taking the exp of large inputs and underflows caused by
taking the log of small inputs.
Args:
x: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(x), rank(x))`.
keepdims: If true, retains reduced dimensions with length 1.
Returns:
The reduced tensor.
"""
return tf_np.asarray(
math_ops.reduce_logsumexp(input_tensor=x, axis=axis, keepdims=keepdims)
)
def expit(x):
"""Compute 1 / (1 + exp(-x))."""
return tf_np.asarray(math_ops.sigmoid(x))
def erf(x):
"""Computes the Gauss error function of x element-wise."""
return tf_np.asarray(math_ops.erf(x))
def _minus(a, b):
return [x for x in a if x not in b]
def _compose_output_rep(lhs_rep, rhs_rep, lhs_contraction, rhs_contraction,
lhs_batch, rhs_batch):
"""Compose the output string representation.
e.g., ij, jk, (((1,), (0,)), ((), ())) -> ik
aij, ajk, (((2,), (1,)), ((0,), (0,))) -> aik
Args:
lhs_rep: A string representation for the left-hand side input array
rhs_rep: A string representation for the right-hand side input array
lhs_contraction: Sequence[int] (the contraction dimensions of lhs)
rhs_contraction: Sequence[int] (the contraction dimensions of rhs)
lhs_batch: Sequence[int] (the batch dimensions of lhs)
rhs_batch: Sequence[int] (the batch dimensions of rhs)
Returns:
A string representation of the result array.
"""
output_rep = []
for dim in lhs_batch:
output_rep.append(lhs_rep[dim])
for i in _minus(range(len(lhs_rep)), lhs_batch + lhs_contraction):
output_rep.append(lhs_rep[i])
for i in _minus(range(len(rhs_rep)), rhs_batch + rhs_contraction):
output_rep.append(rhs_rep[i])
return "".join(output_rep)
def _non_batched_matmul(lhs, rhs, lhs_contraction, rhs_contraction):
"""Compute the non-batched matrix multiplication.
If it is the general non-batched/single-batched matrix multiplication,
use the highly optimized kernel `tf.tensordot` to handle it.
Args:
lhs: an array (the left-hand side matrix/vector to be multiplied)
rhs: an array (the right-hand side matrix/vector to be multiplied)
lhs_contraction: Sequence[int] (the contraction dimensions of lhs)
rhs_contraction: Sequence[int] (the contraction dimensions of rhs)
Returns:
An array that contains the result.
"""
return math_ops.tensordot(
lhs, rhs, axes=(list(lhs_contraction), list(rhs_contraction))
)
def tf_dot_general(lhs, rhs, dimension_numbers):
"""The general dot operation for TensorFlow.
An equivalent general dot operation as that in JAX -
<https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.dot_general.html>
Although there is an implementation in TF XLA, avoid directly using XLA when
possible.
e.g., non-batched: ij,jk->ik
batched: ijk,ikl->ijl
Args:
lhs: an array (the left-hand side matrix/vector to be multiplied)
rhs: an array (the right-hand side matrix/vector to be multiplied)
dimension_numbers: (Tuple[Tuple[Sequence[int], Sequence[int]],
Tuple[Sequence[int], Sequence[int]]]) – a tuple of tuples of the form
((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims,
rhs_batch_dims))
Returns:
An array that contains the result.
"""
char_list = list(string.ascii_lowercase)
char_list = char_list[8:] + char_list[:8]
lhs_rank, rhs_rank = len(lhs.shape), len(rhs.shape)
lhs_rep = char_list[:lhs_rank]
rhs_rep = char_list[lhs_rank:lhs_rank + rhs_rank]
contraction, batch = dimension_numbers
lhs_contraction, rhs_contraction = contraction
if len(lhs_contraction) != len(rhs_contraction):
raise ValueError(
"The input matrices are required to have the same number "
"of contraction dimensions, but got: lhs {}, rhs: {}".format(
len(lhs_contraction), len(rhs_contraction)))
lhs_batch, rhs_batch = batch
if len(lhs_batch) != len(rhs_batch):
raise ValueError("The input matrices are required to have the same number "
"of batch dimensions, but got: lhs {}, rhs: {}".format(
len(lhs_batch), len(rhs_batch)))
if not lhs_batch and not rhs_batch:
return _non_batched_matmul(lhs, rhs, lhs_contraction, rhs_contraction)
if (lhs_rank == rhs_rank == 3 and lhs_batch == (0,) and rhs_batch == (0,) and
lhs_contraction == (2,) and rhs_contraction == (1,)):
return math_ops.matmul(lhs, rhs)
for i in range(len(lhs_contraction)):
rhs_rep[rhs_contraction[i]] = lhs_rep[lhs_contraction[i]]
for i in range(len(lhs_batch)):
rhs_rep[rhs_batch[i]] = lhs_rep[lhs_batch[i]]
output_rep = _compose_output_rep(lhs_rep, rhs_rep, lhs_contraction,
rhs_contraction, lhs_batch, rhs_batch)
equation = "".join(lhs_rep) + "," + "".join(rhs_rep) + "->" + output_rep
return special_math_ops.einsum(equation, lhs, rhs)
def _conv_general_param_type_converter(window_strides, lhs_dilation,
rhs_dilation, dim):
"""Convert strides, lhs_dilation, rhs_dilation to match TF convention.
For example,
in the 3D case, if lhs_dilation = 2, then convert it to [2, 2, 2]
if lhs_dilation = (2, 2, 2), convert it also to [2, 2, 2]
Args:
window_strides: window_strides to be converted
lhs_dilation: lhs_dilation to be converted
rhs_dilation: rhs_dilation to be converted
dim: dim to be converted
Returns:
The updated window_strides, lhs_dilation and rhs_dilation
"""
def _as_list_of_size(item, size):
if item is None:
return None
return [item] * size if isinstance(item, int) else list(item)
return (_as_list_of_size(window_strides, dim),
_as_list_of_size(lhs_dilation, dim),
_as_list_of_size(rhs_dilation, dim))
# pylint: disable=g-bad-todo
# TODO(DarrenZhang01): Expand the test cases of general convolution and revise
# the according bugs.
# TODO(DarrenZhang01): Support feature_group_count, batch_group_count and
# precision, and allow lhs_dilation and rhs_dilation to happen at the same time.
# pylint: enable=g-bad-todo
def tf_conv_general_dilated(lhs, rhs, window_strides, padding, output_shape,
lhs_dilation=None, rhs_dilation=None,
dimension_numbers=None, feature_group_count=1,
batch_group_count=1, precision=None):
"""A general conv API for TensorFlow.
According JAX version:
https://jax.readthedocs.io/en/stable/_autosummary/jax.lax.conv_general_dilated.html
Args:
lhs: a rank n+2 dimensional input array.
rhs: a rank n+2 dimensional array of kernel weights.
window_strides: a sequence of n integers, representing the inter-window
strides.
padding: either the string ‘SAME’, the string ‘VALID’, or a sequence of n
(low, high) integer pairs that give the padding to apply before and
after each spatial dimension.
output_shape: the output shape of the convolution (only required for
transpose convolution).
lhs_dilation: None, or a sequence of n integers, giving the dilation factor
to apply in each spatial dimension of lhs. LHS dilation is
also known as transposed convolution.
rhs_dilation: None, or a sequence of n integers, giving the dilation factor
to apply in each spatial dimension of rhs. RHS dilation is
also known as atrous convolution.
dimension_numbers: either None, a ConvDimensionNumbers object, or a 3-tuple
(lhs_spec, rhs_spec, out_spec), where each element is a
string of length n+2.
feature_group_count: integer, default 1. Changing this is currently not
supported.
batch_group_count: integer, default 1. Changing this is currently not
supported.
precision: Optional. Either None, which means the default precision for the
backend, or a Precision enum value.
Returns:
A TF NumPy array that contains the convolution result.
"""
dim = None
lhs_spec, rhs_spec, out_spec = dimension_numbers
if lhs_spec != out_spec:
raise ValueError("Current implementation requires the `data_format` of the "
"inputs and outputs to be the same.")
if len(lhs_spec) >= 6:
raise ValueError("Current implmentation does not support 4 or higher"
"dimensional convolution, but got: ", len(lhs_spec) - 2)
dim = len(lhs_spec) - 2
if lhs_dilation and rhs_dilation:
if lhs_dilation == (1,) * dim and rhs_dilation == (1,) * dim:
lhs_dilation, rhs_dilation = None, None
else:
raise ValueError("Current implementation does not support that "
"deconvolution and dilation to be performed at the same "
"time, but got lhs_dilation: {}, rhs_dilation: {}"
.format(lhs_dilation, rhs_dilation))
if padding not in ["SAME", "VALID"]:
raise ValueError("Current implementation requires the padding parameter"
"to be either 'VALID' or 'SAME', but got: ", padding)
if batch_group_count != 1 or feature_group_count != 1:
raise NotImplementedError("batch_group_count and feature_group_count "
"other than 1 is currently not supported, but"
" got feature_group_count: {}, batch_group_count"
": {}".format(feature_group_count,
batch_group_count))
if precision is not None:
raise NotImplementedError("precision other than `None` is currently not "
"supported, but got: {}".format(precision))
# Convert params from int/Sequence[int] to list of ints.
strides, lhs_dilation, rhs_dilation = _conv_general_param_type_converter(
window_strides, lhs_dilation, rhs_dilation, dim
)
# Preprocess the shapes
dim_maps = {}
if isinstance(lhs_spec, str):
dim_maps["I"] = list(rhs_spec).index("I")
dim_maps["O"] = list(rhs_spec).index("O")
dim_maps["N"] = list(lhs_spec).index("N")
dim_maps["C"] = list(lhs_spec).index("C")
else:
dim_maps["I"] = rhs_spec[1]
dim_maps["O"] = rhs_spec[0]
dim_maps["N"] = lhs_spec[0]
dim_maps["C"] = lhs_spec[1]
lhs = tf_np.moveaxis(lhs, (dim_maps["N"], dim_maps["C"]), (0, dim + 1))
# Adjust the filters, put the dimension 'I' and 'O' at last.
rhs = tf_np.moveaxis(rhs, (dim_maps["O"], dim_maps["I"]), (dim + 1, dim))
spatial_dim_maps = {1: "W", 2: "HW", 3: "DHW"}
data_format = "N" + spatial_dim_maps[dim] + "C"
if rhs_dilation or (lhs_dilation is None and rhs_dilation is None):
output = _tf_nn_APIs[dim][0](lhs, rhs, strides, padding, data_format,
rhs_dilation)
else:
output = _tf_nn_APIs[dim][1](
lhs,
rhs,
constant_op.constant(output_shape),
strides,
padding,
data_format,
lhs_dilation,
)
output = tf_np.moveaxis(output, (0, dim + 1), (dim_maps["N"], dim_maps["C"]))
return output
def conv(inp,
fltr,
window_strides,
padding,
dimension_numbers,
filter_dilation=None):
"""Convolution over an N-D array.
See https://www.tensorflow.org/api_docs/python/tf/nn/convolution and
https://www.tensorflow.org/xla/operation_semantics#conv_convolution for
reference.
Args:
inp: an (N+2)-D array. The input of the convolution.
fltr: an (N+2)-D array. The filter (i.e. kernel) of the convolution.
window_strides: a sequence of N ints, the strides for moving the convolution
window.
padding: a string, either "VALID" or "SAME". The padding algorithm.
dimension_numbers: a tuple of three strings encoding the data format of
input, filter and output. "I" means input; "O" means output; "C" means
channel; other characters such as "W", "H" and "D" means spatial
dimensions.
filter_dilation: the dilation rates for the filter. Dilating the filter
means adding "holes" to the filter.
Returns:
An (N+2)-D array. The convolution result.
"""
input_spec, filter_spec, output_spec = dimension_numbers
if input_spec != output_spec:
raise ValueError("Input and output data formats must be the same; got %s "
"and %s" % (input_spec, output_spec))
supported_filter_spec = ["WIO", "HWIO", "DHWIO"]
if filter_spec not in supported_filter_spec:
raise ValueError("The supported data format for the filter are %s; got %s" %
(supported_filter_spec, filter_spec))
if input_spec[1:-1] != filter_spec[:-2]:
raise ValueError("Input data format (%s) is not compatible with filter "
"data format (%s)" % (input_spec, filter_spec))
# No type promotion in order to prevent accidentally doing more expensive
# computation.
dtype = tf_np.result_type(inp, fltr)
inp = tf_np.asarray(inp, dtype)
fltr = tf_np.asarray(fltr, dtype)
return tf_np.asarray(
nn_ops.convolution_v2(
input=inp,
filters=fltr,
padding=padding,
strides=window_strides,
dilations=filter_dilation,
data_format=input_spec,
)
)
def avg_pool(x, pool_size, strides, padding):
"""Performs an N-D average pooling.
Args:
x: ndarray of rank N+2, of shape `[batch_size] + input_spatial_shape +
[num_channels]`. Pooling happens over the spatial dimensions only.
pool_size: sequence of N ints.
strides: sequence of N ints.
padding: a string, the padding algorithm. Must be "SAME" or "VALID".
Returns:
An (N+2)-D array, of shape
[batch_size] + output_spatial_shape + [num_channels],
where `output_spatial_shape` depends on the value of padding:
If padding = "SAME":
output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])
If padding = "VALID":
output_spatial_shape[i] =
ceil((input_spatial_shape[i] - (pool_size[i] - 1)) / strides[i]).
"""
x = tf_np.asarray(x)
return tf_np.asarray(
nn_ops.pool(
input=x,
window_shape=pool_size,
pooling_type="AVG",
strides=strides,
padding=padding,
)
)
def max_pool(x, pool_size, strides, padding):
"""Performs an N-D max pooling.
Args:
x: ndarray of rank N+2, of shape `[batch_size] + input_spatial_shape +
[num_channels]`. Pooling happens over the spatial dimensions only.
pool_size: sequence of N ints.
strides: sequence of N ints.
padding: a string, the padding algorithm. Must be "SAME" or "VALID".
Returns:
An (N+2)-D array, of shape
[batch_size] + output_spatial_shape + [num_channels],
where `output_spatial_shape` depends on the value of padding:
If padding = "SAME":
output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])
If padding = "VALID":
output_spatial_shape[i] =
ceil((input_spatial_shape[i] - (pool_size[i] - 1)) / strides[i]).
"""
x = tf_np.asarray(x)
return tf_np.asarray(
nn_ops.pool(
input=x,
window_shape=pool_size,
pooling_type="MAX",
strides=strides,
padding=padding,
)
)
def sort_key_val(keys, values, dimension=-1):
"""Sorts keys along a dimension and applies same permutation to values.
Args:
keys: an array. The dtype must be comparable numbers (integers and reals).
values: an array, with the same shape of `keys`.
dimension: an `int`. The dimension along which to sort.
Returns:
Permuted keys and values.
"""
keys = tf_np.asarray(keys)
values = tf_np.asarray(values)
rank = keys.shape.ndims
if rank is None:
rank = values.shape.ndims
if rank is None:
# We need to know the rank because tf.gather requires batch_dims to be `int`
raise ValueError("The rank of either keys or values must be known, but "
"both are unknown (i.e. their shapes are both None).")
if dimension in (-1, rank - 1):
def maybe_swapaxes(a):
return a
else:
def maybe_swapaxes(a):
return tf_np.swapaxes(a, dimension, -1)
# We need to swap axes because tf.gather (and tf.gather_nd) supports
# batch_dims on the left but not on the right.
# TODO(wangpeng): Investigate whether we should do swapaxes or moveaxis.
keys = maybe_swapaxes(keys)
values = maybe_swapaxes(values)
idxs = tf_np.argsort(keys)
# Using tf.gather rather than np.take because the former supports batch_dims
def gather(a):
return tf_np.asarray(array_ops.gather_v2(a, idxs, batch_dims=rank - 1))
keys = gather(keys)
values = gather(values)
keys = maybe_swapaxes(keys)
values = maybe_swapaxes(values)
return keys, values
def scan(f, init, xs, length=None, reverse=False):
"""Scan a function over leading array axes while carrying along state.
See the docstring of `jax.lax.scan`
(https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.scan.html) for
details.
Args:
f: a Python function to be scanned of type ``c -> a -> (c, b)``, meaning
that ``f`` accepts two arguments where the first is a value of the loop
carry and the second is a slice of ``xs`` along its leading axis, and that
``f`` returns a pair where the first element represents a new value for
the loop carry and the second represents a slice of the output. Note that
the input and output carry must have the same dtype.
init: an initial loop carry value of type ``c``, which can be a scalar,
array, or any pytree (nested Python tuple/list/dict) thereof, representing
the initial loop carry value. This value must have the same structure as
the first element of the pair returned by ``f``.
xs: the value of type ``[a]`` over which to scan along the leading axis,
where ``[a]`` can be an array or any pytree (nested Python
tuple/list/dict) thereof with consistent leading axis sizes.
length: optional integer specifying the number of loop iterations, which
must agree with the sizes of leading axes of the arrays in ``xs`` (but can
be used to perform scans where no input ``xs`` are needed).
reverse: optional boolean specifying whether to run the scan iteration
forward (the default) or in reverse, equivalent to reversing the leading
axes of the arrays in both ``xs`` and in ``ys``.
Returns:
A pair of type ``(c, [b])`` where the first element represents the final
loop carry value and the second element represents the stacked outputs of
the second output of ``f`` when scanned over the leading axis of the inputs.
"""
init, xs = nest.map_structure(
lambda x: tf_np.asarray(x) if x is not None else None, (init, xs)
)
if length is not None:
length = int(length)
def get_length(x):
if x is None:
return None
if x.shape.rank == 0:
raise ValueError("Some array in `xs` doesn't have a leading dimension")
return x.shape[0]
lengths = nest.flatten(nest.map_structure(get_length, xs))
for l in lengths:
if l is not None:
if length is None:
length = l
elif length != l:
raise ValueError("There are two different leading-dimension lengths: "
f"{length} and {l}")
if length is None:
raise ValueError(
"Can't determine length. Please set the `length` argument.")
xs_ta = nest.map_structure(
lambda t: ( # pylint: disable=g-long-lambda
tensor_array_ops.TensorArray( # pylint: disable=g-long-ternary
t.dtype, size=length, dynamic_size=False
).unstack( # pylint: disable=g-long-lambda
t
)
if t is not None
else None
),
xs,
)
# tf.while_loop doesn't allow None in loop_vars, so we mask them.
is_init_none = nest.map_structure(lambda x: x is None, init)
def to_safe(carry):
return nest.map_structure(
lambda x, is_none: array_ops.zeros([]) if is_none else x,
carry,
is_init_none,
)
def from_safe(safe_carry):
return nest.map_structure(
lambda x, is_none: None if is_none else x, safe_carry, is_init_none
)
def body(i, safe_carry, ys_ta):
carry = from_safe(safe_carry)
if reverse:
i_ = length - 1 - i
else:
i_ = i
xs = nest.map_structure(
lambda x_ta: x_ta.read(i_) if x_ta is not None else None, xs_ta
)
carry, ys = f(*_tf_to_np((carry, xs)))
ys_ta = nest.map_structure(
lambda y_ta, y: (y_ta.write(i_, y) if y is not None else y_ta),
ys_ta,
ys,
)
i = i + 1
safe_carry = to_safe(carry)
return i, safe_carry, ys_ta
xs_spec = nest.map_structure(
lambda t: tensor_lib.TensorSpec(t.shape[1:], t.dtype) # pylint: disable=g-long-lambda
if t is not None
else None,
xs,
)
_, ys_spec = eval_on_shapes(f)(init, xs_spec)
# ys_ta can't contain None because tf.while_loop doesn't allow None in
# loop_vars.
ys_ta = nest.map_structure(
lambda y: tensor_array_ops.TensorArray( # pylint: disable=g-long-lambda
y.dtype if y is not None else dtypes.float32,
size=length,
dynamic_size=False,
),
ys_spec,
)
safe_init = to_safe(init)
_, safe_carry, ys_ta = while_loop.while_loop_v2(
lambda i, *_: i < length,
body,
(0, safe_init, ys_ta),
maximum_iterations=length,
)
carry = from_safe(safe_carry)
def _stack(a, spec):
if spec is None:
return None
a = a.stack()
a.set_shape((length,) + a.shape[1:])
return a
ys = nest.map_structure(_stack, ys_ta, ys_spec)
return _tf_to_np((carry, ys))
# named "tf_map" instead of "map" as in JAX to avoid conflict with Python `map`
def tf_map(f, xs):
"""Map a function over leading array axes.
See the docstring of `jax.lax.map`
(https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.map.html) for
details.
Args:
f: a Python function to apply element-wise over the first axis or axes of
`xs`.
xs: values over which to map along the leading axis.
Returns:
Mapped values.
"""
def g(unused, x):
return unused, f(x)
carry = nest.map_structure(lambda _: None, xs)
return scan(g, carry, xs)[1]
def _get_dynamic_indices(operand, start_indices, slice_sizes):
"""Calcuates the indices for `tf.gather_nd` from slices.
Args:
operand: a Tensor to slice.
start_indices: a vector Tensor of integers, one per dimension. The starts of
the slice. The vector can be dynamic.
slice_sizes: a list of integers, one per dimension. The sizes of the slice.
Returns:
An index array suitable for `tf.gather_nd` and `tf.scatter_nd`, or `None` if
`operand` is a scalar.
"""
rank = len(slice_sizes)
operand_rank = array_ops.rank(operand)
control_flow_assert.Assert(operand_rank == rank, [operand_rank, rank])
starts_rank = array_ops.rank(start_indices)
control_flow_assert.Assert(starts_rank == 1, [starts_rank])
num_starts = array_ops.shape_v2(start_indices)[0]
control_flow_assert.Assert(num_starts == rank, [num_starts, rank])
operand_shape = array_ops.shape_v2(operand)
control_flow_assert.Assert(
math_ops.reduce_all(slice_sizes <= operand_shape),
[slice_sizes, operand_shape],
)
if rank == 0:
return None
start_indices = array_ops.where(
start_indices < 0, start_indices + operand_shape, start_indices
)
idx_list = []
for i in range(rank):
start = start_indices[i]
size = slice_sizes[i]
dim = operand_shape[i]
start = clip_ops.clip_by_value(start, 0, dim - size)
# XLA requires tf.range's `start` to be compile-time constant, so we can't
# do tf.range(start, ...).
idx = start + math_ops.range(size)
shape = [1] * rank
shape[i] = size
idx = array_ops.reshape(idx, shape)
idx_list.append(idx)
slice_sizes_tensor = ops.convert_to_tensor(slice_sizes)
# tf.stack doesn't support broadcasting, so we need to broadcast manually.
# TODO(wangpeng): Reduce peak memory by broadcasting one-by-one instead of
# all-together.
idx_list = [array_ops.broadcast_to(x, slice_sizes_tensor) for x in idx_list]
return array_ops_stack.stack(idx_list, axis=-1)
def dynamic_slice(operand, start_indices, slice_sizes):
"""Slicing operation where the indices can be dynamic vlaues.
See the docstring of `jax.lax.dynamic_slice`
(https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.dynamic_slice.html)
for details.
Args:
operand: an array to slice.
start_indices: a vector of integers, one per dimension. The starts of the
slice. The vector can be dynamic.
slice_sizes: a list of integers, one per dimension. The sizes of the slice.
Returns:
An array containing the slice, with shape equal to `slice_sizes`.
"""
# This implementation uses tf.gather_nd to implement dynamic_slice, which is
# memory inefficient because the size of `indices` given to gather_nd is
# large.
operand = tf_np.asarray(operand).data
start_indices = tf_np.asarray(start_indices, np.int32).data
idx = _get_dynamic_indices(operand, start_indices, slice_sizes)
if idx is not None:
operand = array_ops.gather_nd(operand, idx)
return tf_np.asarray(operand)
def dynamic_update_slice(operand, update, start_indices):
"""Updates a dynamic slice.
See the docstring of `jax.lax.dynamic_update_slice`
(https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.dynamic_update_slice.html)
for details.
Args:
operand: an array to slice.
update: an array containing the new values to write onto `operand`.
start_indices: a vector of integers, one per dimension. The starts of the
slice. The vector can be dynamic.
Returns:
The updated version of `operand`.
"""
operand = tf_np.asarray(operand).data
update = tf_np.asarray(update).data
start_indices = tf_np.asarray(start_indices, np.int32).data
if not update.shape.is_fully_defined():
raise ValueError("update's shape must be fully defined")
slice_sizes = update.shape
idx = _get_dynamic_indices(operand, start_indices, slice_sizes)
if idx is None:
# `np.zeros([])[()] = 1.0` will result in a scalar array of 1.0
return tf_np.asarray(update)
operand = array_ops.tensor_scatter_nd_update(operand, idx, update)
return tf_np.asarray(operand)
def dynamic_slice_in_dim(operand, start_index, slice_size, axis=0):
"""Convenience wrapper around dynamic_slice applying to one dimension."""
operand = tf_np.asarray(operand)
start_indices = [0] * operand.ndim
slice_sizes = list(operand.shape)
axis = int(axis)
start_indices[axis] = start_index
slice_sizes[axis] = int(slice_size)
return dynamic_slice(operand, start_indices, slice_sizes)
def dynamic_update_slice_in_dim(operand, update, start_index, axis):
"""Convenience wrapper around dynamic_update_slice for one dimension."""
operand = tf_np.asarray(operand)
axis = int(axis)
start_indices = [0] * operand.ndim
start_indices[axis] = start_index
return dynamic_update_slice(operand, update, start_indices)
# Use int64 instead of int32 to avoid TF's "int32 problem"
_RNG_KEY_DTYPE = np.int64
def _key2seed(a):
"""Converts an RNG key to an RNG seed.
Args:
a: an RNG key, an ndarray of shape [] and dtype `np.int64`.
Returns:
an RNG seed, a tensor of shape [2] and dtype `tf.int32`.
"""
def int64_to_int32s(a):
"""Converts an int64 tensor of shape [] to an int32 tensor of shape [2]."""
a = math_ops.cast(a, dtypes.uint64)
fst = math_ops.cast(a, dtypes.uint32)
snd = math_ops.cast(
gen_bitwise_ops.right_shift(a, constant_op.constant(32, dtypes.uint64)),
dtypes.uint32,
)
a = [fst, snd]
a = nest.map_structure(lambda x: math_ops.cast(x, dtypes.int32), a)
a = array_ops_stack.stack(a)
return a
return int64_to_int32s(a)
def _seed2key(a):
"""Converts an RNG seed to an RNG key.
Args:
a: an RNG seed, a tensor of shape [2] and dtype `tf.int32`.
Returns:
an RNG key, an ndarray of shape [] and dtype `np.int64`.
"""
def int32s_to_int64(a):
"""Converts an int32 tensor of shape [2] to an int64 tensor of shape []."""
a = math_ops.bitwise_or(
math_ops.cast(a[0], dtypes.uint64),
math_ops.left_shift(
math_ops.cast(a[1], dtypes.uint64),
constant_op.constant(32, dtypes.uint64),
),
)
a = math_ops.cast(a, dtypes.int64)
return a
return tf_np.asarray(int32s_to_int64(a))
def prng(s):
"""Creates RNG state from seed.
Args:
s: the seed, an integer.
Returns:
An RNG state, as a scalar array of dtype `np.int64`.
"""
# TODO(wangpeng): Become bitwise-identical to JAX when TF stateless RNGs get
# improved.
return tf_np.asarray(s, dtype=_RNG_KEY_DTYPE)
def stateless_split(seed, num=2):
"""Splits an RNG seed into `num` new seeds by adding a leading axis.
Example:
>>> seed = [1, 2]
>>> new_seeds = tf.random.experimental.stateless_split(seed, num=3)
>>> print(new_seeds)
tf.Tensor(
[[1105988140 1738052849]
[-335576002 370444179]
[ 10670227 -246211131]], shape=(3, 2), dtype=int32)
>>> tf.random.stateless_normal(shape=[3], seed=new_seeds[0, :])
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([-0.59835213, -0.9578608 ,
0.9002807 ], dtype=float32)>
Args:
seed: an RNG seed (a tensor with shape [2] and dtype `int32` or `int64`).
(When using XLA, only `int32` is allowed.)
num: optional, a positive integer or scalar tensor indicating the number of
seeds to produce (default 2).
Returns:
A tensor with shape [num, 2] representing `num` new seeds. It will have the
same dtype as `seed` (if `seed` doesn't have an explict dtype, the dtype
will be determined by `tf.convert_to_tensor`).
"""
seed = ops.convert_to_tensor(seed)
return stateless_random_ops.stateless_random_uniform(
shape=[num, 2], seed=seed, dtype=seed.dtype, minval=None, maxval=None
)
def split(state, num):
"""Creates new independent RNG states from an existing state.
Args:
state: the existing state.
num: the number of the new states.
Returns:
A tuple of new states.
"""
state = tf_np.asarray(state, dtype=_RNG_KEY_DTYPE)
state = _key2seed(state)
try:
states = stateless_random_ops.stateless_split(state, num)
except AttributeError as e: # pylint: disable=unused-variable
# TODO(afrozm): For TF < 2.3 we need to do this. Delete once 2.3 launches.
states = stateless_split(state, num)
states = array_ops_stack.unstack(states, num)
states = nest.map_structure(_seed2key, states)
return states
def uniform(key,
shape,
dtype=tf_np.random.DEFAULT_RANDN_DTYPE,
minval=0.,
maxval=1.):
"""Sample uniform random values in range [`minval`, `maxval`).
Args:
key: the RNG key.
shape: the shape of the result.
dtype: the dtype of the result.
minval: the minimal value (inclusive).
maxval: the maximal value (exclusive).
Returns:
An ndarray with shape `shape` and dtype `dtype`. Each value in the ndarray
is sampled uniformly randomly in range [`minval`, `maxval`).
"""
minval = math_ops.cast(minval, dtype)
maxval = math_ops.cast(maxval, dtype)
key = tf_np.asarray(key, dtype=_RNG_KEY_DTYPE)
return tf_np.asarray(
stateless_random_ops.stateless_random_uniform(
shape, seed=_key2seed(key), dtype=dtype, minval=minval, maxval=maxval
)
)
def normal(key, shape, dtype=dtypes.float32):
"""Sample standard-normal random values.
Args:
key: the RNG key.
shape: the shape of the result.
dtype: the dtype of the result.
Returns:
Random values in standard-normal distribution.
"""
key = tf_np.asarray(key, dtype=_RNG_KEY_DTYPE)
return tf_np.asarray(
stateless_random_ops.stateless_random_normal(
shape, seed=_key2seed(key), dtype=dtype
)
)
def bernoulli(key, mean=np.float32(0.5), shape=None):
"""Sample Bernoulli random values with given shape and mean.
Args:
key: the RNG key.
mean: optional, an array_like broadcastable to `shape` for the mean of the
random variables (default 0.5).
shape: optional, a tuple of nonnegative integers representing the shape
(default to `mean`'s shape).
Returns:
A random array with the specified shape and boolean dtype.
"""
mean = tf_np.asarray(mean)
if shape is None:
shape = mean.shape
return uniform(key, shape) < mean
def _eager_dataset_iterator(dataset):
for item in dataset:
yield nest.map_structure(tf_np.asarray, item)
def dataset_as_numpy(dataset):
"""Converts a `tf.data.Dataset` to an iterable of ndarrays.
`dataset_as_numpy` converts a possibly nested structure of `tf.data.Dataset`s
and `tf.Tensor`s to iterables of ndarrays and ndarrays, respectively. This
function must be run in eager mode outside tf.function.
Args:
dataset: a possibly nested structure of `tf.data.Dataset`s and/or
`tf.Tensor`s.
Returns:
A structure matching `dataset` where `tf.data.Dataset`s are converted to
generators of ndarrays and `tf.Tensor`s are converted to ndarrays.
"""
if not context.executing_eagerly():
raise ValueError(
"dataset_as_numpy must be run in eager mode outside tf.function")
nested_ds = dataset
del dataset
# Flatten
flat_ds = nest.flatten(nested_ds)
flat_np = []
# Type check for Tensors and Datasets
for ds_el in flat_ds:
if not isinstance(ds_el, (tensor_lib.Tensor, dataset_ops.DatasetV2)):
types = nest.map_structure(type, nested_ds)
raise ValueError("Arguments to dataset_as_numpy must be (possibly nested "
"structure of) tf.Tensors or tf.data.Datasets. Got: %s" %
types)
for ds_el in flat_ds:
if isinstance(ds_el, tensor_lib.Tensor):
np_el = tf_np.asarray(ds_el)
elif isinstance(ds_el, dataset_ops.DatasetV2):
np_el = _eager_dataset_iterator(ds_el)
else:
assert False
flat_np.append(np_el)
return nest.pack_sequence_as(nested_ds, flat_np)
# TODO(nareshmodi): Group key should change based on the set of devices that we
# are mapping over. Make it so that we assign a unique group_key for every
# unique set of devices. We don't change it every time to avoid the overhead of
# discovering the full group (though may not be problematic in the local case).
_GROUP_KEY = 1
_INSTANCE_KEY = 0
_INSTANCE_LOCK = threading.Lock()
# TODO(b/142565636): Ensure that multiple concurrent calls to a tf.function
# containing a collective op run reasonably.
def _get_instance_key():
global _INSTANCE_KEY
global _INSTANCE_LOCK
with _INSTANCE_LOCK:
_INSTANCE_KEY = _INSTANCE_KEY + 1
return _INSTANCE_KEY
# Don't use a namedtuple since nest considers that a tuple and unflattens and
# flattens it.
class ShardedNdArray(object):
"""Wrapper over ndarray that can contain tensors on multiple devices.
This is returned by extensions.pmap, and contains the individual tensors on
different devices.
"""
def __init__(self, tensors):
"""Initializes the ShardedNdArray.
Note that the tensors should be ordered in the way the pmap producing these
tensors is run.
Args:
tensors: list or tuple of eager tensors, one for each device.
"""
if not isinstance(tensors, (list, tuple)) or not tensors:
raise ValueError(
"Unable to create a ShardedNdArray without a list of tensors.")
self.tensors = tensors
self.n_devices = len(tensors)
def __getitem__(self, i):
return tf_np.asarray(self.tensors[i])
@property
def shape(self):
return (self.n_devices,) + self.tensors[0]._shape_tuple() # pylint: disable=protected-access
@property
def dtype(self):
return self.tensors[0].dtype
def convert_sharded_tensor_to_eager_tensor(value, *args, **kwargs):
del args, kwargs
# TODO(nareshmodi): Consider a collective op to gather the tensors from the
# various devices for performance reasons.
return array_ops_stack.stack(value.tensors)
tensor_conversion_registry.register_tensor_conversion_function(
ShardedNdArray, convert_sharded_tensor_to_eager_tensor
)
class _PmapConfig(threading.local):
"""Simple config used to maintain state related to a current pmap call."""
def __init__(self):
super(_PmapConfig, self).__init__()
self._axis_name = None
self._devices = None
def axis_name(self):
return self._axis_name
def set_axis_name(self, axis_name):
self._axis_name = axis_name
def devices(self):
return self._devices
def set_devices(self, devices):
self._devices = devices
_pmap_config = _PmapConfig()
@contextlib.contextmanager
def pmap_config(axis_name, devices):
"""Records axis_name and devices for this context."""
old_axis_name = _pmap_config.axis_name()
old_devices = _pmap_config.devices()
_pmap_config.set_axis_name(axis_name)
_pmap_config.set_devices(devices)
try:
yield
finally:
_pmap_config.set_axis_name(old_axis_name)
_pmap_config.set_devices(old_devices)
def _psum(tensor, axis_name=None):
"""Sum all-reduction.
Args:
tensor: A tensor.
axis_name: The axis name to reduce. Must equal to that of the surrounding
pmap.
Returns:
The sum of the `tensor` replicas on each participating devices.
"""
if axis_name != _pmap_config.axis_name():
raise ValueError("axis_name (%s) is not equal to that of the surrounding "
"pmap (%s)" % (axis_name, _pmap_config.axis_name()))
devices = _pmap_config.devices()
if devices is None:
raise ValueError("Can't retrieve the device list from the surrounding pmap")
tensor = tf_np.asarray(tensor)
if tpu_devices(devices):
# TODO(b/170895907): Remove this workaround when tpu.cross_replica_sum
# supports int64/float64.
is_int64 = False
is_float64 = False
if tensor.dtype == np.int64:
is_int64 = True
tensor = tensor.astype(np.int32)
elif tensor.dtype == np.float64:
is_float64 = True
tensor = tensor.astype(np.float32)
# TODO(wangpeng): Supply the `group_assignment` argument to
# tpu.cross_replica_sum, calculated from `devices`.
tensor = tpu_ops.cross_replica_sum(tensor)
if is_int64:
tensor = math_ops.cast(tensor, dtypes.int64)
elif is_float64:
tensor = math_ops.cast(tensor, dtypes.float64)
else:
tensor = gen_collective_ops.collective_reduce(
input=tensor,
group_size=len(devices),
group_key=_GROUP_KEY,
instance_key=_get_instance_key(),
merge_op="Add",
final_op="Id",
subdiv_offsets=(0,),
)
return tf_np.asarray(tensor)
def psum(tensors, axis_name=None):
return nest.map_structure(
functools.partial(_psum, axis_name=axis_name), tensors
)
# Note this is not available in the jax api, but seemed like a reasonable API
# to have.
def pmean(tensor, axis_name=None):
"""Mean all-reduction.
Args:
tensor: A tensor.
axis_name: The axis name to reduce. Must equal to that of the surrounding
pmap.
Returns:
The mean of the `tensor` replicas on each participating devices.
"""
if axis_name != _pmap_config.axis_name():
raise ValueError("axis_name (%s) is not equal to that of the surrounding "
"pmap (%s)" % (axis_name, _pmap_config.axis_name()))
devices = _pmap_config.devices()
if devices is None:
raise ValueError("Can't retrieve the device list from the surrounding pmap")
if tpu_devices(devices):
# TODO(wangpeng): Implement this.
raise ValueError("pmean for TPU is not supported yet.")
else:
return gen_collective_ops.collective_reduce(
input=tensor,
group_size=len(devices),
group_key=_GROUP_KEY,
instance_key=_get_instance_key(),
merge_op="Add",
final_op="Div",
subdiv_offsets=(0,),
)
def _get_pmap_impl(f, devices, has_tpu):
"""This is a helper function to return the pmap impl.
Args:
f: a function that takes ndarrays and returns ndarrays.
devices: a list of strings; the device list.
has_tpu: boolean; whether `devices` contains TPU devices.
Returns:
A function that takes tensors and returns tensors.
"""
if has_tpu:
# Workaround b/121383831
output_is_list = [False] # Use list for mutability
def recorder(args, kwargs, res):
del args, kwargs
output_is_list[0] = isinstance(res, list)
return res
f = _record_result_type(recorder, f)
def tf_f(*tf_args):
"""A wrapper for `f` that takes/returns tensors."""
np_args = _tf_to_np(tf_args)
np_out = f(*np_args)
return np_out
if has_tpu:
@polymorphic_function.function(autograph=False)
def fn(inputs):
# TODO(wangpeng): Supply the `device_assignment` argument to
# tpu.replicate, calculated from `devices`.
res = tpu.replicate(tf_f, inputs)
# Workaround b/121383831
if (res and isinstance(res[0], list) and len(res[0]) == 1 and
not output_is_list[0]):
res = [x[0] for x in res]
return res
return fn
else:
# This is run in a tf.function so that the various underlying functions can
# be run in parallel.
# The trace happens on the client, so any devices should not depend on any
# side effects.
jit_tf_f = polymorphic_function.function(tf_f, autograph=False)
@polymorphic_function.function(autograph=False)
def fn(all_per_device_args):
"""Multi-device function with calls placed on the correct device."""
results = []
for per_device_args, device in zip(all_per_device_args, devices):
with ops.device(device):
results.append(jit_tf_f(*per_device_args))
return results
return fn
def pmap(f, axis_name=None, devices=None):
"""Transforms a function into a multi-device function.
The semantics are similar to JAX's pmap.
Args:
f: The function to be converted.
axis_name: Used for nested pmap, which is not supported yet.
devices: The devices over which the returned function will run.
Returns:
A function that runs the underlying function `f` on `devices`. Its arguments
can be `ShardedNdArray`s, tensors or other Python objects, and its return
values are all `ShardedNdArray`s. If an input is a tensor, the length of its
first dimension must equal the number of devices, and the tensor will be
splitted along its first dimension among the devices. If an input is an
unknown Python object, it will be replicated among the devices.
"""
if devices is None:
devices = accelerators()
if not isinstance(devices, (list, tuple)):
raise ValueError("Must pass a list or tuple of devices")
num_devices = len(devices)
if not num_devices:
raise ValueError("There must be at least 1 device")
has_tpu = bool(tpu_devices(devices))
pmap_fn = _get_pmap_impl(f, devices, has_tpu)
def wrapper(*args):
"""Wrapper that wraps/unwraps args, retvals, and runs the function."""
if _pmap_config.devices() is not None:
raise ValueError("Found a surrounding pmap. Nested pmap is not supported "
"yet.")
# TODO(wangpeng): Maybe we should use `asarray` to convert everything
# to ndarray first.
flattened_input_args = nest.flatten(args)
flattened_per_device_args = [[] for _ in devices]
for arg in flattened_input_args:
if isinstance(arg, tensor_lib.Tensor):
# TODO(nareshmodi): Try and use the dynamic shape instead.
if (not arg.shape.rank) or arg.shape[0] != len(devices):
# TODO(nareshmodi): Fix this restriction
raise ValueError(
"Input tensors need to have a first dimension equal to "
"the number of devices; got tensor of shape %s and %s devices" %
(arg.shape, len(devices)))
# NOTE: Alternatively use tf.split, and place the split tensors on the
# appropriate device. The best solution for this is to have an API that
# splits a tensor across devices.
for j, device in enumerate(devices):
updated_arg = array_ops.gather_v2(arg, j)
# TODO(wangpeng): Investigate whether we need a tf.identity for TPU.
if not has_tpu:
with ops.device(device):
updated_arg = array_ops.identity(updated_arg)
flattened_per_device_args[j].append(updated_arg)
elif isinstance(arg, ShardedNdArray):
for device_args, tensor in zip(flattened_per_device_args, arg.tensors):
device_args.append(tensor)
else:
for device_args in flattened_per_device_args:
device_args.append(arg)
all_per_device_args = [
nest.pack_sequence_as(args, device_args)
for device_args in flattened_per_device_args
]
with pmap_config(axis_name, devices):
results = pmap_fn(all_per_device_args)
# Rewrap things. This can probably be written better.
flattened_results = [nest.flatten(result) for result in results]
final_tree = []
# TODO(nareshmodi): assert all items in flattened_results have the same
# structures
for i in range(len(flattened_results[0])):
tensors = []
for j, device in enumerate(devices):
assert isinstance(
flattened_results[j][i], tensor_lib.Tensor
), "currently only tensor return items are supported"
tensors.append(flattened_results[j][i])
final_tree.append(ShardedNdArray(tensors))
return nest.pack_sequence_as(results[0], final_tree)
return wrapper
def find_devices(device_type, devices=None):
if not devices:
devices = [d.name for d in config.list_logical_devices()]
devices = [(d, device_spec.DeviceSpecV2.from_string(d)) for d in devices]
results = [name for name, d in devices if d.device_type == device_type]
return results
def tpu_devices(devices=None):
"""Gets TPU devices out of `devices`.
Args:
devices: A device list (as a list of strings). If None, the list of all
available devices will be used for it.
Returns:
Those in `devices` that are TPUs.
"""
return find_devices("TPU", devices)
def gpu_devices(devices=None):
"""Gets GPU devices out of `devices`.
Args:
devices: A device list (as a list of strings). If None, the list of all
available devices will be used for it.
Returns:
Those in `devices` that are GPUs.
"""
return find_devices("GPU", devices)
def accelerators(devices=None):
return tpu_devices(devices) or gpu_devices(devices)
def _tree_broadcast(to, s):
"""Broadcasts `s` to the nested structure `to`."""
if not isinstance(to, (list, tuple, dict)):
if not isinstance(s, (int, type(None))):
raise ValueError
return s
if isinstance(s, (int, type(None))):
return nest.map_structure(lambda x: s, to)
if isinstance(to, (list, tuple)):
if len(to) != len(s):
raise ValueError
new_s = [_tree_broadcast(x, y) for x, y in zip(to, s)]
if isinstance(to, tuple):
new_s = tuple(new_s)
return new_s
elif isinstance(to, dict):
return {k: _tree_broadcast(to[k], s[k]) for k in to}
else:
raise TypeError("Unsupported type %s" % type(to))
def vmap(f, in_axes=0, out_axes=0):
"""Returns a function that maps `f` over first dimension of inputs."""
in_axes_flat = nest.flatten(in_axes)
if not all(isinstance(l, (type(None), int))
for l in in_axes_flat):
raise TypeError(
"vmap in_axes must be an int, None, or (nested) container with "
"those types as leaves, but got {}.".format(in_axes))
if all(isinstance(l, type(None)) for l in in_axes_flat):
raise ValueError("vmap must have at least one non-None value in in_axes")
out_axes_flat = nest.flatten(out_axes)
if not all(isinstance(l, (type(None), int))
for l in out_axes_flat):
raise TypeError(
"vmap out_axes must be an int, None, or (nested) container with "
"those types as leaves, but got {}.".format(out_axes))
def _f(*args):
flat_args = nest.flatten(args)
try:
f_in_axes = _tree_broadcast(args, in_axes)
except ValueError:
six.reraise(
ValueError,
ValueError(
"vmap in_axes specification must be a tree prefix of the "
r"corresponding value, got specification %s for value tree %s" % (
in_axes, args)),
sys.exc_info()[2])
f_in_axes_flat = nest.flatten(f_in_axes)
def tf_f(tf_args):
"""Function passed to tf.vectorized_map call."""
# Note that unbatched arguments are not passed to tf_f. Here we fill thos
# arguments back before calling `f`.
tf_flat_args = []
j = 0
for arg, axis in zip(flat_args, f_in_axes_flat):
if axis is None:
tf_flat_args.append(arg)
else:
tf_flat_args.append(tf_args[j])
j += 1
unbatched_args = nest.pack_sequence_as(args, tf_flat_args)
return f(*unbatched_args)
# Constructs arguments to pass to `tf_f`.
# Unbatch arguments are skipped. Arguments with non-zero axis are
# transposed.
tf_args = []
for arg, axis in zip(flat_args, f_in_axes_flat):
if axis is None:
continue
arg = tf_np.asarray(arg)
if axis != 0:
arg = tf_np.moveaxis(arg, axis, 0)
tf_args.append(arg)
# TODO(agarwal): consider creating a tf.function outside of _f and reusing
# that to avoid overheads of re-vectorizing the code when running eagerly.
outputs = pfor_ops.vectorized_map(tf_f, tf_args)
try:
f_out_axes = _tree_broadcast(outputs, out_axes)
except ValueError:
six.reraise(
ValueError,
ValueError(
"vmap out_axes specification must be a tree prefix of the "
r"corresponding value, got specification %s for value tree %s" % (
out_axes, outputs)),
sys.exc_info()[2])
def map_output(x, axis):
"""Maps output of tf.vectorized_map to the final output."""
x = tf_np.asarray(x)
if axis is None:
# Note that `tf.vectorized_map always batches the outputs.
# Here we unbatch it again.
return x[0, ...]
elif axis == 0:
return x
else:
# Need to transpose the output.
return tf_np.moveaxis(x, 0, axis)
new_outputs = [
map_output(output, axis)
for output, axis in zip(nest.flatten(outputs), nest.flatten(f_out_axes))
]
return nest.pack_sequence_as(outputs, new_outputs)
return _f
|
tensorflowREPO_NAMEtensorflowPATH_START.@tensorflow_extracted@tensorflow-master@tensorflow@python@ops@numpy_ops@tests@extensions.py@.PATH_END.py
|
{
"filename": "tfsa-2021-082.md",
"repo_name": "tensorflow/tensorflow",
"repo_path": "tensorflow_extracted/tensorflow-master/tensorflow/security/advisory/tfsa-2021-082.md",
"type": "Markdown"
}
|
## TFSA-2021-082: Division by zero in TFLite's convolution code
### CVE Number
CVE-2021-29594
### Impact
TFLite's [convolution
code](https://github.com/tensorflow/tensorflow/blob/09c73bca7d648e961dd05898292d91a8322a9d45/tensorflow/lite/kernels/conv.cc)
has multiple division where the divisor is controlled by the user and not
checked to be non-zero. For example:
```cc
const int input_size = NumElements(input) / SizeOfDimension(input, 0);
```
### Patches
We have patched the issue in GitHub commit
[ff489d95a9006be080ad14feb378f2b4dac35552](https://github.com/tensorflow/tensorflow/commit/ff489d95a9006be080ad14feb378f2b4dac35552).
The fix will be included in TensorFlow 2.5.0. We will also cherrypick this
commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow
2.1.4, as these are also affected and still in supported range.
### For more information
Please consult [our security
guide](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for
more information regarding the security model and how to contact us with issues
and questions.
### Attribution
This vulnerability has been reported by members of the Aivul Team from Qihoo
360.
|
tensorflowREPO_NAMEtensorflowPATH_START.@tensorflow_extracted@tensorflow-master@tensorflow@security@advisory@tfsa-2021-082.md@.PATH_END.py
|
{
"filename": "unstructured_mesh.py",
"repo_name": "yt-project/yt",
"repo_path": "yt_extracted/yt-main/yt/data_objects/index_subobjects/unstructured_mesh.py",
"type": "Python"
}
|
import numpy as np
from yt.data_objects.selection_objects.data_selection_objects import (
YTSelectionContainer,
)
from yt.funcs import mylog
from yt.utilities.lib.mesh_utilities import fill_fcoords, fill_fwidths
class UnstructuredMesh(YTSelectionContainer):
# This is a base class, not meant to be used directly.
_spatial = False
_connectivity_length = -1
_type_name = "unstructured_mesh"
_skip_add = True
_index_offset = 0
_con_args = ("mesh_id", "filename", "connectivity_indices", "connectivity_coords")
def __init__(
self, mesh_id, filename, connectivity_indices, connectivity_coords, index
):
super().__init__(index.dataset, None)
self.filename = filename
self.mesh_id = mesh_id
# This is where we set up the connectivity information
self.connectivity_indices = connectivity_indices
if connectivity_indices.shape[1] != self._connectivity_length:
if self._connectivity_length == -1:
self._connectivity_length = connectivity_indices.shape[1]
else:
raise RuntimeError
self.connectivity_coords = connectivity_coords
self.ds = index.dataset
self._index = index
self._last_mask = None
self._last_count = -1
self._last_selector_id = None
def _check_consistency(self):
if self.connectivity_indices.shape[1] != self._connectivity_length:
raise RuntimeError
for gi in range(self.connectivity_indices.shape[0]):
ind = self.connectivity_indices[gi, :] - self._index_offset
coords = self.connectivity_coords[ind, :]
for i in range(3):
assert np.unique(coords[:, i]).size == 2
mylog.debug("Connectivity is consistent.")
def __repr__(self):
return "UnstructuredMesh_%04i" % (self.mesh_id)
def get_global_startindex(self):
"""
Return the integer starting index for each dimension at the current
level.
"""
raise NotImplementedError
def convert(self, datatype):
"""
This will attempt to convert a given unit to cgs from code units. It
either returns the multiplicative factor or throws a KeyError.
"""
return self.ds[datatype]
@property
def shape(self):
raise NotImplementedError
def _generate_container_field(self, field):
raise NotImplementedError
def select_fcoords(self, dobj=None):
# This computes centroids!
mask = self._get_selector_mask(dobj.selector)
if mask is None:
return np.empty((0, 3), dtype="float64")
centers = fill_fcoords(
self.connectivity_coords, self.connectivity_indices, self._index_offset
)
return centers[mask, :]
def select_fwidth(self, dobj):
raise NotImplementedError
def select_icoords(self, dobj):
raise NotImplementedError
def select_ires(self, dobj):
raise NotImplementedError
def select_tcoords(self, dobj):
raise NotImplementedError
def deposit(self, positions, fields=None, method=None, kernel_name="cubic"):
raise NotImplementedError
def select_blocks(self, selector):
mask = self._get_selector_mask(selector)
yield self, mask
def select(self, selector, source, dest, offset):
mask = self._get_selector_mask(selector)
count = self.count(selector)
if count == 0:
return 0
dest[offset : offset + count] = source[mask, ...]
return count
def count(self, selector):
mask = self._get_selector_mask(selector)
if mask is None:
return 0
return self._last_count
def count_particles(self, selector, x, y, z):
# We don't cache the selector results
count = selector.count_points(x, y, z, 0.0)
return count
def select_particles(self, selector, x, y, z):
mask = selector.select_points(x, y, z, 0.0)
return mask
def _get_selector_mask(self, selector):
if hash(selector) == self._last_selector_id:
mask = self._last_mask
else:
self._last_mask = mask = selector.fill_mesh_cell_mask(self)
self._last_selector_id = hash(selector)
if mask is None:
self._last_count = 0
else:
self._last_count = mask.sum()
return mask
def select_fcoords_vertex(self, dobj=None):
mask = self._get_selector_mask(dobj.selector)
if mask is None:
return np.empty((0, self._connectivity_length, 3), dtype="float64")
vertices = self.connectivity_coords[self.connectivity_indices - 1]
return vertices[mask, :, :]
class SemiStructuredMesh(UnstructuredMesh):
_connectivity_length = 8
_type_name = "semi_structured_mesh"
_container_fields = ("dx", "dy", "dz")
def __repr__(self):
return "SemiStructuredMesh_%04i" % (self.mesh_id)
def _generate_container_field(self, field):
if self._current_chunk is None:
self.index._identify_base_chunk(self)
if field == "dx":
return self._current_chunk.fwidth[:, 0]
elif field == "dy":
return self._current_chunk.fwidth[:, 1]
elif field == "dz":
return self._current_chunk.fwidth[:, 2]
def select_fwidth(self, dobj):
mask = self._get_selector_mask(dobj.selector)
if mask is None:
return np.empty((0, 3), dtype="float64")
widths = fill_fwidths(
self.connectivity_coords, self.connectivity_indices, self._index_offset
)
return widths[mask, :]
def select_ires(self, dobj):
ind = np.zeros(self.connectivity_indices.shape[0])
mask = self._get_selector_mask(dobj.selector)
if mask is None:
return np.empty(0, dtype="int32")
return ind[mask]
def select_tcoords(self, dobj):
mask = self._get_selector_mask(dobj.selector)
if mask is None:
return np.empty(0, dtype="float64")
dt, t = dobj.selector.get_dt_mesh(self, mask.sum(), self._index_offset)
return dt, t
def _get_selector_mask(self, selector):
if hash(selector) == self._last_selector_id:
mask = self._last_mask
else:
self._last_mask = mask = selector.fill_mesh_cell_mask(self)
self._last_selector_id = hash(selector)
if mask is None:
self._last_count = 0
else:
self._last_count = mask.sum()
return mask
def select(self, selector, source, dest, offset):
mask = self._get_selector_mask(selector)
count = self.count(selector)
if count == 0:
return 0
# Note: this likely will not work with vector fields.
dest[offset : offset + count] = source.flat[mask]
return count
|
yt-projectREPO_NAMEytPATH_START.@yt_extracted@yt-main@yt@data_objects@index_subobjects@unstructured_mesh.py@.PATH_END.py
|
{
"filename": "_xaxis.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/scatter/_xaxis.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class XaxisValidator(_plotly_utils.basevalidators.SubplotidValidator):
def __init__(self, plotly_name="xaxis", parent_name="scatter", **kwargs):
super(XaxisValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
dflt=kwargs.pop("dflt", "x"),
edit_type=kwargs.pop("edit_type", "calc+clearAxisTypes"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@scatter@_xaxis.py@.PATH_END.py
|
{
"filename": "tool.py",
"repo_name": "langchain-ai/langchain",
"repo_path": "langchain_extracted/langchain-master/libs/langchain/langchain/tools/metaphor_search/tool.py",
"type": "Python"
}
|
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import MetaphorSearchResults
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"MetaphorSearchResults": "langchain_community.tools"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"MetaphorSearchResults",
]
|
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@langchain@langchain@tools@metaphor_search@tool.py@.PATH_END.py
|
{
"filename": "full_lrs2_reduction.py",
"repo_name": "grzeimann/Panacea",
"repo_path": "Panacea_extracted/Panacea-master/full_lrs2_reduction.py",
"type": "Python"
}
|
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 13:30:06 2018
@author: gregz
"""
import numpy as np
import fnmatch
import os.path as op
import os
import glob
import sys
import warnings
import tarfile
import argparse as ap
import requests
import uuid
from datetime import datetime, timedelta
from astropy.io.votable import parse_single_table
from fiber_utils import bspline_x0
from astropy.io import fits
from astropy.table import Table
from scipy.signal import savgol_filter
from distutils.dir_util import mkpath
from scipy.ndimage.filters import percentile_filter
from scipy.interpolate import interp1d, interp2d, griddata
from input_utils import setup_logging
from astrometry import Astrometry
from astropy.stats import biweight_midvariance, biweight_location
from astropy.modeling.models import Moffat2D, Polynomial2D, Gaussian2D
from astropy.modeling.fitting import LevMarLSQFitter
from sklearn.decomposition import PCA
from astropy.convolution import Gaussian1DKernel, Gaussian2DKernel, convolve
standard_names = ['HD_19445', 'SA95-42', 'GD50', 'G191B2B',
'HILTNER_600', 'G193-74', 'PG0823+546', 'HD_84937',
'GD108', 'FEIGE_34', 'HD93521', 'GD140', 'HZ_21',
'FEIGE_66', 'FEIGE_67', 'G60-54', 'HZ_44', 'GRW+70_5824',
'BD+26+2606', 'BD+33_2642', 'G138-31', 'WOLF_1346',
'BD_+17_4708', 'FEIGE_110', 'GD248', 'HZ_4',
'BD+40_4032', 'HILTNER_102',
'BD_+26_2606', 'GD_248', 'FEIGE_56', 'FEIGE_92',
'HZ_15', 'FEIGE_98', 'BD+08_2015', 'BD+25_3941',
'FEIGE_15', 'FEIGE_25', 'SA_95-42', 'BD+28_4211',
'HR6203']
log = setup_logging('panacea_quicklook')
parser = ap.ArgumentParser(add_help=True)
parser.add_argument("-d", "--date",
help='''Date for reduction''',
type=str, default='20181108')
parser.add_argument("-s", "--sides",
help='''"uv,orange,red,farred"''',
type=str, default="uv,orange,red,farred")
parser.add_argument("-o", "--object",
help='''Object name, no input reduces all objects''',
type=str, default=None)
parser.add_argument("-uf", "--use_flat",
help='''Use FLT instead of Twi''',
action="count", default=0)
parser.add_argument("-cf", "--correct_ftf",
help='''Correct fiber to fiber''',
action="count", default=0)
parser.add_argument("-md", "--model_dar",
help='''model DAR''',
action="count", default=0)
parser.add_argument("-cw", "--central_wave",
help='''Central Wavelength for collapsed Frame''',
type=float, default=None)
parser.add_argument("-wb", "--wavelength_bin",
help='''Wavelength Bin to collapse over (+/- bin size)''',
type=float, default=10.)
parser.add_argument("-sx", "--source_x",
help='''Source's x position at the central_wave''',
type=float, default=None)
parser.add_argument("-sy", "--source_y",
help='''Source's y position at the central_wave''',
type=float, default=None)
parser.add_argument("-ssd", "--standard_star_date",
help='''Standard Star Date for response function,
example: 20181101''',
type=str, default=None)
parser.add_argument("-sso", "--standard_star_obsid",
help='''Standard Star ObsID for response function,
example: 0000012''',
type=str, default=None)
parser.add_argument("-ad", "--arc_date",
help='''Arc Date for reduction''',
type=str, default=None)
parser.add_argument("-td", "--twi_date",
help='''Twilight Date for reduction''',
type=str, default=None)
parser.add_argument("-re", "--reduce_eng",
help='''Reduce Engineer Data''',
action="count", default=0)
parser.add_argument("-rf", "--reduce_flt",
help='''Reduce Flat Data''',
action="count", default=0)
parser.add_argument("-rd", "--reduce_drk",
help='''Reduce Dark Data''',
action="count", default=0)
args = parser.parse_args(args=None)
if args.standard_star_obsid is not None:
args.standard_star_obsid = '%07d' % int(args.standard_star_obsid)
if args.standard_star_date is None:
log.error('Please include --standard_star_date DATE with call.')
for i in ['source_x', 'source_y']:
for j in ['source_x', 'source_y', 'central_wave']:
if i == j:
continue
if getattr(args, i) is not None:
if getattr(args, j) is None:
log.error('%s was set but not %s.' % (i, j))
sys.exit(1)
args.sides = [x.replace(' ', '') for x in args.sides.split(',')]
blueinfo = [['BL', 'uv', '503_056_7001', [3640., 4645.], ['LL', 'LU'],
[4350., 4375.], ['hg_b', 'cd-a_b', 'fear_r', 'cd_b', 'hg', 'cd', 'fear']],
['BR', 'orange', '503_056_7001',
[4635., 6950.], ['RU', 'RL'], [6270., 6470.],
['hg_b', 'cd-a_b', 'fear_r', 'cd_b', 'hg', 'cd', 'fear']]]
redinfo = [['RL', 'red', '502_066_7002', [6450., 8400.], ['LL', 'LU'],
[7225., 7425.], ['hg_r', 'cd-a_b', 'fear_r', 'cd_b', 'hg', 'cd', 'fear']],
['RR', 'farred', '502_066_7002',
[8275., 10500.], ['RU', 'RL'], [9280., 9530.],
['hg_r', 'cd-a_b', 'fear_r', 'cd_b', 'hg', 'cd', 'fear']]]
listinfo = []
for side in args.sides:
if side.lower() == 'uv':
listinfo.append(blueinfo[0])
if side.lower() == 'orange':
listinfo.append(blueinfo[1])
if side.lower() == 'red':
listinfo.append(redinfo[0])
if side.lower() == 'farred':
listinfo.append(redinfo[1])
fplane_file = '/work/03730/gregz/maverick/fplane.txt'
twi_date = args.date
sci_date = args.date
# FOR LRS2
instrument = 'lrs2'
dither_pattern = np.zeros((50, 2))
baseraw = '/work/03946/hetdex/maverick'
sci_tar = op.join(baseraw, sci_date, '%s', '%s000*.tar')
sci_path = op.join(baseraw, sci_date, '%s', '%s%s', 'exp%s',
'%s', '2*_%sLL*sci.fits')
cmp_path = op.join(baseraw, sci_date, '%s', '%s%s', 'exp*',
'%s', '2*_%sLL_cmp.fits')
twi_path = op.join(baseraw, sci_date, '%s', '%s%s', 'exp*',
'%s', '2*_%sLL_twi.fits')
bias_path = op.join(baseraw, sci_date, '%s', '%s%s', 'exp*',
'%s', '2*_%sLL_zro.fits')
if args.reduce_eng:
sci_path = sci_path.replace('sci', 'eng')
if args.reduce_flt:
sci_path = sci_path.replace('sci', 'flt')
if args.reduce_drk:
sci_path = sci_path.replace('sci', 'drk')
def get_script_path():
return op.dirname(op.realpath(sys.argv[0]))
def get_ifucenfile(side, amp,
virusconfig='/work/03946/hetdex/maverick/virus_config',
skiprows=4):
file_dict = {"uv": "LRS2_B_UV_mapping.txt",
"orange": "LRS2_B_OR_mapping.txt",
"red": "LRS2_R_NR_mapping.txt",
"farred": "LRS2_R_FR_mapping.txt"}
ifucen = np.loadtxt(op.join(virusconfig, 'IFUcen_files',
file_dict[side]), usecols=[0, 1, 2], skiprows=skiprows)
if amp == "LL":
return ifucen[140:, 1:3][::-1, :]
if amp == "LU":
return ifucen[:140, 1:3][::-1, :]
if amp == "RL":
return ifucen[:140, 1:3][::-1, :]
if amp == "RU":
return ifucen[140:, 1:3][::-1, :]
def orient_image(image, amp, ampname):
'''
Orient the images from blue to red (left to right)
Fibers are oriented to match configuration files
'''
if amp == "LU":
image[:] = image[::-1, ::-1]
if amp == "RL":
image[:] = image[::-1, ::-1]
if ampname is not None:
if ampname == 'LR' or ampname == 'UL':
image[:] = image[:, ::-1]
return image
def make_avg_spec(wave, spec, binsize=35, per=50):
ind = np.argsort(wave.ravel())
T = 1
for p in wave.shape:
T *= p
wchunks = np.array_split(wave.ravel()[ind],
T / binsize)
schunks = np.array_split(spec.ravel()[ind],
T / binsize)
nwave = np.array([np.mean(chunk) for chunk in wchunks])
nspec = np.array([np.percentile(chunk, per) for chunk in schunks])
nwave, nind = np.unique(nwave, return_index=True)
return nwave, nspec[nind]
def base_reduction(filename, tarname=None, get_header=False):
if tarname is None:
a = fits.open(filename)
else:
try:
t = tarfile.open(tarname, 'r')
a = fits.open(t.extractfile('/'.join(filename.split('/')[-4:])))
except:
log.warning('Could not open %s' % filename)
return np.zeros((1032, 2064)), np.zeros((1032, 2064))
image = np.array(a[0].data, dtype=float)
# overscan sub
overscan_length = int(32 * (image.shape[1] / 1064))
O = biweight_location(image[:, -int(overscan_length-2):])
image[:] = image - O
# trim image
image = image[:, :-overscan_length]
gain = a[0].header['GAIN']
gain = np.where(gain > 0., gain, 0.85)
rdnoise = a[0].header['RDNOISE']
rdnoise = np.where(rdnoise > 0., rdnoise, 3.)
amp = (a[0].header['CCDPOS'].replace(' ', '') +
a[0].header['CCDHALF'].replace(' ', ''))
try:
ampname = a[0].header['AMPNAME']
except:
ampname = None
header = a[0].header
a = orient_image(image, amp, ampname) * gain
E = np.sqrt(rdnoise**2 + np.where(a > 0., a, 0.))
if tarname is not None:
t.close()
if get_header:
return a, E, header
return a, E
def power_law(x, c1, c2=.5, c3=.15, c4=1., sig=2.5):
return c1 / (c2 + c3 * np.power(abs(x / sig), c4))
def get_powerlaw(image, trace, spec):
YM, XM = np.indices(image.shape)
inds = []
for j in np.arange(trace.shape[0]):
inds.append(np.where(np.abs(YM - trace[j, np.newaxis, :]).ravel() <
7.)[0])
inds = np.hstack(inds)
inds = np.unique(inds)
inds = np.setdiff1d(np.arange(image.shape[0] * image.shape[1]), inds)
y, x = np.unravel_index(inds, image.shape)
xlim = [0, image.shape[1]]
xy = np.nanmedian(spec, axis=1)
bottom = np.abs(np.nanpercentile(xy, 15))
sel = np.where(xy > (15. * bottom))[0]
log.info('Number of fibers that need powerlaw modeling: %i' % len(sel))
xp = np.hstack([np.arange(xlim[0], xlim[1], 128), image.shape[1]-1])
ylim = [0, image.shape[0]]
yz = np.hstack([np.arange(ylim[0], ylim[1], 128), image.shape[0]-1])
plaw, XX, YY = ([], [], [])
YM, XM = np.indices(trace.shape)
for xi in xp:
for yi in yz:
d = np.sqrt((yi - trace)**2 + (xi - XM)**2)
plaw.append(np.nansum(spec * power_law(d, 1.4e-5, c3=2., c4=1.0,
sig=1.5)))
XX.append(xi)
YY.append(yi)
for xi in xp:
for s in sel:
y0 = int(trace[s, xi])
for i in np.arange(-4, 6, 2):
d = np.sqrt(((y0+i) - trace)**2 + (xi - XM)**2)
plaw.append(np.nansum(spec * power_law(d, 1.4e-5, c3=2.,
c4=1.0, sig=1.5)))
YY.append(y0+i)
XX.append(xi)
plaw, XX, YY = [np.hstack(j) for j in [plaw, XX, YY]]
grid_x, grid_y = np.meshgrid(np.arange(image.shape[1]),
np.arange(image.shape[0]))
C = griddata(np.array([XX, YY]).swapaxes(0, 1), plaw, (grid_x, grid_y),
method='cubic', fill_value=0.0)
norm = np.zeros((image.shape[1],))
for b in np.arange(image.shape[1]):
sel = (x == b)
norm[b] = np.median(image[y[sel], x[sel]] / C[y[sel], x[sel]])
return C * savgol_filter(norm, 141, 1)[np.newaxis, :], norm
def get_bigW(amp, array_wave, array_trace, image):
bigW = np.zeros(image.shape)
Y, X = np.indices(array_wave.shape)
YY, XX = np.indices(image.shape)
for x, at, aw, xx, yy in zip(np.array_split(X, 2, axis=0),
np.array_split(array_trace, 2, axis=0),
np.array_split(array_wave, 2, axis=0),
np.array_split(XX, 2, axis=0),
np.array_split(YY, 2, axis=0)):
for j in np.arange(at.shape[1]):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
p0 = np.polyfit(at[:, j], aw[:, j], 7)
bigW[yy[:, j], j] = np.polyval(p0, yy[:, j])
return bigW
def get_bigF(array_trace, image):
bigF = np.zeros(image.shape)
Y, X = np.indices(array_trace.shape)
YY, XX = np.indices(image.shape)
n, m = array_trace.shape
F0 = array_trace[:, int(m/2)]
for j in np.arange(image.shape[1]):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
p0 = np.polyfit(array_trace[:, j], F0, 7)
bigF[:, j] = np.polyval(p0, YY[:, j])
return bigF
def get_tarname_from_filename(filename):
tarname = op.dirname(op.dirname(op.dirname(filename))) + '.tar'
return tarname
def get_twiflat_field(files, amps, array_wave, array_trace, bigW,
common_wave, masterbias, specname):
files1 = [file.replace('LL', amps[0]) for file in files]
files2 = [file.replace('LL', amps[1]) for file in files]
tarnames = [get_tarname_from_filename(file) for file in files]
array_list = []
for filename1, filename2, tarname in zip(files1, files2, tarnames):
log.info('Prepping flat %s' % filename1)
array_flt1, e1 = base_reduction(filename1, tarname=tarname)
array_flt2, e2 = base_reduction(filename2, tarname=tarname)
array_flt = np.vstack([array_flt1, array_flt2])
array_flt[:] -= masterbias
array_list.append(array_flt)
array_list = np.array(array_list)
if len(array_list) > 1:
norm = np.median(array_list, axis=(1,2))
array_flt = np.median(array_list / norm[:, np.newaxis, np.newaxis],
axis=0)
else:
array_flt = np.squeeze(np.array(array_list))
array_flt[:] /= np.median(array_flt)
log.info('Working on flat')
x = np.arange(array_wave.shape[1])
spectrum = array_trace * 0.
for fiber in np.arange(array_wave.shape[0]):
indl = np.floor(array_trace[fiber]).astype(int)
indh = np.ceil(array_trace[fiber]).astype(int)
try:
spectrum[fiber] = array_flt[indl, x] / 2. + array_flt[indh, x] / 2.
except:
spectrum[fiber] = 0.
log.info('Getting powerlaw for side %s' % specname)
plaw, norm = get_powerlaw(array_flt, array_trace, spectrum)
array_flt[:] -= plaw
array_flt[:] = np.where(array_flt < 0., 0., array_flt)
#fits.PrimaryHDU(plaw).writeto('test_plaw_%s.fits' % specname, overwrite=True)
#fits.PrimaryHDU(array_flt).writeto('test_spec_%s.fits' % specname, overwrite=True)
smooth = savgol_filter(spectrum, 315, 1, axis=1)
avg = biweight_location(smooth, axis=(0,))
norm = biweight_location(smooth / avg, axis=(1,))
nw, ns = make_avg_spec(array_wave, spectrum / norm[:, np.newaxis],
binsize=41, per=50)
I = interp1d(nw, ns, kind='linear', fill_value='extrapolate')
ftf = spectrum * 0.
for fiber in np.arange(array_wave.shape[0]):
model = I(array_wave[fiber])
ftf[fiber] = savgol_filter(spectrum[fiber] / model, 151, 1)
nw1, ns1 = make_avg_spec(array_wave, spectrum / ftf, binsize=41,
per=50)
B, c = bspline_x0(nw1, nknots=int(spectrum.shape[1]))
sol = np.linalg.lstsq(c, ns1)[0]
ns1 = np.dot(c, sol)
I = interp1d(nw1, ns1, kind='quadratic', fill_value='extrapolate')
modelimage = I(bigW)
flat = array_flt / modelimage
flat[~np.isfinite(flat)] = 0.0
flat[flat < 0.0] = 0.0
#fits.HDUList([fits.PrimaryHDU(array_flt), fits.ImageHDU(modelimage),
# fits.ImageHDU(flat)]).writeto('flat_example_%s.fits' % specname, overwrite=True)
return flat
def get_spectra(array_flt, array_trace):
spectrum = array_trace * 0.
x = np.arange(array_flt.shape[1])
for fiber in np.arange(array_trace.shape[0]):
indl = np.floor(array_trace[fiber]).astype(int)
indh = np.ceil(array_trace[fiber]).astype(int)
try:
spectrum[fiber] = array_flt[indl, x] / 2. + array_flt[indh, x] / 2.
except:
log.warning('Index for getting spectrum out of bounds.')
return spectrum
def safe_division(num, denom, eps=1e-8, fillval=0.0):
good = np.isfinite(denom) * (np.abs(denom) > eps)
div = num * 0.
if num.ndim == denom.ndim:
div[good] = num[good] / denom[good]
div[~good] = fillval
else:
div[:, good] = num[:, good] / denom[good]
div[:, ~good] = fillval
return div
def find_cosmics(Y, E, trace, thresh=8., ran=0):
x = np.arange(trace.shape[1])
C = Y * 0.
for fiber in np.arange(trace.shape[0]):
indl = np.floor(trace[fiber]).astype(int)
T = np.zeros((4, trace.shape[1], 4))
flag = True
for ss, k in enumerate(np.arange(-1, 3)):
try:
T[0, :, ss] = Y[indl+k, x]
T[1, :, ss] = E[indl+k, x]
T[2, :, ss] = indl+k
T[3, :, ss] = x
except:
flag = False
if flag:
m = np.median(T[0], axis=1)
P = np.abs(T[0] - m[:, np.newaxis]) / T[1]
C[T[2][P > thresh].astype(int), T[3][P > thresh].astype(int)] = 1.
C = np.array(C, dtype=bool)
log.info('Number of fiber pixels hit by cosmics: %i' % C.sum())
return C
def weighted_extraction(image, error, flat, trace, cthresh=8.):
E = safe_division(error, flat)
E[E < 1e-8] = 1e9
Y = safe_division(image, flat)
nY = Y * 1.
C = np.array(Y * 0., dtype=bool)
for i in np.arange(1):
cosmics = find_cosmics(nY, E, trace, thresh=cthresh, ran=1)
C = C + cosmics
x = np.arange(trace.shape[1])
spectrum = 0. * trace
error_spec = 0. * trace
Fimage = image * 0.
for fiber in np.arange(trace.shape[0]):
T = np.zeros((4, trace.shape[1], 4))
indl = np.floor(trace[fiber]).astype(int)-1
flag = False
for ss, k in enumerate(np.arange(0, 4)):
try:
T[0, :, ss] = Y[indl+k, x]
T[1, :, ss] = 1. / E[indl+k, x]**2
T[2, :, ss] = ~C[indl+k, x]
T[3, :, ss] = error[indl+k, x]**2
Fimage[indl+k, x] = fiber + 1
except:
v = indl+k
sel = np.where((v >= 0) * (v < Y.shape[0]))[0]
T[0, sel, ss] = Y[v[sel], x[sel]]
T[1, sel, ss] = 1. / E[v[sel], x[sel]]**2
T[2, sel, ss] = ~C[v[sel], x[sel]]
T[3, sel, ss] = error[v[sel], x[sel]]**2
Fimage[v[sel], x[sel]] = fiber + 1
flag = True
if flag:
if np.mean(indl) > (Y.shape[0]/2.):
k = 2
else:
k = -1
v = indl+k
sel = np.where((v >= 0) * (v < len(x)))[0]
a = np.sum(T[0, sel] * T[1, sel] * T[2, sel], axis=1)
b = np.sum(T[1, sel] * T[2, sel], axis=1)
spectrum[fiber, sel] = safe_division(a, b)
sel1 = T[2, sel].sum(axis=1) < 2.
spectrum[fiber][sel][sel1] = 0.0
error_spec[fiber][sel][sel1] = 0.0
else:
a = np.sum(T[0] * T[1] * T[2], axis=1)
b = np.sum(T[1] * T[2], axis=1)
spectrum[fiber] = safe_division(a, b)
a = np.sum(T[3] * T[1] * T[2], axis=1)
b = np.sum(T[1] * T[2], axis=1)
error_spec[fiber] = np.sqrt(safe_division(a, b))
sel = T[2].sum(axis=1) < 2.
spectrum[fiber][sel] = 0.0
error_spec[fiber][sel] = 0.0
return spectrum, error_spec, C, Y, Fimage
def get_trace_shift(sci_array, flat, array_trace, Yx):
YM, XM = np.indices(flat.shape)
inds = np.zeros((3, array_trace.shape[0], array_trace.shape[1]))
XN = np.round(array_trace)
inds[0] = XN - 1.
inds[1] = XN + 0.
inds[2] = XN + 1.
inds = np.array(inds, dtype=int)
Trace = array_trace * 0.
FlatTrace = array_trace * 0.
N = YM.max()
x = np.arange(array_trace.shape[1])
for i in np.arange(Trace.shape[0]):
sel = YM[inds[0, i, :], x] >= 0.
sel = sel * (YM[inds[2, i, :], x] < N)
xmax = (YM[inds[1, i, sel], x[sel]] -
(sci_array[inds[2, i, sel], x[sel]] -
sci_array[inds[0, i, sel], x[sel]]) /
(2. * (sci_array[inds[2, i, sel], x[sel]] -
2. * sci_array[inds[1, i, sel], x[sel]] +
sci_array[inds[0, i, sel], x[sel]])))
Trace[i, sel] = xmax
xmax = (YM[inds[1, i, sel], x[sel]] - (flat[inds[2, i, sel], x[sel]] -
flat[inds[0, i, sel], x[sel]]) /
(2. * (flat[inds[2, i, sel], x[sel]] - 2. *
flat[inds[1, i, sel], x[sel]] +
flat[inds[0, i, sel], x[sel]])))
FlatTrace[i, sel] = xmax
mid = int(Trace.shape[1] / 2)
shifts = np.nanmedian((FlatTrace - Trace)[:, mid-200:mid+200], axis=1)
shifts = np.polyval(np.polyfit(np.nanmedian(FlatTrace, axis=1), shifts, 2),
Yx)
return shifts
def modify_spectrum(spectrum, error, w, xloc, yloc):
dw = np.median(np.diff(w, axis=1), axis=0)
dw = np.hstack([dw[0], dw])
for i in np.arange(spectrum.shape[0]):
sel = spectrum[i] == 0.
I = interp1d(w[i][~sel], spectrum[i][~sel], kind='quadratic',
fill_value='extrapolate')
spectrum[i] = I(w[i]) / dw
error[i] /= dw
bad = error == 0.
for i in np.arange(1, 3):
bad[:, :-i] += bad[:, i:]
bad[:, i:] += bad[:, :-i]
error[bad] = 0.
return spectrum, error
def extract_sci(sci_path, amps, flat, array_trace, array_wave, bigW,
masterbias, pos):
files1 = get_filenames_from_tarfolder(get_tarname_from_filename(sci_path),
sci_path.replace('LL', amps[0]))
files2 = get_filenames_from_tarfolder(get_tarname_from_filename(sci_path),
sci_path.replace('LL', amps[1]))
for filen in files1:
log.info('SECOND --- filename: %s' % filen)
tarnames = [get_tarname_from_filename(file) for file in files1]
xloc, yloc = (pos[:, 0], pos[:, 1])
array_list, hdr_list = ([], [])
for filename1, filename2, tarname in zip(files1, files2, tarnames):
log.info('Prepping sci %s' % filename1)
array_flt1, e1, header = base_reduction(filename1, tarname=tarname,
get_header=True)
array_flt2, e2 = base_reduction(filename2, tarname=tarname)
array_flt = np.vstack([array_flt1, array_flt2])
array_flt[:] -= masterbias
array_list.append(array_flt)
hdr_list.append(header)
if len(array_list) > 1:
sci_array = np.sum(array_list, axis=0)
else:
sci_array = np.squeeze(np.array(array_list))
Xx = np.arange(flat.shape[1])
Yx = np.arange(flat.shape[0])
I = interp2d(Xx, Yx, flat, kind='cubic', bounds_error=False,
fill_value=0.0)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
shifts = get_trace_shift(sci_array, flat, array_trace, Yx)
flat = I(Xx, Yx + shifts)
log.info('Found shift for %s of %0.3f' % (files1[0], np.median(shifts)))
array_list = []
spec_list, error_list = ([], [])
orig_list = []
clist, flist, Flist = ([], [], [])
for filename1, filename2, tarname in zip(files1, files2, tarnames):
log.info('Fiber extraction sci %s' % filename1)
array_flt1, e1 = base_reduction(filename1, tarname=tarname)
array_flt2, e2 = base_reduction(filename2, tarname=tarname)
array_flt = np.vstack([array_flt1, array_flt2])
array_err = np.vstack([e1, e2])
array_flt[:] -= masterbias
log.info('Getting powerlaw for %s' % filename1)
spectrum = get_spectra(array_flt, array_trace)
plaw, norm = get_powerlaw(array_flt, array_trace, spectrum)
array_flt[:] -= plaw
array_list.append(array_flt)
spectrum, error, c, fl, Fimage = weighted_extraction(array_flt,
array_err,
flat, array_trace)
sel = ~np.isfinite(spectrum)
spectrum[sel] = 0.0
error[sel] = 0.0
log.info('Number of 0.0 pixels in spectra: %i' %
(spectrum == 0.0).sum())
speclist, errorlist = ([], [])
spectrum, error = modify_spectrum(spectrum, error, array_wave, xloc,
yloc)
log.info('Number of 0.0 pixels in spectra: %i' %
(spectrum == 0.0).sum())
for fiber in np.arange(array_wave.shape[0]):
I = interp1d(array_wave[fiber], spectrum[fiber],
kind='linear', fill_value='extrapolate')
coV = np.zeros((len(commonwave), spectrum.shape[1]))
for i in np.arange(len(commonwave)):
w = np.zeros((len(commonwave),))
w[i] = 1.
coV[i] = np.interp(array_wave[fiber], commonwave, w)
error_interp = np.sqrt((coV * error[fiber]**2).sum(axis=1))
sel = error[fiber] == 0.
if sel.sum() > 0.:
nsel = coV[:, sel].sum(axis=1) > 0.
error_interp[nsel] = 0.
speclist.append(I(commonwave))
errorlist.append(error_interp)
log.info('Finished rectifying spectra')
spec_list.append(np.array(speclist))
error_list.append(np.array(errorlist))
orig_list.append(spectrum)
clist.append(c)
flist.append(fl)
Flist.append(Fimage)
return (np.array(array_list), np.array(spec_list), np.array(orig_list),
np.array(clist, dtype=float), np.array(flist), np.array(Flist),
np.array(error_list), hdr_list)
def get_masterbias(files, amp):
files = [file.replace('LL', amp) for file in files]
tarnames = [get_tarname_from_filename(file) for file in files]
biassum = np.zeros((len(files), 1032, 2064))
for j, filename in enumerate(files):
tarname = tarnames[j]
a, error = base_reduction(filename, tarname=tarname)
biassum[j] = a
return biweight_location(biassum, axis=0)
def get_masterarc(files, amp, arc_names, masterbias, specname, trace):
files = [file.replace('LL', amp) for file in files]
tarnames = [get_tarname_from_filename(file) for file in files]
arcsum = np.zeros((1032, 2064))
cnt = np.zeros((1032, 2064))
for filename, tarname in zip(files, tarnames):
t = tarfile.open(tarname, 'r')
f = fits.open(t.extractfile('/'.join(filename.split('/')[-4:])))
if f[0].header['OBJECT'].lower() in arc_names:
a, e = base_reduction(filename, tarname=tarname)
a[:] -= masterbias
if np.median(a) < 3000.:
#c = find_cosmics(a, e, trace, thresh=15., ran=0)
arcsum += a
cnt += 1.
return arcsum / cnt
def get_mastertwi(files, amp, masterbias):
files = [file.replace('LL', amp) for file in files]
tarnames = [get_tarname_from_filename(file) for file in files]
listtwi = []
for filename, tarname in zip(files, tarnames):
a, e = base_reduction(filename, tarname=tarname)
a[:] -= masterbias
if np.percentile(a, 75) > 100.:
listtwi.append(a)
twi_array = np.array(listtwi, dtype=float)
norm = np.median(twi_array, axis=(1, 2))[:, np.newaxis, np.newaxis]
return np.median(twi_array / norm, axis=0)
def get_trace_reference(specid, ifuslot, ifuid, amp, obsdate,
virusconfig='/work/03946/hetdex/'
'maverick/virus_config'):
files = glob.glob(op.join(virusconfig, 'Fiber_Locations', '*',
'fiber_loc_%s_%s_%s_%s.txt' %
(specid, ifuslot, ifuid, amp)))
dates = [op.basename(op.dirname(fn)) for fn in files]
obsdate = datetime(int(obsdate[:4]), int(obsdate[4:6]),
int(obsdate[6:]))
timediff = np.zeros((len(dates),))
for i, datei in enumerate(dates):
d = datetime(int(datei[:4]), int(datei[4:6]),
int(datei[6:]))
timediff[i] = np.abs((obsdate - d).days)
ref_file = np.loadtxt(files[np.argmin(timediff)])
return ref_file
def get_trace(twilight, specid, ifuslot, ifuid, amp, obsdate):
ref = get_trace_reference(specid, ifuslot, ifuid, amp, obsdate)
N1 = (ref[:, 1] == 0.).sum()
good = np.where(ref[:, 1] == 0.)[0]
def get_trace_chunk(flat, XN):
YM = np.arange(flat.shape[0])
inds = np.zeros((3, len(XN)))
inds[0] = XN - 1.
inds[1] = XN + 0.
inds[2] = XN + 1.
inds = np.array(inds, dtype=int)
Trace = (YM[inds[1]] - (flat[inds[2]] - flat[inds[0]]) /
(2. * (flat[inds[2]] - 2. * flat[inds[1]] + flat[inds[0]])))
return Trace
image = twilight
N = 40
xchunks = np.array([np.mean(x) for x in
np.array_split(np.arange(image.shape[1]), N)])
chunks = np.array_split(image, N, axis=1)
flats = [np.median(chunk, axis=1) for chunk in chunks]
Trace = np.zeros((len(ref), len(chunks)))
k = 0
for flat, x in zip(flats, xchunks):
diff_array = flat[1:] - flat[:-1]
loc = np.where((diff_array[:-1] > 0.) * (diff_array[1:] < 0.))[0]
peaks = flat[loc+1]
loc = loc[peaks > 0.1 * np.median(peaks)]+1
trace = get_trace_chunk(flat, loc)
T = np.zeros((len(ref)))
if len(trace) == N1:
T[good] = trace
for missing in np.where(ref[:, 1] == 1)[0]:
gind = np.argmin(np.abs(missing - good))
T[missing] = (T[good[gind]] + ref[missing, 0] -
ref[good[gind], 0])
Trace[:, k] = T
k += 1
x = np.arange(twilight.shape[1])
trace = np.zeros((Trace.shape[0], twilight.shape[1]))
for i in np.arange(Trace.shape[0]):
sel = Trace[i, :] > 0.
trace[i] = np.polyval(np.polyfit(xchunks[sel], Trace[i, sel], 7), x)
return trace, ref
def find_peaks(y, thresh=8.):
def get_peaks(flat, XN):
YM = np.arange(flat.shape[0])
inds = np.zeros((3, len(XN)))
inds[0] = XN - 1.
inds[1] = XN + 0.
inds[2] = XN + 1.
inds = np.array(inds, dtype=int)
Peaks = (YM[inds[1]] - (flat[inds[2]] - flat[inds[0]]) /
(2. * (flat[inds[2]] - 2. * flat[inds[1]] + flat[inds[0]])))
return Peaks
diff_array = y[1:] - y[:-1]
loc = np.where((diff_array[:-1] > 0.) * (diff_array[1:] < 0.))[0]
peaks = y[loc+1]
std = np.sqrt(biweight_midvariance(y))
loc = loc[peaks > (thresh * std)]+1
peak_loc = get_peaks(y, loc)
peaks = y[np.round(peak_loc).astype(int)]
return peak_loc, peaks/std, peaks
def robust_polyfit(x, y, order=3, niter=3):
sel = y > 0.
ymod = np.polyval(np.polyfit(x[sel], y[sel], order), x)
for i in np.arange(niter):
a = np.abs(y - ymod)
mad = np.median(a)
sel = a < 3. * mad
if sel.sum() > (order+2):
ymod = np.polyval(np.polyfit(x[sel], y[sel], order), x)
return ymod
def count_matches(lines, loc, fib, cnt=5):
found_lines = np.zeros((trace.shape[0], len(lines)))
M = np.zeros((cnt, cnt))
for k in np.arange(cnt):
for j in np.arange(cnt):
i1 = 0 + k
i2 = -1 - j
diff = [loc[fib][i1] - lines['col2'][0],
loc[fib][i2] - lines['col2'][-1]]
m = (diff[1] - diff[0]) / (lines['col2'][-1] - lines['col2'][0])
y = np.array(m * (lines['col2'] - lines['col2'][0]) +
diff[0] + lines['col2'])
for i, line in enumerate(lines):
col = y[i]
v = np.abs(col - loc[fib])
if np.min(v) < 3.:
found_lines[fib, i] = loc[fib][np.argmin(v)]
M[k, j] = (found_lines[fib] > 0.).sum()
return np.unravel_index(np.argmax(M), M.shape)
def find_lines(spectrum, trace, nlines, thresh, fib, side=None):
cont = percentile_filter(spectrum, 15, (1, 101))
spectrum -= cont
loc = []
ph, pr = ([], [])
lines = Table(nlines)
for i, spec in enumerate(spectrum):
px, ps, py = find_peaks(spec, thresh=thresh)
sel = np.abs(px - 1032.) > 0.
loc.append(px[sel])
ph.append(ps[sel])
pr.append(py[sel])
if side == 'orange':
names = ['Hg', 'Cd']
v = []
for name in names:
selhg = lines['col4'] == name
ma = np.argmax(arc_lines['col3'][selhg])
sel = np.abs(loc[fib] - lines['col2'][selhg][ma]) < 50.
v1 = np.max(pr[fib][sel])
v2 = lines['col3'][selhg][ma]
v.append([v1, v2])
selhg = lines['col4'] == name
if v[0][0] > v[1][0]:
selhg = lines['col4'] == 'Hg'
ma = np.argmax(arc_lines['col3'][selhg])
mxv = lines['col3'][selhg][ma]
lines['col3'][selhg] *= 1. / mxv
selhg = (lines['col4'] == 'Cd') + (lines['col4'] == 'Ar')
ma = np.argmax(arc_lines['col3'][selhg])
mxv = lines['col3'][selhg][ma]
nrt = v[1][0] / v[0][0]
lines['col3'][selhg] *= nrt / mxv
else:
selhg = (lines['col4'] == 'Cd') + (lines['col4'] == 'Ar')
ma = np.argmax(arc_lines['col3'][selhg])
mxv = lines['col3'][selhg][ma]
lines['col3'][selhg] *= 1. / mxv
selhg = lines['col4'] == 'Hg'
ma = np.argmax(arc_lines['col3'][selhg])
mxv = lines['col3'][selhg][ma]
nrt = v[0][0] / v[1][0]
lines['col3'][selhg] *= nrt / mxv
found_lines = np.zeros((trace.shape[0], len(lines)))
ls = np.argsort(lines['col3'])[::-1]
if side == 'farred':
distthresh = 15.
else:
distthresh = 50.
sel = np.abs(loc[fib] - lines['col2'][ls[0]]) < distthresh
ind = np.where(sel)[0][np.argmax(pr[fib][sel])]
off = loc[fib][ind] - lines['col2'][ls[0]]
found_lines[fib, ls[0]] = loc[fib][ind]
y = lines['col2'] + off
s = found_lines[fib] * 0.
pp = s * 0.
pph = s * 0.
s[ls[0]] = 1.
pp[ls[0]] = 0.
for l in ls[1:]:
guess = y[l]
v = np.abs(guess - loc[fib])
ER = lines['col3'][l] / lines['col3'][ls[0]]
MR = pr[fib] / pr[fib][ind]
EE = MR * np.sqrt(1./ph[fib]**2 + 1./ph[fib][ind])
EE = np.max([EE, .1 * MR, 0.001 * np.ones(MR.shape)], axis=0)
dist = v/2. + np.abs(ER - MR) / EE / 2.
if np.min(dist) < 10.:
ind1 = np.argmin(dist)
found_lines[fib, l] = loc[fib][ind1]
ll = np.where(found_lines[fib] > 0.)[0][0]
lh = np.where(found_lines[fib] > 0.)[0][-1]
diff = [found_lines[fib, ll] - lines['col2'][ll],
found_lines[fib, lh] - lines['col2'][lh]]
m = ((diff[1] - diff[0]) /
(lines['col2'][lh] - lines['col2'][ll]))
y = np.array(m * (lines['col2'] - lines['col2'][ll]) +
diff[0] + lines['col2'])
s[l] = MR[ind1]
pp[l] = dist[ind1]
pph[l] = ph[fib][ind1]
inds = np.where(found_lines[fib] > 0.)[0]
delv = []
for ind in inds:
sel = np.where(found_lines[fib, ind] == found_lines[fib, inds])[0]
if len(sel)>1:
if np.any(pp[ind] > pp[inds[sel]]):
delv.append(ind)
found_lines[fib, ind] = 0.
inds = np.delete(inds, delv)
for ind in inds:
print(lines['col1'][ind], lines['col2'][ind], found_lines[fib][ind],
lines['col3'][ind], s[ind], pp[ind], pph[ind])
for i, line in enumerate(lines):
if found_lines[fib, i] == 0.:
continue
for j in np.arange(0, fib)[::-1]:
if len(loc[j]) < 1:
continue
k = j + 1
v = found_lines[k, i]
while (v == 0.) and (k < trace.shape[0]):
k += 1
v = found_lines[k, i]
m = np.abs(loc[j] - v)
if np.min(m) < 2.0:
found_lines[j, i] = loc[j][np.argmin(m)]
for j in np.arange(fib+1, trace.shape[0]):
if len(loc[j]) < 1:
continue
k = j - 1
v = found_lines[k, i]
while (v == 0.) and (k >= 0):
k -= 1
v = found_lines[k, i]
m = np.abs(loc[j] - v)
if np.min(m) < 2.0:
found_lines[j, i] = loc[j][np.argmin(m)]
return found_lines
def get_wavelength_from_arc(image, trace, lines, side, amp, date, otherimage=None):
spectrum = get_spectra(image, trace)
fib = np.argmax(np.median(spectrum, axis=1))
if side == 'uv' and date > 20161101:
thresh = 5. # 5
spectrum2 = spectrum*0.
fib = trace.shape[0] / 2
for i in np.arange(trace.shape[0]):
ll = int(np.max([0, i-4]))
hl = int(np.min([trace.shape[0], i+5]))
spectrum2[i] = np.median(spectrum[ll:hl], axis=0)
G = Gaussian1DKernel(1.5)
spectrum2[i] = convolve(spectrum2[i], G)
spectrum = spectrum2 * 1.
spectrum1 = get_spectra(otherimage, trace)
spectrum2 = spectrum1*0.
fib = trace.shape[0] / 2
for i in np.arange(trace.shape[0]):
ll = int(np.max([0, i-4]))
hl = int(np.min([trace.shape[0], i+5]))
spectrum2[i] = np.median(spectrum1[ll:hl], axis=0)
G = Gaussian1DKernel(1.5)
spectrum2[i] = convolve(spectrum2[i], G)
spectrum1 = spectrum2 * 1.
fib = int(trace.shape[0] / 2)
found_lines = find_lines(spectrum, trace, lines, thresh, fib)
found_lines1 = find_lines(spectrum1, trace, lines, thresh, fib)
sel = (found_lines > 0.) * (found_lines1 > 0.)
for i in np.arange(found_lines.shape[0]):
found_lines[i] = (found_lines1[i] +
np.median(found_lines[i][sel[i]] -
found_lines1[i][sel[i]]))
found_lines[i][found_lines1[i] == 0.] = 0.
else:
thresh = 3.
found_lines = find_lines(spectrum, trace, lines, thresh, fib, side)
x = np.arange(trace.shape[1])
found_lines[found_lines > 2060] = 0.
found_lines1 = found_lines * 1.
#fits.PrimaryHDU(found_lines).writeto('fl_%s_%s.fits' % (side, amp), overwrite=True)
qft = np.zeros((len(lines),))
for i, line in enumerate(lines):
if np.sum(found_lines[:, i]) < (0.5 * trace.shape[0]):
found_lines[:, i] = 0.0
continue
ind = np.array(found_lines[:, i], dtype=int)
xt = trace[np.arange(trace.shape[0]), ind]
yt = robust_polyfit(xt, found_lines[:, i])
sel = found_lines1[:, i] > 0.
qft[i] = np.std(found_lines1[sel, i] - yt[sel])
if qft[i] > 0.25:
found_lines[:, i] = 0.0
continue
found_lines[:, i] = yt
wave = trace * 0.0
res = np.zeros((trace.shape[0],))
Res = np.zeros(found_lines.shape)
for j in np.arange(trace.shape[0]):
sel = found_lines[j, :] > 0.0
if sel.sum() < 3:
continue
wave[j] = np.polyval(np.polyfit(found_lines[j, sel],
lines['col1'][sel], 3), x)
res[j] = np.std(np.interp(found_lines[j, sel], x, wave[j]) -
lines['col1'][sel])
Res[j, sel] = (np.interp(found_lines1[j, sel], x, wave[j]) -
lines['col1'][sel])
#fits.PrimaryHDU(Res).writeto('Rl_%s_%s.fits' % (side, amp), overwrite=True)
missing = np.where(np.all(wave == 0., axis=1))[0]
if len(missing):
good = np.where(~np.all(wave == 0., axis=1))[0]
for j in np.arange(trace.shape[1]):
x = trace[good, j]
y = wave[good, j]
wave[missing, j] = np.polyval(np.polyfit(x, y, 3),
trace[missing, j])
log.info('Min, Max Wave: %0.2f, %0.2f' % (wave.min(), wave.max()))
log.info('Mean Res, Median Res: %0.3f, %0.3f' % (np.mean(res),
np.median(res)))
return wave
def get_objects(basefiles, attrs, full=False):
s = []
for fn in basefiles:
tarname = get_tarname_from_filename(fn)
t = tarfile.open(tarname, 'r')
F = fits.open(t.extractfile('/'.join(fn.split('/')[-4:])))
s.append([])
for att in attrs:
s[-1].append(F[0].header[att])
if full:
area = get_mirror_illumination_guider(fn, s[-1][1])
try:
throughput = get_throughput(fn, s[-1][1])
except:
log.warning('Problem with throughput for %s' % fn)
throughput = 1.0
s[-1].append(area)
s[-1].append(throughput)
t.close()
return s
def create_image_header(wave, xgrid, ygrid, zgrid, func=fits.ImageHDU):
hdu = func(np.array(zgrid, dtype='float32'))
hdu.header['CRVAL1'] = xgrid[0, 0]
hdu.header['CRVAL2'] = ygrid[0, 0]
hdu.header['CRPIX1'] = 1
hdu.header['CRPIX2'] = 1
hdu.header['CTYPE1'] = 'pixel'
hdu.header['CTYPE2'] = 'pixel'
hdu.header['CDELT1'] = xgrid[0, 1] - xgrid[0, 0]
hdu.header['CDELT2'] = ygrid[1, 0] - ygrid[0, 0]
return hdu
def create_header_objection(wave, image, func=fits.ImageHDU):
hdu = func(np.array(image, dtype='float32'))
hdu.header['CRVAL1'] = wave[0]
hdu.header['CRVAL2'] = 1
hdu.header['CRPIX1'] = 1
hdu.header['CRPIX2'] = 1
hdu.header['CTYPE1'] = 'pixel'
hdu.header['CTYPE2'] = 'pixel'
hdu.header['CDELT2'] = 1
hdu.header['CDELT1'] = wave[1] - wave[0]
return hdu
def correct_ftf(rect, error):
def outlier(y, y1, oi):
m = np.abs(y[oi] - y1[oi])
o = (y - y1) > 3. * np.median(m)
return o
def fit_sky_col(x, y):
o = y == 0.
low = np.percentile(y[~o], 16)
mid = np.percentile(y[~o], 50)
high = np.percentile(y[~o], 84)
flag = False
if (high - mid) > 2.0 * (mid - low):
y1 = np.ones(x[~o].shape) * np.percentile(y[~o], 5)
log.info('Object is too bright for fiber to fiber correction.')
flag = True
else:
y1 = savgol_filter(y[~o], 31, 1)
I = interp1d(x[~o], y1, kind='quadratic', fill_value='extrapolate')
y1 = I(x)
for i in np.arange(3):
o += outlier(y, y1, ~o)
y1 = savgol_filter(y[~o], 51, 1)
I = interp1d(x[~o], y1, kind='quadratic', fill_value='extrapolate')
y1 = I(x)
return y1, o, flag
x = np.arange(rect.shape[0])
y = np.median(rect, axis=1)
f, o, flag = fit_sky_col(x, y)
ftf = f / np.median(f)
if not flag:
return rect / ftf[:, np.newaxis], error / ftf[:, np.newaxis]
else:
return rect, error
def sky_subtraction(rect, error, xloc, yloc):
y = np.median(rect, axis=1)
selg = y != 0.
v = np.percentile(y[selg], 5)
init_sel = selg * (y < v)
init = np.percentile(rect[init_sel], 50, axis=0)
df = np.diff(init)
df = np.hstack([df[0], df])
cont = np.abs(df) < np.percentile(np.abs(df), 25)
G = Gaussian1DKernel(15)
tempy = init * 1.
tempy[~cont] = np.nan
smooth_back = convolve(tempy, G, nan_treatment='interpolate',
preserve_nan=False)
peak_loc, sn, v = find_peaks(init - smooth_back, thresh = 3)
locs = np.round(peak_loc).astype(int)
locs = np.sort(np.hstack([locs-2, locs-1, locs, locs+1, locs+2]))
locs = locs[np.where(locs>=0)[0]]
locs = locs[np.where(locs<2064)[0]]
facs = np.arange(0.7, 1.3, 0.01)
cnt = facs * 0.
sol = np.ones((280,))
for k in np.arange(280):
good = np.zeros(rect[k].shape, dtype=bool)
good[locs] = True
good[error[k] == 0.] = False
if good.sum() > 50.:
for j, i in enumerate(facs):
cnt[j] = (((rect[k] - i * init) * init)[good]).sum()
ind = np.argsort(cnt)
sol[k] = np.interp(0., cnt[ind], facs[ind])
sol[np.abs(sol - 1.3) < 0.01] = 1.
n1 = np.median(sol[:140])
n2 = np.median(sol[140:])
nsol = sol * 1.
nsol[:140] = sol[:140] / n1
nsol[140:] = sol[140:] / n2
fitter = LevMarLSQFitter()
P = Polynomial2D(2)
good = nsol != 0.
fit = fitter(P, xloc[good], yloc[good], nsol[good])
off = np.abs(sol - fit(xloc, yloc))
mad = np.median(off)
good = (nsol != 0.) * (off <= 2. * mad)
fit = fitter(P, xloc[good], yloc[good], nsol[good])
model = fit(xloc, yloc)
model[:140] *= n1
model[140:] *= n2
sky = init * model[:, np.newaxis]
sky[~selg] = 0.
res = 0. * sky
skysub = rect - sky
for j in np.arange(rect.shape[1]):
E = error[:, j] * 1.
E[E == 0.] = 1e9
W = 1. / E**2
W = np.sqrt(np.diag(W))
A = model[:, np.newaxis]
B = skysub[:, j]
Aw = np.dot(W, A)
Bw = np.dot(B, W)
sol = np.linalg.lstsq(Aw, Bw)[0][0]
sg = np.sign(sol)
V = [np.abs(sol), 0.5 * np.median(E)]
mult = V[np.argmin(V)] * sg
res[:, j] = mult
return sky + res
def make_frame(xloc, yloc, data, error, wave, dw, Dx, Dy, wstart=5700.,
wend=5800., scale=0.4, seeing_fac=1.3):
seeing = seeing_fac * scale
a, b = data.shape
x = np.arange(xloc.min()-scale,
xloc.max()+1*scale, scale)
y = np.arange(yloc.min()-scale,
yloc.max()+1*scale, scale)
xgrid, ygrid = np.meshgrid(x, y)
zgrid = np.zeros((b,)+xgrid.shape)
area = 3. / 4. * np.sqrt(3.) * 0.59**2
for k in np.arange(b):
sel = np.isfinite(data[:, k]) * (error[:, k] != 0.)
D = np.sqrt((xloc[:, np.newaxis, np.newaxis] - Dx[k] - xgrid)**2 +
(yloc[:, np.newaxis, np.newaxis] - Dy[k] - ygrid)**2)
W = np.exp(-0.5 / (seeing/2.35)**2 * D**2)
zgrid[k, :, :] = ((data[sel, k][:, np.newaxis, np.newaxis] *
W[sel]).sum(axis=0) / W[sel].sum(axis=0) *
(scale**2 / area))
wi = np.searchsorted(wave, wstart, side='left')
we = np.searchsorted(wave, wend, side='right')
zimage = np.median(zgrid[wi:we+1], axis=(0,))
return zgrid, zimage, xgrid, ygrid
def write_cube(wave, xgrid, ygrid, zgrid, outname, he):
hdu = fits.PrimaryHDU(np.array(zgrid, dtype='float32'))
hdu.header['CRVAL1'] = xgrid[0, 0]
hdu.header['CRVAL2'] = ygrid[0, 0]
hdu.header['CRVAL3'] = wave[0]
hdu.header['CRPIX1'] = 1
hdu.header['CRPIX2'] = 1
hdu.header['CRPIX3'] = 1
hdu.header['CTYPE1'] = 'pixel'
hdu.header['CTYPE2'] = 'pixel'
hdu.header['CTYPE3'] = 'pixel'
hdu.header['CDELT1'] = xgrid[0, 1] - xgrid[0, 0]
hdu.header['CDELT2'] = ygrid[1, 0] - ygrid[0, 0]
hdu.header['CDELT3'] = wave[1] - wave[0]
for key in he.keys():
if key in hdu.header:
continue
if ('CCDSEC' in key) or ('DATASEC' in key):
continue
if ('BSCALE' in key) or ('BZERO' in key):
continue
try:
hdu.header[key] = he[key]
except:
continue
hdu.writeto(outname, overwrite=True)
def build_weight_matrix(x, y, sig=1.5):
d = np.sqrt((x - x[:, np.newaxis])**2 + (y - y[:, np.newaxis])**2)
G = np.exp(-0.5 * (d / sig)**2)
G = G / G.sum(axis=0)[:, np.newaxis]
return G.swapaxes(0, 1)
def mask_skylines_cosmics(wave, rect_spec, name, error):
mask1 = rect_spec * 0.
if op.exists(op.join(DIRNAME, 'lrs2_config', '%s_skylines.dat' % name)):
T = Table.read(op.join(DIRNAME, 'lrs2_config', '%s_skylines.dat' % name),
format='ascii.fixed_width_two_line')
for w in T['wavelength']:
mask1[:, np.abs(wave - w) < 6.] = -1.
mask2 = rect_spec * 0.
mask2[error == 0.] = -1.
mask2[1:, :] += mask2[:-1, :]
mask2[:-1, :] += mask2[1:, :]
if name == 'uv':
mask1[79:83, 979:987] = -1.
mask = (mask1 + mask2) < 0
return mask
def get_all_cosmics(x, y, ispec, error):
D = np.sqrt((x - x[:, np.newaxis])**2 + (y - y[:, np.newaxis])**2)
for i in np.arange(D.shape[0]):
D[i, :] = np.array(D[i, :] < 1.5, dtype=float)
ispec[error==0.] = 0.
T = ispec * 1.
for i in np.arange(ispec.shape[1]):
T[:, i] = np.dot(ispec[:, i], D)
YY = ispec / T
YY[np.isnan(YY)] = 0.
return YY > 0.2
def convolve_spatially(x, y, spec, wave, name, error, ispec, sig_spatial=0.75,
sig_wave=1.5):
W = build_weight_matrix(x, y, sig=sig_spatial)
D = np.sqrt((x - x[:, np.newaxis])**2 + (y - y[:, np.newaxis])**2)
for i in np.arange(D.shape[0]):
D[i, :] = np.array(D[i, :] < 1.5, dtype=float)
mask = mask_skylines_cosmics(wave, spec, name, error)
Z = spec * 1.
E = error**2
Z[mask] = np.nan
E[mask] = np.nan
ispec[mask] = 0.
T = ispec * 1.
for i in np.arange(ispec.shape[1]):
T[:, i] = np.dot(ispec[:, i], D)
YY = ispec / T
YY[np.isnan(YY)] = 0.
Z[YY > 0.2] = np.nan
E[YY > 0.2] = np.nan
G = Gaussian1DKernel(sig_wave)
for i in np.arange(spec.shape[0]):
Z[i, :] = convolve(Z[i, :], G, nan_treatment='fill', fill_value=0.0)
E[i, :] = convolve(E[i, :], G, nan_treatment='fill', fill_value=0.0)
Z_copy = Z * 1.
E_copy = np.sqrt(E)
T = spec * 0.
for i in np.arange(spec.shape[1]):
Z[:, i] = np.dot(Z[:, i], W)
E[:, i] = np.dot(E[:, i], W)
E[:] = np.sqrt(E)
Y = Z * 0.
sel = E > 0.
Y[sel] = Z[sel] / E[sel]
Y[~np.isfinite(Y)] = 0.
ind = np.unravel_index(np.nanargmax(Y[:, 50:-50],
axis=None), Z[:, 50:-50].shape)
l1 = ind[1] + 50 - 25
l2 = ind[1] + 50 + 26
return ind[1]+50, Z_copy[:, l1:l2], E_copy[:, l1:l2]
def find_source(dx, dy, skysub, commonwave, obj, specn, error,
xoff, yoff, wave_0, ispec):
D = np.sqrt((dx - dx[:, np.newaxis])**2 + (dy - dy[:, np.newaxis])**2)
loc, sdimage, sderror = convolve_spatially(dx, dy, skysub, commonwave,
specn, error, ispec*1.,
sig_wave=1.5)
BN = int(sdimage.shape[1] / 2)
kSN = 0.
for k in np.arange(BN):
k = int(k)
dimage = np.sum(sdimage[:, (BN-k):(BN+k+1)], axis=1)
derror = np.sqrt(np.sum(sderror[:, (BN-k):(BN+k+1)]**2, axis=1))
sn = dimage * 0.
for i in np.arange(len(dimage)):
sel = D[i, :] < 1.5
S = np.sum(dimage[sel])
N = np.sqrt(np.sum(derror[sel]**2))
sn[i] = S / N
SN = np.nanmax(sn)
if kSN > SN:
break
else:
kSN = SN * 1.
kind = 'Emission'
if args.model_dar:
D = get_standard_star_params(skysub, commonwave, calinfo[5][:, 0],
calinfo[5][:, 1])
xc, yc, xstd, ystd, xoff, yoff = D
log.info('%s, %s: Source found at s/n: %0.2f' % (obj, specn, SN))
return xc, yc, xstd, ystd, xoff, yoff
if SN > 5.:
ind = np.argmax(dimage)
dist = np.sqrt((dx - dx[ind])**2 + (dy - dy[ind])**2)
inds = dist < 1.5
x_centroid = np.sum(dimage[inds] * dx[inds]) / np.sum(dimage[inds])
y_centroid = np.sum(dimage[inds] * dy[inds]) / np.sum(dimage[inds])
X = np.ones(commonwave.shape)
G = Gaussian2D()
fitter = LevMarLSQFitter()
G.amplitude.value = dimage[ind]
G.x_mean.value = x_centroid
G.y_mean.value = y_centroid
fit = fitter(G, dx[inds], dy[inds], dimage[inds])
seeing = 2.35 * np.sqrt(fit.x_stddev * fit.y_stddev)
if seeing < 0.75:
log.info('%s, %s: %s source found at s/n: %0.2f but rejected for being too small, col: %i' % (obj, specn, kind, SN, loc))
return None
else:
log.info('%s, %s: %s source found at s/n: %0.2f, with fwhm: %0.2f' % (obj, specn, kind, SN, seeing))
xoff = xoff - xoff[loc]
yoff = yoff - yoff[loc]
return x_centroid, y_centroid, fit.x_stddev.value*X, fit.y_stddev.value * X, xoff, yoff
else:
log.info('%s, %s: No source found, s/n too low: %0.2f' % (obj, specn, SN))
return None
def get_standard_star_params(data, commonwave, xloc, yloc):
G = Gaussian2D()
fitter = LevMarLSQFitter()
wchunk = np.array([np.mean(chunk)
for chunk in np.array_split(commonwave, 11)])
dchunk = [np.median(chunk, axis=1)
for chunk in np.array_split(data, 11, axis=1)]
xc, yc, xs, ys = [i * wchunk for i in [0., 0., 0., 0.]]
for i in np.arange(11):
y = dchunk[i]
ind = np.argmax(y)
dist = np.sqrt((xloc - xloc[ind])**2 + (yloc - yloc[ind])**2)
inds = dist < 3.
x_centroid = np.sum(y[inds] * xloc[inds]) / np.sum(y[inds])
y_centroid = np.sum(y[inds] * yloc[inds]) / np.sum(y[inds])
G.amplitude.value = y[ind]
G.x_mean.value = x_centroid
G.y_mean.value = y_centroid
fit = fitter(G, xloc[inds], yloc[inds], y[inds])
xc[i] = fit.x_mean.value * 1.
yc[i] = fit.y_mean.value * 1.
xs[i] = fit.x_stddev.value * 1.
ys[i] = fit.y_stddev.value * 1.
sel = xs > 0.
xoff = np.polyval(np.polyfit(wchunk[sel], xc[sel], 2), commonwave)
yoff = np.polyval(np.polyfit(wchunk[sel], yc[sel], 2), commonwave)
xstd = np.median(xs[sel]) * np.ones(commonwave.shape)
ystd = np.median(ys[sel]) * np.ones(commonwave.shape)
N = len(commonwave)
return xoff[N/2], yoff[N/2], xstd, ystd, xoff - xoff[N/2], yoff - yoff[N/2]
def get_bigarray(xloc, yloc):
BigX = [xloc]
BigY = [yloc]
uy = np.unique(yloc)
dy = np.mean(np.diff(uy))
for i in np.arange(1, 10):
ny = dy + np.max(np.hstack(BigY))
x = np.hstack(BigX)[np.where(uy[-2] == np.hstack(BigY))[0]]
y = ny * np.ones(x.shape)
BigY.append(y)
BigX.append(x)
uy = np.unique(np.hstack(BigY))
ny = -dy + np.min(np.hstack(BigY))
x = np.hstack(BigX)[np.where(uy[1] == np.hstack(BigY))[0]]
y = ny * np.ones(x.shape)
BigY.append(y)
BigX.append(x)
uy = np.unique(np.hstack(BigY))
BigX = np.hstack(BigX)
BigY = np.hstack(BigY)
uy = np.unique(BigY)
NX, NY = ([BigX], [BigY])
for i in uy:
sel = np.where(i == BigY)[0]
dx = np.abs(np.mean(np.diff(BigX[sel])))
xn = np.min(BigX[sel]) - np.arange(1, 10)*dx
xn2 = np.max(BigX[sel]) + np.arange(1, 10)*dx
yn = i * np.ones(xn.shape)
yn2 = i * np.ones(xn2.shape)
NX.append(xn)
NX.append(xn2)
NY.append(yn)
NY.append(yn2)
BigX = np.hstack(NX)
BigY = np.hstack(NY)
M = np.zeros(BigX.shape, dtype=bool)
inds = np.zeros(xloc.shape, dtype=int)
for i in np.arange(len(xloc)):
ind = np.where((xloc[i] == BigX) * (yloc[i] == BigY))[0]
M[ind] = True
inds[i] = ind
return BigX, BigY
def extract_source(data, xc, yc, xoff, yoff, wave, xloc, yloc, error,
xstd, ystd):
PSF = Gaussian2D()
spec = wave * 0.
serror = wave * 0.
weights = data * 0.
mask = data * 0.
bigX, bigY = get_bigarray(xloc, yloc)
for i in np.arange(len(wave)):
x = xc + xoff[i]
y = yc + yoff[i]
PSF.x_mean.value = x
PSF.y_mean.value = y
PSF.x_stddev = xstd[i]
PSF.y_stddev = ystd[i]
seeing = np.sqrt(ystd[i]*xstd[i])
W = PSF(xloc, yloc)
S = PSF(bigX, bigY).sum()
W /= S
M = (error[:, i] != 0.) * (np.sqrt((xloc-x)**2 + (yloc-y)**2) < seeing*2.5)
weights[:, i] = W
mask[:, i] = M
spec[i] = (data[:, i] * W * M).sum() / (M * W**2).sum()
serror[i] = np.sqrt((error[:, i]**2 * W * M).sum() / (M * W**2).sum())
return spec, serror, weights, mask
def get_mirror_illumination(fn=None, default=51.4e4):
''' Use hetillum from illum_lib to calculate mirror illumination (cm^2) '''
#log.info('Getting mirror illumination')
try:
F = fits.open(fn)
names = ['RHO_STRT', 'THE_STRT', 'PHI_STRT', 'X_STRT', 'Y_STRT']
r, t, p, x, y = [F[0].header[name] for name in names]
# log.info('Rho, Theta, Phi, X, Y: %0.4f, %0.4f, %0.4f, %0.4f, %0.4f' %
# (r, t, p, x, y))
mirror_illum = float(os.popen('/work/03730/gregz/maverick/illum_lib/hetillum -p'
' -x "[%0.4f,%0.4f,%0.4f]" "[%0.4f,%0.4f]" 256' %
(x, y, p, 0.042, 0.014)).read().split('\n')[0])
area = mirror_illum * default
except:
log.info('Using default mirror illumination value')
area = default
# log.info('Mirror illumination: %0.2f m^2' % (area/1e4))
return area
def panstarrs_query(ra_deg, dec_deg, rad_deg, mindet=1,
maxsources=30000,
server=('https://archive.stsci.edu/panstarrs/search.php')):
"""
Query Pan-STARRS DR1 @ MAST
parameters: ra_deg, dec_deg, rad_deg: RA, Dec, field
radius in degrees
mindet: minimum number of detection (optional)
maxsources: maximum number of sources
server: servername
returns: astropy.table object
"""
r = requests.get(server, params={'RA': ra_deg, 'DEC': dec_deg,
'SR': rad_deg, 'max_records': maxsources,
'outputformat': 'VOTable',
'ndetections': ('>%d' % mindet)})
# write query data into local file
name = str(uuid.uuid4()) + '.xml'
outf = open(name, 'w')
outf.write(r.text)
outf.close()
# parse local file into astropy.table object
data = parse_single_table(name)
os.remove(name)
return data.to_table(use_names_over_ids=True)
def truncate_list(lst):
if len(lst) <= 5:
return lst # If the list already has 5 or fewer elements, return it as is.
# Calculate indices for the three evenly spaced elements in the middle.
step = (len(lst) - 1) / 4
indices = [0, round(step), round(2 * step), round(3 * step), len(lst) - 1]
# Select elements at the calculated indices
return [lst[i] for i in indices]
def get_mirror_illumination_guider(fn, exptime, default=51.4e4,
path='/work/03946/hetdex/maverick'):
try:
M = []
path = op.join(path, args.date)
f = op.basename(fn)
DT = f.split('_')[0]
y, m, d, h, mi, s = [int(x) for x in [DT[:4], DT[4:6], DT[6:8], DT[9:11],
DT[11:13], DT[13:15]]]
d0 = datetime(y, m, d, h, mi, s)
tarfolder = op.join(path, 'gc1', '*.tar')
tarfolder = glob.glob(tarfolder)
if len(tarfolder) == 0:
area = 51.4e4
log.info('Using default mirror illumination: %0.2f m^2' % (area/1e4))
return area
T = tarfile.open(tarfolder[0], 'r')
init_list = sorted([name for name in T.getnames()
if name[-5:] == '.fits'])
final_list = []
for t in init_list:
DT = op.basename(t).split('_')[0]
y, m, d, h, mi, s = [int(x) for x in [DT[:4], DT[4:6], DT[6:8],
DT[9:11], DT[11:13], DT[13:15]]]
d = datetime(y, m, d, h, mi, s)
p = (d - d0).seconds
if (p > -10.) * (p < exptime+10.):
final_list.append(t)
final_list = truncate_list(final_list)
for fn in final_list:
fobj = T.extractfile(T.getmember(fn))
M.append(get_mirror_illumination(fobj))
M = np.array(M)
sel = M != 51.4e4
if sel.sum() > 0.:
area = np.mean(M[sel])
else:
area = 51.4e4
log.info('Final Mirror illumination: %0.2f m^2' % (area/1e4))
return area
except:
log.info('Using default mirror illumination: %0.2f m^2' % (default/1e4))
return default
def get_throughput(fn, exptime, path='/work/03946/hetdex/maverick'):
attr = ['GUIDLOOP', 'MJD', 'TRANSPAR']
M = []
path = op.join(path, args.date)
f = op.basename(fn)
DT = f.split('_')[0]
y, m, d, h, mi, s = [int(x) for x in [DT[:4], DT[4:6], DT[6:8], DT[9:11],
DT[11:13], DT[13:15]]]
d0 = datetime(y, m, d, h, mi, s)
for gp in ['gc1', 'gc2']:
tarfolder = op.join(path, gp, '%s.tar' % gp)
T = tarfile.open(tarfolder, 'r')
init_list = sorted([name for name in T.getnames()
if name[-5:] == '.fits'])
final_list = []
for t in init_list:
DT = op.basename(t).split('_')[0]
y, m, d, h, mi, s = [int(x) for x in [DT[:4], DT[4:6], DT[6:8],
DT[9:11], DT[11:13], DT[13:15]]]
d = datetime(y, m, d, h, mi, s)
p = (d - d0).seconds
if (p > -10.) * (p < exptime+10.):
final_list.append(t)
for fnt in final_list:
fobj = T.extractfile(T.getmember(fnt))
f = fits.open(fobj)
if f[1].header['GUIDLOOP'] == 'ACTIVE':
M.append([])
for att in attr:
M[-1].append(f[1].header[att])
throughput = np.zeros((len(M),))
for i, mi in enumerate(M):
if len(mi) < 2:
continue
if mi[2] > 0.:
throughput[i] = mi[2]
t = np.mean(throughput[throughput>0.0])
if np.isnan(t):
log.warning('Could not find TRANSPAR measurments')
t = 1.0
if t > 1.1:
log.info('The throughput for %s is %0.2f is too high, setting to 1.0' % (fn, t))
t = 1.0
if t < 0.1:
log.info('The throughput for %s is %0.2f is too high, setting to 1.0' % (fn, t))
t = 1.0
log.info('Throughput for %s is %0.2f' % (fn, t))
return t
def check_if_standard(objname):
for standard in standard_names:
if standard.lower() in objname.lower():
return True
return False
def fit_response_cont(wv, sky, skip=5, fil_len=95, func=np.array):
skym_s = 1. * sky
sky_sm = savgol_filter(skym_s, fil_len, 1)
allind = np.arange(len(wv), dtype=int)
y = np.abs(np.diff(np.hstack([sky[0], sky])))
sel = np.where(y > 1.5 * np.median(sky))[0]
for j in np.arange(1, skip+1):
sel = np.union1d(sel, sel + 1)
sel = np.union1d(sel, sel - 1)
sel = np.sort(np.unique(sel))
sel = sel[skip:-skip]
good = np.setdiff1d(allind, sel)
skym_s = 1.*sky
skym_s[sel] = np.interp(wv[sel], wv[good], sky_sm[good])
sky_sm = savgol_filter(skym_s, fil_len, 1)
for i in np.arange(5):
mad = np.median(np.abs(sky - sky_sm))
outlier = func(sky - sky_sm) < -1.5 * mad
sel = np.where(outlier)[0]
for j in np.arange(1, skip+1):
sel = np.union1d(sel, sel + 1)
sel = np.union1d(sel, sel - 1)
sel = np.sort(np.unique(sel))
sel = sel[skip:-skip]
good = np.setdiff1d(allind, sel)
skym_s = 1.*sky
skym_s[sel] = np.interp(wv[sel], wv[good], sky_sm[good])
sky_sm = savgol_filter(skym_s, fil_len, 1)
return sky_sm
def get_response(objname, commonwave, spec, specname):
for standard in standard_names:
if standard.lower() in objname.lower():
filename = op.join('/work/03946/hetdex/maverick/virus_config/'
'standards',
'm' + standard.lower() + '.dat.txt')
wave, standardmag = np.loadtxt(filename, usecols=(0, 1),
unpack=True)
fnu = 10**(0.4 * (-48.6 - standardmag))
standard_flam = fnu * 2.99792e18 / wave**2
standard_wave = wave
flam = np.interp(commonwave, standard_wave, standard_flam)
cont = fit_response_cont(commonwave, spec / flam, fil_len=11)
return 1. / cont
return None
def big_reduction(obj, bf, instrument, sci_obs, calinfo, amps, commonwave,
ifuslot, specname, standard=False, response=None):
log.info('Extracting %s from %s' % (obj[0], bf))
#scifiles = op.join(op.dirname(bf.replace('exp01', 'exp*')), '*%sLL*.fits' % ifuslot)
scifiles = op.join(op.dirname(bf), '*%sLL*.fits' % ifuslot)
images, rect, spec, cos, fl, Fi, E, header = extract_sci(scifiles, amps, calinfo[2],
calinfo[1], calinfo[0], calinfo[3],
calinfo[4], calinfo[5])
cnt = 1
if args.central_wave is None:
wave_0 = np.mean(commonwave)
wb = 50.
else:
wave_0 = args.central_wave
wb = args.wavelength_bin
darfile = op.join(DIRNAME, 'lrs2_config/dar_%s.dat' % specinit)
T = Table.read(darfile, format='ascii.fixed_width_two_line')
xoff = (np.interp(commonwave, T['wave'], T['x_0']) -
np.interp(wave_0, T['wave'], T['x_0']))
yoff = (np.interp(commonwave, T['wave'], T['y_0']) -
np.interp(wave_0, T['wave'], T['y_0']))
for im, r, s, c, fli, Fii, e, he in zip(images, rect, spec, cos,
fl, Fi, E, header):
# try:
try:
basename = 'LRS2/' + he['QPROG']
except:
if check_if_standard(obj[0]) and (ifuslot in obj[0]):
basename = 'LRS2/STANDARDS'
else:
basename = 'LRS2/ORPHANS'
mkpath(basename)
pos = np.zeros((len(calinfo[5]), 6))
pos[:, 0:2] = calinfo[5]
try:
PA = float(he['PARANGLE'])
RA = float(he['TRAJRA'])
DEC = float(he['TRAJDEC'])
log.info('Observation at %0.4f %0.4f, PA: %0.3f' % (RA, DEC, PA))
A = Astrometry(RA, DEC, PA, 0., 0., fplane_file=fplane_file)
ra, dec = A.get_ifupos_ra_dec(ifuslot, calinfo[5][:, 0],
calinfo[5][:, 1])
fpx = A.fplane.by_ifuslot(ifuslot).y + calinfo[5][:, 0]
fpy = A.fplane.by_ifuslot(ifuslot).x + calinfo[5][:, 1]
pos[:, 2] = fpx
pos[:, 3] = fpy
pos[:, 4] = ra
pos[:, 5] = dec
except:
log.warning('Astrometry Issue')
fn = op.join(op.dirname(bf.replace('exp01', 'exp%02d' % cnt)), '*%sLL*.fits' % ifuslot)
fn = get_filenames_from_tarfolder(get_tarname_from_filename(fn),
fn)
mini = get_objects(fn, ['OBJECT', 'EXPTIME'], full=True)
log.info('Subtracting sky %s, exp%02d' % (obj[0], cnt))
r[calinfo[6][:, 1] == 1.] = 0.
e[calinfo[6][:, 1] == 1.] = 0.
r /= mini[0][1]
r /= mini[0][2]
r /= mini[0][3]
e /= mini[0][1]
e /= mini[0][2]
e /= mini[0][3]
if args.correct_ftf:
r, e = correct_ftf(r, e)
bad = get_all_cosmics(pos[:, 0], pos[:, 1], r*1., e * 1.)
e[bad] = 0.
sky = sky_subtraction(r, e, pos[:, 0], pos[:, 1])
sky[calinfo[6][:, 1] == 1.] = 0.
skysub = r - sky
if response is not None:
r *= response
e *= response
sky *= response
skysub *= response
X = np.array([T['wave'], T['x_0'], T['y_0']])
for S, name in zip([r, sky, skysub], ['obs', 'sky', 'skysub']):
outname = ('%s_%s_%s_%s_%s_cube.fits' % (args.date, sci_obs,
'exp%02d' % cnt, specname, name))
outname = op.join(basename, outname)
zcube, zimage, xgrid, ygrid = make_frame(calinfo[5][:, 0],
calinfo[5][:, 1], S, e,
commonwave,
T['wave'],
xoff, yoff,
wstart=wave_0-wb,
wend=wave_0+wb)
write_cube(commonwave, xgrid, ygrid, zcube, outname, he)
loc = None
if args.source_x is None:
wi = np.searchsorted(commonwave, wave_0-wb, side='left')
we = np.searchsorted(commonwave, wave_0+wb, side='right')
dimage = np.median(skysub[:, wi:we+1], axis=1)
derror = np.sqrt(np.sum(e[:, wi:we+1]**2, axis=1))*1.253 / np.sqrt(we-wi+1)
loc1 = find_source(pos[:, 0], pos[:, 1],
skysub, commonwave, obj[0], specname, e,
xoff, yoff, wave_0, r)
if loc1 is not None:
loc = [0., 0., 0.]
loc[0] = loc1[0]
loc[1] = loc1[1]
loc[2] = 2.35 * np.mean(np.sqrt(loc1[2]*loc1[3]))
xstd = loc1[2]
ystd = loc1[3]
xoff = loc1[4]
yoff = loc1[4]
log.info('Source seeing initially found to be: %0.2f' % loc[2])
if args.source_x is not None:
loc = [args.source_x, args.source_y, 1.5]
xstd = np.ones(commonwave.shape) * 0.75
ystd = np.ones(commonwave.shape) * 0.75
if loc is not None:
log.info('Source found at %0.2f, %0.2f' % (loc[0], loc[1]))
skyspec, errorskyspec, w, m = extract_source(sky, loc[0], loc[1], xoff,
yoff, commonwave,
calinfo[5][:, 0],
calinfo[5][:, 1], e,
xstd, ystd)
skysubspec, errorskysubspec, w, m = extract_source(skysub, loc[0],
loc[1], xoff, yoff,
commonwave,
calinfo[5][:, 0],
calinfo[5][:, 1], e,
xstd, ystd)
else:
skyspec = commonwave * 0.
skysubspec = commonwave * 0.
errorskyspec = commonwave * 0.
errorskysubspec = commonwave * 0.
if response is not None:
f5 = np.vstack([commonwave, skysubspec, skyspec,
errorskysubspec, errorskyspec,
response])
else:
f5 = np.vstack([commonwave, skysubspec, skyspec,
errorskysubspec, errorskyspec,
np.ones(commonwave.shape)])
f1 = create_header_objection(commonwave, r, func=fits.PrimaryHDU)
f2 = create_header_objection(commonwave, sky)
f3 = create_header_objection(commonwave, skysub)
f4 = create_image_header(commonwave, xgrid, ygrid, zimage)
f6 = create_header_objection(commonwave, e)
for key in he.keys():
if key in f1.header:
continue
if 'SEC' in key:
continue
if ('BSCALE' in key) or ('BZERO' in key):
continue
try:
f1.header[key] = he[key]
except:
continue
if loc is not None:
f1.header['SOURCEX'] = loc[0]
f1.header['SOURCEY'] = loc[1]
f1.header['SEEING'] = loc[2]
f1.header['MILLUM'] = mini[0][2]
f1.header['THROUGHP'] = mini[0][3]
names = ['observed_spectra', 'sky_spectra', 'skysub_spectra',
'error_spectra', 'collapsed_image', 'fiber_positions',
'extracted_spectrum', 'adr', 'bigw', 'image',
'flattened_image', 'trace', 'cosmics', 'unrectified_spectra']
flist = [f1, f2, f3, f6, f4, fits.ImageHDU(pos), fits.ImageHDU(f5),
fits.ImageHDU(X), fits.ImageHDU(calinfo[3]),
fits.ImageHDU(im), fits.ImageHDU(fli), fits.ImageHDU(Fii),
fits.ImageHDU(c), fits.ImageHDU(s)]
for fl, name in zip(flist, names):
fl.header['EXTNAME'] = name
outname = ('%s_%s_%s_%s_%s.fits' % ('multi', args.date, sci_obs,
'exp%02d' % cnt, specname))
outname = op.join(basename, outname)
fits.HDUList(flist).writeto(outname, overwrite=True)
outname = ('%s_%s_%s_%s_%s.fits' % ('spectrum', args.date, sci_obs,
'exp%02d' % cnt, specname))
outname = op.join(basename, outname)
f1 = fits.PrimaryHDU(f5)
for key in he.keys():
if key in f1.header:
continue
if 'SEC' in key:
continue
if ('BSCALE' in key) or ('BZERO' in key):
continue
try:
f1.header[key] = he[key]
except:
continue
names = ['wavelength', 'F_lambda', 'Sky_lambda', 'e_F_lambda',
'e_Sky_lambda', 'response']
f1.header['DWAVE'] = commonwave[1] - commonwave[0]
f1.header['WAVE0'] = commonwave[0]
f1.header['WAVESOL'] = 'WAVE0 + DWAVE * linspace(0, NAXIS1)'
f1.header['WAVEUNIT'] = 'A'
if loc is not None:
f1.header['SOURCEX'] = loc[0]
f1.header['SOURCEY'] = loc[1]
f1.header['SEEING'] = loc[2]
f1.header['MILLUM'] = mini[0][2]
f1.header['THROUGHP'] = mini[0][3]
if response is not None:
f1.header['FLUXUNIT'] = 'ergs/s/cm2/A'
else:
f1.header['FLUXUNIT'] = 'e-/s/cm2/A'
for i, name in enumerate(names):
f1.header['ROW%i' % (i+1)] = name
f1.writeto(outname, overwrite=True)
if standard and ((skysubspec != 0.).sum() > 500):
return get_response(obj[0], commonwave, skysubspec, specname)
cnt += 1
# except Exception as e:
# log.warning('Exposure %i Failed' % cnt)
# cnt += 1
def get_filenames_from_tarfolder(tarfolder, path):
T = tarfile.open(tarfolder, 'r')
names = T.getnames()
matches = fnmatch.filter(names, op.join('*', op.basename(path)))
matches = [op.join(op.dirname(tarfolder), match) for match in matches]
matches = sorted(matches)
T.close()
return matches
def get_cal_path(pathname, date, ndays=31):
date_ = datetime(int(date[:4]), int(date[4:6]), int(date[6:]))
# Controller change date
date_controller_swap = datetime(2024, 7, 22)
if date_ > date_controller_swap:
flag_new = True
else:
flag_new = False
filenames = []
while len(filenames) == 0:
datel = date_ - timedelta(days=int(ndays/2))
for i in np.arange(ndays):
ndate = datel + timedelta(days=int(i))
if flag_new and (ndate <= date_controller_swap):
continue
daten = '%04d%02d%02d' % (ndate.year, ndate.month, ndate.day)
npath = pathname.replace(date, daten)
tarpath = get_tarname_from_filename(npath)
for tarname in sorted(glob.glob(tarpath)):
filenames.append(get_filenames_from_tarfolder(tarname, npath))
flat_list = [item for sublist in filenames for item in sublist]
filenames = sorted(flat_list)
ndays += 1
return filenames
def get_previous_night(daten):
datec_ = datetime(int(daten[:4]), int(daten[4:6]), int(daten[6:]))
daten_ = datec_ - timedelta(days=1)
daten = '%04d%02d%02d' % (daten_.year, daten_.month, daten_.day)
return daten
# LRS2-R
fiberpos, fiberspec = ([], [])
log.info('Beginning the long haul.')
allflatspec, allspec, allra, alldec, allx, ally, allsub = ([], [], [], [], [],
[], [])
DIRNAME = get_script_path()
for info in listinfo:
specinit, specname, multi, lims, amps, slims, arc_names = info
if int(args.date) < 20161101:
nnn = specname #'%s_old' % specname
else:
nnn = specname
arc_lines = Table.read(op.join(DIRNAME, 'lrs2_config/lines_%s.dat' %
nnn), format='ascii')
commonwave = np.linspace(lims[0], lims[1], 2064)
specid, ifuslot, ifuid = multi.split('_')
package = []
marc, mtwi, mflt = ([], [], [])
twipath = twi_path % (instrument, instrument, '00000*', instrument,
ifuslot)
twifiles = get_cal_path(twipath, args.date, ndays=15)
flt_path = (twi_path.replace('twi', 'flt') %
(instrument, instrument, '00000*', instrument, ifuslot))
fltfiles = get_cal_path(flt_path, args.date, ndays=15)
if args.use_flat:
twifiles = fltfiles
for amp in amps:
amppos = get_ifucenfile(specname, amp)
##############
# MASTERBIAS #
##############
log.info('Getting Masterbias for ifuslot, %s, and amp, %s' %
(ifuslot, amp))
zro_path = bias_path % (instrument, instrument, '00000*', instrument,
ifuslot)
zrofiles = get_cal_path(zro_path, args.date, ndays=2)
masterbias = get_masterbias(zrofiles, amp)
#####################
# MASTERTWI [TRACE] #
#####################
log.info('Getting MasterFlat for ifuslot, %s, and amp, %s' %
(ifuslot, amp))
log.info('Getting Trace for ifuslot, %s, and amp, %s' %
(ifuslot, amp))
log.info('Number of twi files: %i' % len(twifiles))
masterflt = get_mastertwi(twifiles, amp, masterbias)
trace, dead = get_trace(masterflt, specid, ifuslot, ifuid, amp,
args.date)
##########################
# MASTERARC [WAVELENGTH] #
##########################
log.info('Getting MasterArc for ifuslot, %s, and amp, %s' %
(ifuslot, amp))
lamp_path = cmp_path % (instrument, instrument, '00000*', instrument,
ifuslot)
lampfiles = get_cal_path(lamp_path, args.date, ndays=15)
log.info('Number of arc files: %i' % len(lampfiles))
masterarc = get_masterarc(lampfiles, amp, arc_names, masterbias,
specname, trace)
lampfiles = get_cal_path(lamp_path.replace(args.date, '20181201'),
'20181201', ndays=3)
def_arc = get_masterarc(lampfiles, amp,
arc_names, masterbias, specname, trace)
#fits.PrimaryHDU(masterarc).writeto('/work/03946/hetdex/maverick/run_lrs2/wtf_%s_%s.fits' % (ifuslot, amp), overwrite=True)
log.info('Getting Wavelength for ifuslot, %s, and amp, %s' %
(ifuslot, amp))
wave = get_wavelength_from_arc(masterarc, trace, arc_lines, specname,
amp, int(args.date), otherimage=def_arc)
#fits.PrimaryHDU(wave).writeto('test_wave.fits', overwrite=True)
#################################
# TWILIGHT FLAT [FIBER PROFILE] #
#################################
log.info('Getting bigW for ifuslot, %s, and amp, %s' %
(ifuslot, amp))
bigW = get_bigW(amp, wave, trace, masterbias)
package.append([wave, trace, bigW, masterbias, amppos, dead])
log.info('Number of flt files: %i' % len(fltfiles))
masterFlat = get_mastertwi(fltfiles, amp, masterbias)
marc.append(masterarc)
mtwi.append(masterflt)
mflt.append(masterFlat)
# Normalize the two amps and correct the flat
calinfo = [np.vstack([package[0][i], package[1][i]])
for i in np.arange(len(package[0]))]
masterarc, masterflt, masterFlat = [np.vstack(x) for x in [marc, mtwi, mflt]]
calinfo[1][package[0][1].shape[0]:, :] += package[0][2].shape[0]
log.info('Getting flat for ifuslot, %s, side, %s' % (ifuslot, specname))
twiflat = get_twiflat_field(twifiles, amps, calinfo[0], calinfo[1],
calinfo[2], commonwave, calinfo[3], specname)
calinfo.insert(2, twiflat)
flatspec = get_spectra(calinfo[2], calinfo[1])
for mfile in [masterarc, masterflt, masterFlat]:
masterarcerror = np.sqrt(3.**2 + np.where(mfile > 0., mfile, 0.))
arcspec, ae, Cc, Yyy, Fff = weighted_extraction(mfile, masterarcerror,
calinfo[2], calinfo[1],
cthresh=500)
sP = np.zeros((calinfo[0].shape[0], len(commonwave)))
for fiber in np.arange(calinfo[0].shape[0]):
I = interp1d(calinfo[0][fiber], arcspec[fiber],
kind='linear', fill_value='extrapolate')
sP[fiber] = I(commonwave)
calinfo.append(sP)
bigF = get_bigF(calinfo[1], calinfo[2])
calinfo.append(bigF)
#####################
# SCIENCE REDUCTION #
#####################
response = None
pathS = sci_path % (instrument, instrument, '0000*',
'01', instrument, ifuslot)
basefiles = []
for tarname in glob.glob(get_tarname_from_filename(pathS)):
basefiles.append(get_filenames_from_tarfolder(tarname, pathS))
flat_list = [item for sublist in basefiles for item in sublist]
basefiles = [f for f in sorted(flat_list) if "exp01" in f]
all_sci_obs = [op.basename(op.dirname(op.dirname(op.dirname(fn))))[-7:]
for fn in basefiles]
objects = get_objects(basefiles, ['OBJECT', 'EXPTIME'])
if response is None:
log.info('Getting average response')
basename = 'LRS2/CALS'
R = fits.open(op.join(DIRNAME,
'lrs2_config/response_%s.fits' % specname))
response = R[0].data[1]*1.
f = []
names = ['wavelength', 'trace', 'flat', 'bigW', 'masterbias',
'xypos', 'dead', 'arcspec', 'fltspec', 'Flatspec', 'bigF']
for i, cal in enumerate(calinfo):
if i == 0:
func = fits.PrimaryHDU
else:
func = fits.ImageHDU
f.append(func(cal))
f.append(fits.ImageHDU(masterarc))
names.append('masterarc')
f.append(fits.ImageHDU(masterFlat))
names.append('masterFlat')
if response is not None:
f.append(fits.ImageHDU(np.array([commonwave, response], dtype=float)))
names.append('response')
for fi, n in zip(f, names):
fi.header['EXTNAME'] = n
basename = 'LRS2/CALS'
mkpath(basename)
fits.HDUList(f).writeto(op.join(basename,
'cal_%s_%s.fits' % (args.date, specname)),
overwrite=True)
for sci_obs, obj, bf in zip(all_sci_obs, objects, basefiles):
log.info('Checkpoint --- Working on %s' %bf)
if args.object is None:
big_reduction(obj, bf, instrument, sci_obs, calinfo, amps, commonwave,
ifuslot, specname, response=response)
else:
if args.object.lower() in obj[0].lower():
big_reduction(obj, bf, instrument, sci_obs, calinfo, amps, commonwave,
ifuslot, specname, response=response)
if check_if_standard(obj[0]) and (ifuslot in obj[0]):
big_reduction(obj, bf, instrument, sci_obs, calinfo, amps, commonwave,
ifuslot, specname, response=response)
|
grzeimannREPO_NAMEPanaceaPATH_START.@Panacea_extracted@Panacea-master@full_lrs2_reduction.py@.PATH_END.py
|
{
"filename": "_export.py",
"repo_name": "scikit-learn/scikit-learn",
"repo_path": "scikit-learn_extracted/scikit-learn-main/sklearn/tree/_export.py",
"type": "Python"
}
|
"""
This module defines export functions for decision trees.
"""
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
from collections.abc import Iterable
from io import StringIO
from numbers import Integral
import numpy as np
from ..base import is_classifier
from ..utils._param_validation import HasMethods, Interval, StrOptions, validate_params
from ..utils.validation import check_array, check_is_fitted
from . import DecisionTreeClassifier, DecisionTreeRegressor, _criterion, _tree
from ._reingold_tilford import Tree, buchheim
def _color_brew(n):
"""Generate n colors with equally spaced hues.
Parameters
----------
n : int
The number of colors required.
Returns
-------
color_list : list, length n
List of n tuples of form (R, G, B) being the components of each color.
"""
color_list = []
# Initialize saturation & value; calculate chroma & value shift
s, v = 0.75, 0.9
c = s * v
m = v - c
for h in np.arange(25, 385, 360.0 / n).astype(int):
# Calculate some intermediate values
h_bar = h / 60.0
x = c * (1 - abs((h_bar % 2) - 1))
# Initialize RGB with same hue & chroma as our color
rgb = [
(c, x, 0),
(x, c, 0),
(0, c, x),
(0, x, c),
(x, 0, c),
(c, 0, x),
(c, x, 0),
]
r, g, b = rgb[int(h_bar)]
# Shift the initial RGB values to match value and store
rgb = [(int(255 * (r + m))), (int(255 * (g + m))), (int(255 * (b + m)))]
color_list.append(rgb)
return color_list
class Sentinel:
def __repr__(self):
return '"tree.dot"'
SENTINEL = Sentinel()
@validate_params(
{
"decision_tree": [DecisionTreeClassifier, DecisionTreeRegressor],
"max_depth": [Interval(Integral, 0, None, closed="left"), None],
"feature_names": ["array-like", None],
"class_names": ["array-like", "boolean", None],
"label": [StrOptions({"all", "root", "none"})],
"filled": ["boolean"],
"impurity": ["boolean"],
"node_ids": ["boolean"],
"proportion": ["boolean"],
"rounded": ["boolean"],
"precision": [Interval(Integral, 0, None, closed="left"), None],
"ax": "no_validation", # delegate validation to matplotlib
"fontsize": [Interval(Integral, 0, None, closed="left"), None],
},
prefer_skip_nested_validation=True,
)
def plot_tree(
decision_tree,
*,
max_depth=None,
feature_names=None,
class_names=None,
label="all",
filled=False,
impurity=True,
node_ids=False,
proportion=False,
rounded=False,
precision=3,
ax=None,
fontsize=None,
):
"""Plot a decision tree.
The sample counts that are shown are weighted with any sample_weights that
might be present.
The visualization is fit automatically to the size of the axis.
Use the ``figsize`` or ``dpi`` arguments of ``plt.figure`` to control
the size of the rendering.
Read more in the :ref:`User Guide <tree>`.
.. versionadded:: 0.21
Parameters
----------
decision_tree : decision tree regressor or classifier
The decision tree to be plotted.
max_depth : int, default=None
The maximum depth of the representation. If None, the tree is fully
generated.
feature_names : array-like of str, default=None
Names of each of the features.
If None, generic names will be used ("x[0]", "x[1]", ...).
class_names : array-like of str or True, default=None
Names of each of the target classes in ascending numerical order.
Only relevant for classification and not supported for multi-output.
If ``True``, shows a symbolic representation of the class name.
label : {'all', 'root', 'none'}, default='all'
Whether to show informative labels for impurity, etc.
Options include 'all' to show at every node, 'root' to show only at
the top root node, or 'none' to not show at any node.
filled : bool, default=False
When set to ``True``, paint nodes to indicate majority class for
classification, extremity of values for regression, or purity of node
for multi-output.
impurity : bool, default=True
When set to ``True``, show the impurity at each node.
node_ids : bool, default=False
When set to ``True``, show the ID number on each node.
proportion : bool, default=False
When set to ``True``, change the display of 'values' and/or 'samples'
to be proportions and percentages respectively.
rounded : bool, default=False
When set to ``True``, draw node boxes with rounded corners and use
Helvetica fonts instead of Times-Roman.
precision : int, default=3
Number of digits of precision for floating point in the values of
impurity, threshold and value attributes of each node.
ax : matplotlib axis, default=None
Axes to plot to. If None, use current axis. Any previous content
is cleared.
fontsize : int, default=None
Size of text font. If None, determined automatically to fit figure.
Returns
-------
annotations : list of artists
List containing the artists for the annotation boxes making up the
tree.
Examples
--------
>>> from sklearn.datasets import load_iris
>>> from sklearn import tree
>>> clf = tree.DecisionTreeClassifier(random_state=0)
>>> iris = load_iris()
>>> clf = clf.fit(iris.data, iris.target)
>>> tree.plot_tree(clf)
[...]
"""
check_is_fitted(decision_tree)
exporter = _MPLTreeExporter(
max_depth=max_depth,
feature_names=feature_names,
class_names=class_names,
label=label,
filled=filled,
impurity=impurity,
node_ids=node_ids,
proportion=proportion,
rounded=rounded,
precision=precision,
fontsize=fontsize,
)
return exporter.export(decision_tree, ax=ax)
class _BaseTreeExporter:
def __init__(
self,
max_depth=None,
feature_names=None,
class_names=None,
label="all",
filled=False,
impurity=True,
node_ids=False,
proportion=False,
rounded=False,
precision=3,
fontsize=None,
):
self.max_depth = max_depth
self.feature_names = feature_names
self.class_names = class_names
self.label = label
self.filled = filled
self.impurity = impurity
self.node_ids = node_ids
self.proportion = proportion
self.rounded = rounded
self.precision = precision
self.fontsize = fontsize
def get_color(self, value):
# Find the appropriate color & intensity for a node
if self.colors["bounds"] is None:
# Classification tree
color = list(self.colors["rgb"][np.argmax(value)])
sorted_values = sorted(value, reverse=True)
if len(sorted_values) == 1:
alpha = 0.0
else:
alpha = (sorted_values[0] - sorted_values[1]) / (1 - sorted_values[1])
else:
# Regression tree or multi-output
color = list(self.colors["rgb"][0])
alpha = (value - self.colors["bounds"][0]) / (
self.colors["bounds"][1] - self.colors["bounds"][0]
)
# compute the color as alpha against white
color = [int(round(alpha * c + (1 - alpha) * 255, 0)) for c in color]
# Return html color code in #RRGGBB format
return "#%2x%2x%2x" % tuple(color)
def get_fill_color(self, tree, node_id):
# Fetch appropriate color for node
if "rgb" not in self.colors:
# Initialize colors and bounds if required
self.colors["rgb"] = _color_brew(tree.n_classes[0])
if tree.n_outputs != 1:
# Find max and min impurities for multi-output
# The next line uses -max(impurity) instead of min(-impurity)
# and -min(impurity) instead of max(-impurity) on purpose, in
# order to avoid what looks like an issue with SIMD on non
# memory aligned arrays on 32bit OS. For more details see
# https://github.com/scikit-learn/scikit-learn/issues/27506.
self.colors["bounds"] = (-np.max(tree.impurity), -np.min(tree.impurity))
elif tree.n_classes[0] == 1 and len(np.unique(tree.value)) != 1:
# Find max and min values in leaf nodes for regression
self.colors["bounds"] = (np.min(tree.value), np.max(tree.value))
if tree.n_outputs == 1:
node_val = tree.value[node_id][0, :]
if (
tree.n_classes[0] == 1
and isinstance(node_val, Iterable)
and self.colors["bounds"] is not None
):
# Unpack the float only for the regression tree case.
# Classification tree requires an Iterable in `get_color`.
node_val = node_val.item()
else:
# If multi-output color node by impurity
node_val = -tree.impurity[node_id]
return self.get_color(node_val)
def node_to_str(self, tree, node_id, criterion):
# Generate the node content string
if tree.n_outputs == 1:
value = tree.value[node_id][0, :]
else:
value = tree.value[node_id]
# Should labels be shown?
labels = (self.label == "root" and node_id == 0) or self.label == "all"
characters = self.characters
node_string = characters[-1]
# Write node ID
if self.node_ids:
if labels:
node_string += "node "
node_string += characters[0] + str(node_id) + characters[4]
# Write decision criteria
if tree.children_left[node_id] != _tree.TREE_LEAF:
# Always write node decision criteria, except for leaves
if self.feature_names is not None:
feature = self.feature_names[tree.feature[node_id]]
feature = self.str_escape(feature)
else:
feature = "x%s%s%s" % (
characters[1],
tree.feature[node_id],
characters[2],
)
node_string += "%s %s %s%s" % (
feature,
characters[3],
round(tree.threshold[node_id], self.precision),
characters[4],
)
# Write impurity
if self.impurity:
if isinstance(criterion, _criterion.FriedmanMSE):
criterion = "friedman_mse"
elif isinstance(criterion, _criterion.MSE) or criterion == "squared_error":
criterion = "squared_error"
elif not isinstance(criterion, str):
criterion = "impurity"
if labels:
node_string += "%s = " % criterion
node_string += (
str(round(tree.impurity[node_id], self.precision)) + characters[4]
)
# Write node sample count
if labels:
node_string += "samples = "
if self.proportion:
percent = (
100.0 * tree.n_node_samples[node_id] / float(tree.n_node_samples[0])
)
node_string += str(round(percent, 1)) + "%" + characters[4]
else:
node_string += str(tree.n_node_samples[node_id]) + characters[4]
# Write node class distribution / regression value
if not self.proportion and tree.n_classes[0] != 1:
# For classification this will show the proportion of samples
value = value * tree.weighted_n_node_samples[node_id]
if labels:
node_string += "value = "
if tree.n_classes[0] == 1:
# Regression
value_text = np.around(value, self.precision)
elif self.proportion:
# Classification
value_text = np.around(value, self.precision)
elif np.all(np.equal(np.mod(value, 1), 0)):
# Classification without floating-point weights
value_text = value.astype(int)
else:
# Classification with floating-point weights
value_text = np.around(value, self.precision)
# Strip whitespace
value_text = str(value_text.astype("S32")).replace("b'", "'")
value_text = value_text.replace("' '", ", ").replace("'", "")
if tree.n_classes[0] == 1 and tree.n_outputs == 1:
value_text = value_text.replace("[", "").replace("]", "")
value_text = value_text.replace("\n ", characters[4])
node_string += value_text + characters[4]
# Write node majority class
if (
self.class_names is not None
and tree.n_classes[0] != 1
and tree.n_outputs == 1
):
# Only done for single-output classification trees
if labels:
node_string += "class = "
if self.class_names is not True:
class_name = self.class_names[np.argmax(value)]
class_name = self.str_escape(class_name)
else:
class_name = "y%s%s%s" % (
characters[1],
np.argmax(value),
characters[2],
)
node_string += class_name
# Clean up any trailing newlines
if node_string.endswith(characters[4]):
node_string = node_string[: -len(characters[4])]
return node_string + characters[5]
def str_escape(self, string):
return string
class _DOTTreeExporter(_BaseTreeExporter):
def __init__(
self,
out_file=SENTINEL,
max_depth=None,
feature_names=None,
class_names=None,
label="all",
filled=False,
leaves_parallel=False,
impurity=True,
node_ids=False,
proportion=False,
rotate=False,
rounded=False,
special_characters=False,
precision=3,
fontname="helvetica",
):
super().__init__(
max_depth=max_depth,
feature_names=feature_names,
class_names=class_names,
label=label,
filled=filled,
impurity=impurity,
node_ids=node_ids,
proportion=proportion,
rounded=rounded,
precision=precision,
)
self.leaves_parallel = leaves_parallel
self.out_file = out_file
self.special_characters = special_characters
self.fontname = fontname
self.rotate = rotate
# PostScript compatibility for special characters
if special_characters:
self.characters = ["#", "<SUB>", "</SUB>", "≤", "<br/>", ">", "<"]
else:
self.characters = ["#", "[", "]", "<=", "\\n", '"', '"']
# The depth of each node for plotting with 'leaf' option
self.ranks = {"leaves": []}
# The colors to render each node with
self.colors = {"bounds": None}
def export(self, decision_tree):
# Check length of feature_names before getting into the tree node
# Raise error if length of feature_names does not match
# n_features_in_ in the decision_tree
if self.feature_names is not None:
if len(self.feature_names) != decision_tree.n_features_in_:
raise ValueError(
"Length of feature_names, %d does not match number of features, %d"
% (len(self.feature_names), decision_tree.n_features_in_)
)
# each part writes to out_file
self.head()
# Now recurse the tree and add node & edge attributes
if isinstance(decision_tree, _tree.Tree):
self.recurse(decision_tree, 0, criterion="impurity")
else:
self.recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion)
self.tail()
def tail(self):
# If required, draw leaf nodes at same depth as each other
if self.leaves_parallel:
for rank in sorted(self.ranks):
self.out_file.write(
"{rank=same ; " + "; ".join(r for r in self.ranks[rank]) + "} ;\n"
)
self.out_file.write("}")
def head(self):
self.out_file.write("digraph Tree {\n")
# Specify node aesthetics
self.out_file.write("node [shape=box")
rounded_filled = []
if self.filled:
rounded_filled.append("filled")
if self.rounded:
rounded_filled.append("rounded")
if len(rounded_filled) > 0:
self.out_file.write(
', style="%s", color="black"' % ", ".join(rounded_filled)
)
self.out_file.write(', fontname="%s"' % self.fontname)
self.out_file.write("] ;\n")
# Specify graph & edge aesthetics
if self.leaves_parallel:
self.out_file.write("graph [ranksep=equally, splines=polyline] ;\n")
self.out_file.write('edge [fontname="%s"] ;\n' % self.fontname)
if self.rotate:
self.out_file.write("rankdir=LR ;\n")
def recurse(self, tree, node_id, criterion, parent=None, depth=0):
if node_id == _tree.TREE_LEAF:
raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF)
left_child = tree.children_left[node_id]
right_child = tree.children_right[node_id]
# Add node with description
if self.max_depth is None or depth <= self.max_depth:
# Collect ranks for 'leaf' option in plot_options
if left_child == _tree.TREE_LEAF:
self.ranks["leaves"].append(str(node_id))
elif str(depth) not in self.ranks:
self.ranks[str(depth)] = [str(node_id)]
else:
self.ranks[str(depth)].append(str(node_id))
self.out_file.write(
"%d [label=%s" % (node_id, self.node_to_str(tree, node_id, criterion))
)
if self.filled:
self.out_file.write(
', fillcolor="%s"' % self.get_fill_color(tree, node_id)
)
self.out_file.write("] ;\n")
if parent is not None:
# Add edge to parent
self.out_file.write("%d -> %d" % (parent, node_id))
if parent == 0:
# Draw True/False labels if parent is root node
angles = np.array([45, -45]) * ((self.rotate - 0.5) * -2)
self.out_file.write(" [labeldistance=2.5, labelangle=")
if node_id == 1:
self.out_file.write('%d, headlabel="True"]' % angles[0])
else:
self.out_file.write('%d, headlabel="False"]' % angles[1])
self.out_file.write(" ;\n")
if left_child != _tree.TREE_LEAF:
self.recurse(
tree,
left_child,
criterion=criterion,
parent=node_id,
depth=depth + 1,
)
self.recurse(
tree,
right_child,
criterion=criterion,
parent=node_id,
depth=depth + 1,
)
else:
self.ranks["leaves"].append(str(node_id))
self.out_file.write('%d [label="(...)"' % node_id)
if self.filled:
# color cropped nodes grey
self.out_file.write(', fillcolor="#C0C0C0"')
self.out_file.write("] ;\n" % node_id)
if parent is not None:
# Add edge to parent
self.out_file.write("%d -> %d ;\n" % (parent, node_id))
def str_escape(self, string):
# override default escaping for graphviz
return string.replace('"', r"\"")
class _MPLTreeExporter(_BaseTreeExporter):
def __init__(
self,
max_depth=None,
feature_names=None,
class_names=None,
label="all",
filled=False,
impurity=True,
node_ids=False,
proportion=False,
rounded=False,
precision=3,
fontsize=None,
):
super().__init__(
max_depth=max_depth,
feature_names=feature_names,
class_names=class_names,
label=label,
filled=filled,
impurity=impurity,
node_ids=node_ids,
proportion=proportion,
rounded=rounded,
precision=precision,
)
self.fontsize = fontsize
# The depth of each node for plotting with 'leaf' option
self.ranks = {"leaves": []}
# The colors to render each node with
self.colors = {"bounds": None}
self.characters = ["#", "[", "]", "<=", "\n", "", ""]
self.bbox_args = dict()
if self.rounded:
self.bbox_args["boxstyle"] = "round"
self.arrow_args = dict(arrowstyle="<-")
def _make_tree(self, node_id, et, criterion, depth=0):
# traverses _tree.Tree recursively, builds intermediate
# "_reingold_tilford.Tree" object
name = self.node_to_str(et, node_id, criterion=criterion)
if et.children_left[node_id] != _tree.TREE_LEAF and (
self.max_depth is None or depth <= self.max_depth
):
children = [
self._make_tree(
et.children_left[node_id], et, criterion, depth=depth + 1
),
self._make_tree(
et.children_right[node_id], et, criterion, depth=depth + 1
),
]
else:
return Tree(name, node_id)
return Tree(name, node_id, *children)
def export(self, decision_tree, ax=None):
import matplotlib.pyplot as plt
from matplotlib.text import Annotation
if ax is None:
ax = plt.gca()
ax.clear()
ax.set_axis_off()
my_tree = self._make_tree(0, decision_tree.tree_, decision_tree.criterion)
draw_tree = buchheim(my_tree)
# important to make sure we're still
# inside the axis after drawing the box
# this makes sense because the width of a box
# is about the same as the distance between boxes
max_x, max_y = draw_tree.max_extents() + 1
ax_width = ax.get_window_extent().width
ax_height = ax.get_window_extent().height
scale_x = ax_width / max_x
scale_y = ax_height / max_y
self.recurse(draw_tree, decision_tree.tree_, ax, max_x, max_y)
anns = [ann for ann in ax.get_children() if isinstance(ann, Annotation)]
# update sizes of all bboxes
renderer = ax.figure.canvas.get_renderer()
for ann in anns:
ann.update_bbox_position_size(renderer)
if self.fontsize is None:
# get figure to data transform
# adjust fontsize to avoid overlap
# get max box width and height
extents = [
bbox_patch.get_window_extent()
for ann in anns
if (bbox_patch := ann.get_bbox_patch()) is not None
]
max_width = max([extent.width for extent in extents])
max_height = max([extent.height for extent in extents])
# width should be around scale_x in axis coordinates
size = anns[0].get_fontsize() * min(
scale_x / max_width, scale_y / max_height
)
for ann in anns:
ann.set_fontsize(size)
return anns
def recurse(self, node, tree, ax, max_x, max_y, depth=0):
import matplotlib.pyplot as plt
# kwargs for annotations without a bounding box
common_kwargs = dict(
zorder=100 - 10 * depth,
xycoords="axes fraction",
)
if self.fontsize is not None:
common_kwargs["fontsize"] = self.fontsize
# kwargs for annotations with a bounding box
kwargs = dict(
ha="center",
va="center",
bbox=self.bbox_args.copy(),
arrowprops=self.arrow_args.copy(),
**common_kwargs,
)
kwargs["arrowprops"]["edgecolor"] = plt.rcParams["text.color"]
# offset things by .5 to center them in plot
xy = ((node.x + 0.5) / max_x, (max_y - node.y - 0.5) / max_y)
if self.max_depth is None or depth <= self.max_depth:
if self.filled:
kwargs["bbox"]["fc"] = self.get_fill_color(tree, node.tree.node_id)
else:
kwargs["bbox"]["fc"] = ax.get_facecolor()
if node.parent is None:
# root
ax.annotate(node.tree.label, xy, **kwargs)
else:
xy_parent = (
(node.parent.x + 0.5) / max_x,
(max_y - node.parent.y - 0.5) / max_y,
)
ax.annotate(node.tree.label, xy_parent, xy, **kwargs)
# Draw True/False labels if parent is root node
if node.parent.parent is None:
# Adjust the position for the text to be slightly above the arrow
text_pos = (
(xy_parent[0] + xy[0]) / 2,
(xy_parent[1] + xy[1]) / 2,
)
# Annotate the arrow with the edge label to indicate the child
# where the sample-split condition is satisfied
if node.parent.left() == node:
label_text, label_ha = ("True ", "right")
else:
label_text, label_ha = (" False", "left")
ax.annotate(label_text, text_pos, ha=label_ha, **common_kwargs)
for child in node.children:
self.recurse(child, tree, ax, max_x, max_y, depth=depth + 1)
else:
xy_parent = (
(node.parent.x + 0.5) / max_x,
(max_y - node.parent.y - 0.5) / max_y,
)
kwargs["bbox"]["fc"] = "grey"
ax.annotate("\n (...) \n", xy_parent, xy, **kwargs)
@validate_params(
{
"decision_tree": "no_validation",
"out_file": [str, None, HasMethods("write")],
"max_depth": [Interval(Integral, 0, None, closed="left"), None],
"feature_names": ["array-like", None],
"class_names": ["array-like", "boolean", None],
"label": [StrOptions({"all", "root", "none"})],
"filled": ["boolean"],
"leaves_parallel": ["boolean"],
"impurity": ["boolean"],
"node_ids": ["boolean"],
"proportion": ["boolean"],
"rotate": ["boolean"],
"rounded": ["boolean"],
"special_characters": ["boolean"],
"precision": [Interval(Integral, 0, None, closed="left"), None],
"fontname": [str],
},
prefer_skip_nested_validation=True,
)
def export_graphviz(
decision_tree,
out_file=None,
*,
max_depth=None,
feature_names=None,
class_names=None,
label="all",
filled=False,
leaves_parallel=False,
impurity=True,
node_ids=False,
proportion=False,
rotate=False,
rounded=False,
special_characters=False,
precision=3,
fontname="helvetica",
):
"""Export a decision tree in DOT format.
This function generates a GraphViz representation of the decision tree,
which is then written into `out_file`. Once exported, graphical renderings
can be generated using, for example::
$ dot -Tps tree.dot -o tree.ps (PostScript format)
$ dot -Tpng tree.dot -o tree.png (PNG format)
The sample counts that are shown are weighted with any sample_weights that
might be present.
Read more in the :ref:`User Guide <tree>`.
Parameters
----------
decision_tree : object
The decision tree estimator to be exported to GraphViz.
out_file : object or str, default=None
Handle or name of the output file. If ``None``, the result is
returned as a string.
.. versionchanged:: 0.20
Default of out_file changed from "tree.dot" to None.
max_depth : int, default=None
The maximum depth of the representation. If None, the tree is fully
generated.
feature_names : array-like of shape (n_features,), default=None
An array containing the feature names.
If None, generic names will be used ("x[0]", "x[1]", ...).
class_names : array-like of shape (n_classes,) or bool, default=None
Names of each of the target classes in ascending numerical order.
Only relevant for classification and not supported for multi-output.
If ``True``, shows a symbolic representation of the class name.
label : {'all', 'root', 'none'}, default='all'
Whether to show informative labels for impurity, etc.
Options include 'all' to show at every node, 'root' to show only at
the top root node, or 'none' to not show at any node.
filled : bool, default=False
When set to ``True``, paint nodes to indicate majority class for
classification, extremity of values for regression, or purity of node
for multi-output.
leaves_parallel : bool, default=False
When set to ``True``, draw all leaf nodes at the bottom of the tree.
impurity : bool, default=True
When set to ``True``, show the impurity at each node.
node_ids : bool, default=False
When set to ``True``, show the ID number on each node.
proportion : bool, default=False
When set to ``True``, change the display of 'values' and/or 'samples'
to be proportions and percentages respectively.
rotate : bool, default=False
When set to ``True``, orient tree left to right rather than top-down.
rounded : bool, default=False
When set to ``True``, draw node boxes with rounded corners.
special_characters : bool, default=False
When set to ``False``, ignore special characters for PostScript
compatibility.
precision : int, default=3
Number of digits of precision for floating point in the values of
impurity, threshold and value attributes of each node.
fontname : str, default='helvetica'
Name of font used to render text.
Returns
-------
dot_data : str
String representation of the input tree in GraphViz dot format.
Only returned if ``out_file`` is None.
.. versionadded:: 0.18
Examples
--------
>>> from sklearn.datasets import load_iris
>>> from sklearn import tree
>>> clf = tree.DecisionTreeClassifier()
>>> iris = load_iris()
>>> clf = clf.fit(iris.data, iris.target)
>>> tree.export_graphviz(clf)
'digraph Tree {...
"""
if feature_names is not None:
feature_names = check_array(
feature_names, ensure_2d=False, dtype=None, ensure_min_samples=0
)
if class_names is not None and not isinstance(class_names, bool):
class_names = check_array(
class_names, ensure_2d=False, dtype=None, ensure_min_samples=0
)
check_is_fitted(decision_tree)
own_file = False
return_string = False
try:
if isinstance(out_file, str):
out_file = open(out_file, "w", encoding="utf-8")
own_file = True
if out_file is None:
return_string = True
out_file = StringIO()
exporter = _DOTTreeExporter(
out_file=out_file,
max_depth=max_depth,
feature_names=feature_names,
class_names=class_names,
label=label,
filled=filled,
leaves_parallel=leaves_parallel,
impurity=impurity,
node_ids=node_ids,
proportion=proportion,
rotate=rotate,
rounded=rounded,
special_characters=special_characters,
precision=precision,
fontname=fontname,
)
exporter.export(decision_tree)
if return_string:
return exporter.out_file.getvalue()
finally:
if own_file:
out_file.close()
def _compute_depth(tree, node):
"""
Returns the depth of the subtree rooted in node.
"""
def compute_depth_(
current_node, current_depth, children_left, children_right, depths
):
depths += [current_depth]
left = children_left[current_node]
right = children_right[current_node]
if left != -1 and right != -1:
compute_depth_(
left, current_depth + 1, children_left, children_right, depths
)
compute_depth_(
right, current_depth + 1, children_left, children_right, depths
)
depths = []
compute_depth_(node, 1, tree.children_left, tree.children_right, depths)
return max(depths)
@validate_params(
{
"decision_tree": [DecisionTreeClassifier, DecisionTreeRegressor],
"feature_names": ["array-like", None],
"class_names": ["array-like", None],
"max_depth": [Interval(Integral, 0, None, closed="left"), None],
"spacing": [Interval(Integral, 1, None, closed="left"), None],
"decimals": [Interval(Integral, 0, None, closed="left"), None],
"show_weights": ["boolean"],
},
prefer_skip_nested_validation=True,
)
def export_text(
decision_tree,
*,
feature_names=None,
class_names=None,
max_depth=10,
spacing=3,
decimals=2,
show_weights=False,
):
"""Build a text report showing the rules of a decision tree.
Note that backwards compatibility may not be supported.
Parameters
----------
decision_tree : object
The decision tree estimator to be exported.
It can be an instance of
DecisionTreeClassifier or DecisionTreeRegressor.
feature_names : array-like of shape (n_features,), default=None
An array containing the feature names.
If None generic names will be used ("feature_0", "feature_1", ...).
class_names : array-like of shape (n_classes,), default=None
Names of each of the target classes in ascending numerical order.
Only relevant for classification and not supported for multi-output.
- if `None`, the class names are delegated to `decision_tree.classes_`;
- otherwise, `class_names` will be used as class names instead of
`decision_tree.classes_`. The length of `class_names` must match
the length of `decision_tree.classes_`.
.. versionadded:: 1.3
max_depth : int, default=10
Only the first max_depth levels of the tree are exported.
Truncated branches will be marked with "...".
spacing : int, default=3
Number of spaces between edges. The higher it is, the wider the result.
decimals : int, default=2
Number of decimal digits to display.
show_weights : bool, default=False
If true the classification weights will be exported on each leaf.
The classification weights are the number of samples each class.
Returns
-------
report : str
Text summary of all the rules in the decision tree.
Examples
--------
>>> from sklearn.datasets import load_iris
>>> from sklearn.tree import DecisionTreeClassifier
>>> from sklearn.tree import export_text
>>> iris = load_iris()
>>> X = iris['data']
>>> y = iris['target']
>>> decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
>>> decision_tree = decision_tree.fit(X, y)
>>> r = export_text(decision_tree, feature_names=iris['feature_names'])
>>> print(r)
|--- petal width (cm) <= 0.80
| |--- class: 0
|--- petal width (cm) > 0.80
| |--- petal width (cm) <= 1.75
| | |--- class: 1
| |--- petal width (cm) > 1.75
| | |--- class: 2
"""
if feature_names is not None:
feature_names = check_array(
feature_names, ensure_2d=False, dtype=None, ensure_min_samples=0
)
if class_names is not None:
class_names = check_array(
class_names, ensure_2d=False, dtype=None, ensure_min_samples=0
)
check_is_fitted(decision_tree)
tree_ = decision_tree.tree_
if is_classifier(decision_tree):
if class_names is None:
class_names = decision_tree.classes_
elif len(class_names) != len(decision_tree.classes_):
raise ValueError(
"When `class_names` is an array, it should contain as"
" many items as `decision_tree.classes_`. Got"
f" {len(class_names)} while the tree was fitted with"
f" {len(decision_tree.classes_)} classes."
)
right_child_fmt = "{} {} <= {}\n"
left_child_fmt = "{} {} > {}\n"
truncation_fmt = "{} {}\n"
if feature_names is not None and len(feature_names) != tree_.n_features:
raise ValueError(
"feature_names must contain %d elements, got %d"
% (tree_.n_features, len(feature_names))
)
if isinstance(decision_tree, DecisionTreeClassifier):
value_fmt = "{}{} weights: {}\n"
if not show_weights:
value_fmt = "{}{}{}\n"
else:
value_fmt = "{}{} value: {}\n"
if feature_names is not None:
feature_names_ = [
feature_names[i] if i != _tree.TREE_UNDEFINED else None
for i in tree_.feature
]
else:
feature_names_ = ["feature_{}".format(i) for i in tree_.feature]
export_text.report = ""
def _add_leaf(value, weighted_n_node_samples, class_name, indent):
val = ""
if isinstance(decision_tree, DecisionTreeClassifier):
if show_weights:
val = [
"{1:.{0}f}, ".format(decimals, v * weighted_n_node_samples)
for v in value
]
val = "[" + "".join(val)[:-2] + "]"
weighted_n_node_samples
val += " class: " + str(class_name)
else:
val = ["{1:.{0}f}, ".format(decimals, v) for v in value]
val = "[" + "".join(val)[:-2] + "]"
export_text.report += value_fmt.format(indent, "", val)
def print_tree_recurse(node, depth):
indent = ("|" + (" " * spacing)) * depth
indent = indent[:-spacing] + "-" * spacing
value = None
if tree_.n_outputs == 1:
value = tree_.value[node][0]
else:
value = tree_.value[node].T[0]
class_name = np.argmax(value)
if tree_.n_classes[0] != 1 and tree_.n_outputs == 1:
class_name = class_names[class_name]
weighted_n_node_samples = tree_.weighted_n_node_samples[node]
if depth <= max_depth + 1:
info_fmt = ""
info_fmt_left = info_fmt
info_fmt_right = info_fmt
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_names_[node]
threshold = tree_.threshold[node]
threshold = "{1:.{0}f}".format(decimals, threshold)
export_text.report += right_child_fmt.format(indent, name, threshold)
export_text.report += info_fmt_left
print_tree_recurse(tree_.children_left[node], depth + 1)
export_text.report += left_child_fmt.format(indent, name, threshold)
export_text.report += info_fmt_right
print_tree_recurse(tree_.children_right[node], depth + 1)
else: # leaf
_add_leaf(value, weighted_n_node_samples, class_name, indent)
else:
subtree_depth = _compute_depth(tree_, node)
if subtree_depth == 1:
_add_leaf(value, weighted_n_node_samples, class_name, indent)
else:
trunc_report = "truncated branch of depth %d" % subtree_depth
export_text.report += truncation_fmt.format(indent, trunc_report)
print_tree_recurse(0, 1)
return export_text.report
|
scikit-learnREPO_NAMEscikit-learnPATH_START.@scikit-learn_extracted@scikit-learn-main@sklearn@tree@_export.py@.PATH_END.py
|
{
"filename": "root_listeners.py",
"repo_name": "langchain-ai/langchain",
"repo_path": "langchain_extracted/langchain-master/libs/core/langchain_core/tracers/root_listeners.py",
"type": "Python"
}
|
from collections.abc import Awaitable
from typing import Callable, Optional, Union
from uuid import UUID
from langchain_core.runnables.config import (
RunnableConfig,
acall_func_with_variable_args,
call_func_with_variable_args,
)
from langchain_core.tracers.base import AsyncBaseTracer, BaseTracer
from langchain_core.tracers.schemas import Run
Listener = Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]
AsyncListener = Union[
Callable[[Run], Awaitable[None]], Callable[[Run, RunnableConfig], Awaitable[None]]
]
class RootListenersTracer(BaseTracer):
"""Tracer that calls listeners on run start, end, and error.
Parameters:
log_missing_parent: Whether to log a warning if the parent is missing.
Default is False.
config: The runnable config.
on_start: The listener to call on run start.
on_end: The listener to call on run end.
on_error: The listener to call on run error.
"""
log_missing_parent = False
def __init__(
self,
*,
config: RunnableConfig,
on_start: Optional[Listener],
on_end: Optional[Listener],
on_error: Optional[Listener],
) -> None:
"""Initialize the tracer.
Args:
config: The runnable config.
on_start: The listener to call on run start.
on_end: The listener to call on run end.
on_error: The listener to call on run error
"""
super().__init__(_schema_format="original+chat")
self.config = config
self._arg_on_start = on_start
self._arg_on_end = on_end
self._arg_on_error = on_error
self.root_id: Optional[UUID] = None
def _persist_run(self, run: Run) -> None:
# This is a legacy method only called once for an entire run tree
# therefore not useful here
pass
def _on_run_create(self, run: Run) -> None:
if self.root_id is not None:
return
self.root_id = run.id
if self._arg_on_start is not None:
call_func_with_variable_args(self._arg_on_start, run, self.config)
def _on_run_update(self, run: Run) -> None:
if run.id != self.root_id:
return
if run.error is None:
if self._arg_on_end is not None:
call_func_with_variable_args(self._arg_on_end, run, self.config)
else:
if self._arg_on_error is not None:
call_func_with_variable_args(self._arg_on_error, run, self.config)
class AsyncRootListenersTracer(AsyncBaseTracer):
"""Async Tracer that calls listeners on run start, end, and error.
Parameters:
log_missing_parent: Whether to log a warning if the parent is missing.
Default is False.
config: The runnable config.
on_start: The listener to call on run start.
on_end: The listener to call on run end.
on_error: The listener to call on run error.
"""
log_missing_parent = False
def __init__(
self,
*,
config: RunnableConfig,
on_start: Optional[AsyncListener],
on_end: Optional[AsyncListener],
on_error: Optional[AsyncListener],
) -> None:
"""Initialize the tracer.
Args:
config: The runnable config.
on_start: The listener to call on run start.
on_end: The listener to call on run end.
on_error: The listener to call on run error
"""
super().__init__(_schema_format="original+chat")
self.config = config
self._arg_on_start = on_start
self._arg_on_end = on_end
self._arg_on_error = on_error
self.root_id: Optional[UUID] = None
async def _persist_run(self, run: Run) -> None:
# This is a legacy method only called once for an entire run tree
# therefore not useful here
pass
async def _on_run_create(self, run: Run) -> None:
if self.root_id is not None:
return
self.root_id = run.id
if self._arg_on_start is not None:
await acall_func_with_variable_args(self._arg_on_start, run, self.config)
async def _on_run_update(self, run: Run) -> None:
if run.id != self.root_id:
return
if run.error is None:
if self._arg_on_end is not None:
await acall_func_with_variable_args(self._arg_on_end, run, self.config)
else:
if self._arg_on_error is not None:
await acall_func_with_variable_args(
self._arg_on_error, run, self.config
)
|
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@core@langchain_core@tracers@root_listeners.py@.PATH_END.py
|
{
"filename": "setopt.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/setuptools/py2/setuptools/command/setopt.py",
"type": "Python"
}
|
from distutils.util import convert_path
from distutils import log
from distutils.errors import DistutilsOptionError
import distutils
import os
from setuptools.extern.six.moves import configparser
from setuptools import Command
__all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
def config_file(kind="local"):
"""Get the filename of the distutils, local, global, or per-user config
`kind` must be one of "local", "global", or "user"
"""
if kind == 'local':
return 'setup.cfg'
if kind == 'global':
return os.path.join(
os.path.dirname(distutils.__file__), 'distutils.cfg'
)
if kind == 'user':
dot = os.name == 'posix' and '.' or ''
return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot))
raise ValueError(
"config_file() type must be 'local', 'global', or 'user'", kind
)
def edit_config(filename, settings, dry_run=False):
"""Edit a configuration file to include `settings`
`settings` is a dictionary of dictionaries or ``None`` values, keyed by
command/section name. A ``None`` value means to delete the entire section,
while a dictionary lists settings to be changed or deleted in that section.
A setting of ``None`` means to delete that setting.
"""
log.debug("Reading configuration from %s", filename)
opts = configparser.RawConfigParser()
opts.read([filename])
for section, options in settings.items():
if options is None:
log.info("Deleting section [%s] from %s", section, filename)
opts.remove_section(section)
else:
if not opts.has_section(section):
log.debug("Adding new section [%s] to %s", section, filename)
opts.add_section(section)
for option, value in options.items():
if value is None:
log.debug(
"Deleting %s.%s from %s",
section, option, filename
)
opts.remove_option(section, option)
if not opts.options(section):
log.info("Deleting empty [%s] section from %s",
section, filename)
opts.remove_section(section)
else:
log.debug(
"Setting %s.%s to %r in %s",
section, option, value, filename
)
opts.set(section, option, value)
log.info("Writing %s", filename)
if not dry_run:
with open(filename, 'w') as f:
opts.write(f)
class option_base(Command):
"""Abstract base class for commands that mess with config files"""
user_options = [
('global-config', 'g',
"save options to the site-wide distutils.cfg file"),
('user-config', 'u',
"save options to the current user's pydistutils.cfg file"),
('filename=', 'f',
"configuration file to use (default=setup.cfg)"),
]
boolean_options = [
'global-config', 'user-config',
]
def initialize_options(self):
self.global_config = None
self.user_config = None
self.filename = None
def finalize_options(self):
filenames = []
if self.global_config:
filenames.append(config_file('global'))
if self.user_config:
filenames.append(config_file('user'))
if self.filename is not None:
filenames.append(self.filename)
if not filenames:
filenames.append(config_file('local'))
if len(filenames) > 1:
raise DistutilsOptionError(
"Must specify only one configuration file option",
filenames
)
self.filename, = filenames
class setopt(option_base):
"""Save command-line options to a file"""
description = "set an option in setup.cfg or another config file"
user_options = [
('command=', 'c', 'command to set an option for'),
('option=', 'o', 'option to set'),
('set-value=', 's', 'value of the option'),
('remove', 'r', 'remove (unset) the value'),
] + option_base.user_options
boolean_options = option_base.boolean_options + ['remove']
def initialize_options(self):
option_base.initialize_options(self)
self.command = None
self.option = None
self.set_value = None
self.remove = None
def finalize_options(self):
option_base.finalize_options(self)
if self.command is None or self.option is None:
raise DistutilsOptionError("Must specify --command *and* --option")
if self.set_value is None and not self.remove:
raise DistutilsOptionError("Must specify --set-value or --remove")
def run(self):
edit_config(
self.filename, {
self.command: {self.option.replace('-', '_'): self.set_value}
},
self.dry_run
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@setuptools@py2@setuptools@command@setopt.py@.PATH_END.py
|
{
"filename": "limb_darkening.py",
"repo_name": "ladsantos/flatstar",
"repo_path": "flatstar_extracted/flatstar-main/flatstar/limb_darkening.py",
"type": "Python"
}
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module is used to compute the limb-darkening functions of stars.
"""
import numpy as np
__all__ = ["linear", "quadratic", "square_root", "logarithmic", "exponential",
"sing_three", "claret_four"]
# Schwarzschild (1906; Nachrichten von der Königlichen Gesellschaft der
# Wissenschaften zu Göttingen. Mathematisch-Physikalische Klasse, p. 43)
def linear(mu, c, i0=1.0):
"""
Calculates the intensity of a given cell in the stellar surface using a
linear limb-darkening law.
Parameters
----------
mu (``float`` or ``numpy.ndarray``):
Cosine of the angle between a line normal to the stellar surface and the
line of sight.
c (``float``):
Limb-darkening coefficient.
i0 (``float``, optional):
Intensity without limb-darkening. Default is 1.0.
Returns
-------
i_mu (``float`` or ``numpy.ndarray``):
Intensity with limb-darkening. The format is the same as the input
``mu``.
"""
attenuation = 1 - c * (1 - mu)
i_mu = i0 * attenuation
return i_mu
# Source: https://ui.adsabs.harvard.edu/abs/1950HarCi.454....1K/abstract
def quadratic(mu, c, i0=1.0):
"""
Calculates the intensity of a given cell in the stellar surface using a
quadratic limb-darkening law.
Parameters
----------
mu (``float`` or ``numpy.ndarray``):
Cosine of the angle between a line normal to the stellar surface and the
line of sight.
c (``array-like``):
Limb-darkening coefficients in the order c1, c2.
i0 (``float``, optional):
Intensity without limb-darkening. Default is 1.0.
Returns
-------
i_mu (``float`` or ``numpy.ndarray``):
Intensity with limb-darkening. The format is the same as the input
``mu``.
"""
c1, c2 = c
attenuation = 1 - c1 * (1 - mu) - c2 * (1 - mu) ** 2
i_mu = i0 * attenuation
return i_mu
# Source: https://ui.adsabs.harvard.edu/abs/1992A%26A...259..227D/abstract
def square_root(mu, c, i0=1.0):
"""
Calculates the intensity of a given cell in the stellar surface using a
square-root limb-darkening law.
Parameters
----------
mu (``float`` or ``numpy.ndarray``):
Cosine of the angle between a line normal to the stellar surface and the
line of sight.
c (``array-like``):
Limb-darkening coefficients in the order c1, c2.
i0 (``float``, optional):
Intensity without limb-darkening. Default is 1.0.
Returns
-------
i_mu (``float`` or ``numpy.ndarray``):
Intensity with limb-darkening. The format is the same as the input
``mu``.
"""
c1, c2 = c
attenuation = 1 - c1 * (1 - mu) - c2 * (1 - mu ** 0.5)
i_mu = i0 * attenuation
return i_mu
# Source: https://ui.adsabs.harvard.edu/abs/1970AJ.....75..175K/abstract
def logarithmic(mu, c, i0=1.0):
"""
Calculates the intensity of a given cell in the stellar surface using a
logarithmic limb-darkening law.
Parameters
----------
mu (``float`` or ``numpy.ndarray``):
Cosine of the angle between a line normal to the stellar surface and the
line of sight.
c (``array-like``):
Limb-darkening coefficients in the order c1, c2.
i0 (``float``, optional):
Intensity without limb-darkening. Default is 1.0.
Returns
-------
i_mu (``float`` or ``numpy.ndarray``):
Intensity with limb-darkening. The format is the same as the input
``mu``.
"""
c1, c2 = c
attenuation = 1 - c1 * (1 - mu) - c2 * mu * np.log(mu) ** 2
# Remove the NaNs
attenuation[np.isnan(attenuation)] = 0.0
i_mu = i0 * attenuation
return i_mu
# Source: https://ui.adsabs.harvard.edu/abs/2003A%26A...412..241C/abstract
def exponential(mu, c, i0=1.0):
"""
Calculates the intensity of a given cell in the stellar surface using an
exponential limb-darkening law.
Parameters
----------
mu (``float`` or ``numpy.ndarray``):
Cosine of the angle between a line normal to the stellar surface and the
line of sight.
c (``array-like``):
Limb-darkening coefficients in the order c1, c2.
i0 (``float``, optional):
Intensity without limb-darkening. Default is 1.0.
Returns
-------
i_mu (``float`` or ``numpy.ndarray``):
Intensity with limb-darkening. The format is the same as the input
``mu``.
"""
c1, c2 = c
# This particular limb-darkening law requires some sleight of hand to avoid
# numerical exceptions and warnings
term1 = np.copy(c1 * (1 - mu))
mu[mu <1E-16] = -np.inf
term2 = c2 / (1 - np.exp(mu))
attenuation = 1 - term1 - term2
i_mu = i0 * attenuation
return i_mu
# Source: https://ui.adsabs.harvard.edu/abs/2009A%26A...505..891S/abstract
def sing_three(mu, c, i0=1.0):
"""
Calculates the intensity of a given cell in the stellar surface using the
Sing et al (2009) limb-darkening law.
Parameters
----------
mu (``float`` or ``numpy.ndarray``):
Cosine of the angle between a line normal to the stellar surface and the
line of sight.
c (``array-like``):
Limb-darkening coefficients in the order c1, c2, c3.
i0 (``float``, optional):
Intensity without limb-darkening. Default is 1.0.
Returns
-------
i_mu (``float`` or ``numpy.ndarray``):
Intensity with limb-darkening. The format is the same as the input
``mu``.
"""
c1, c2, c3 = c
attenuation = 1 - c1 * (1 - mu) - c2 * (1 - mu ** (3 / 2)) - c3 * \
(1 - mu ** 2)
i_mu = i0 * attenuation
return i_mu
# Source: https://ui.adsabs.harvard.edu/abs/2000A%26A...363.1081C/abstract
def claret_four(mu, c, i0=1.0):
"""
Calculates the intensity of a given cell in the stellar surface using the
Claret et al. (2000) limb-darkening law.
Parameters
----------
mu (``float`` or ``numpy.ndarray``):
Cosine of the angle between a line normal to the stellar surface and the
line of sight.
c (``array-like``):
Limb-darkening coefficients in the order c1, c2, c3, c4.
i0 (``float``, optional):
Intensity without limb-darkening. Default is 1.0.
Returns
-------
i_mu (``float`` or ``numpy.ndarray``):
Intensity with limb-darkening. The format is the same as the input
``mu``.
"""
c1, c2, c3, c4 = c
attenuation = 1 - c1 * (1 - mu ** 0.5) - c2 * (1 - mu) - c3 * \
(1 - mu ** (3 / 2)) - c4 * (1 - mu ** 2)
i_mu = i0 * attenuation
return i_mu
|
ladsantosREPO_NAMEflatstarPATH_START.@flatstar_extracted@flatstar-main@flatstar@limb_darkening.py@.PATH_END.py
|
{
"filename": "default_layout.py",
"repo_name": "nu-radio/NuRadioMC",
"repo_path": "NuRadioMC_extracted/NuRadioMC-master/NuRadioReco/eventbrowser/default_layout.py",
"type": "Python"
}
|
default_layout = {
'margin': {
't': 15
},
'showlegend': True
}
efield_plot_colors = [
['rgb(91, 179, 240)', 'rgb(31, 119, 180)'],
['rgb(255, 187, 94)', 'rgb(255, 127, 14)'],
['rgb(104, 220, 104)', 'rgb(44, 160, 44)'],
['rgb(255, 99, 100)', 'rgb(214, 39, 40)'],
['rgb(208, 163, 249)', 'rgb(148, 103, 189)'],
['rgb(200, 146, 135)', 'rgb(140, 86, 75)']
]
efield_plot_linestyles = {
'direct': 'solid',
'reflected': 'dash',
'refracted': 'dot'
}
polarizaiton_names = ['r', 'theta', 'phi']
|
nu-radioREPO_NAMENuRadioMCPATH_START.@NuRadioMC_extracted@NuRadioMC-master@NuRadioReco@eventbrowser@default_layout.py@.PATH_END.py
|
{
"filename": "plotit.py",
"repo_name": "bolverk/huji-rich",
"repo_path": "huji-rich_extracted/huji-rich-master/tests/newtonian/one_dimensional/pure_advection_2o/plotit.py",
"type": "Python"
}
|
import pylab
import numpy
import re
import sys
import Tkinter
import glob
pref = re.sub(r'/[^/]*$','',sys.argv[0])
n = len(glob.glob(pref+'/center_list.[0-9]+.txt'))
if len(sys.argv)>1:
val = int(sys.argv[1])
else:
val = n
x_list = numpy.loadtxt(pref+'/center_list.'+str(val)+'.txt')
d_list = numpy.loadtxt(pref+'/density_list.'+str(val)+'.txt')
p_list = numpy.loadtxt(pref+'/pressure_list.'+str(val)+'.txt')
v_list = numpy.loadtxt(pref+'/xvelocity_list.'+str(val)+'.txt')
pylab.subplot(311)
pylab.plot(x_list,d_list)
pylab.ylabel('Density')
pylab.subplot(312)
pylab.plot(x_list,p_list)
pylab.ylabel('Pressure')
pylab.subplot(313)
pylab.plot(x_list,v_list)
pylab.ylabel('Velocity')
pylab.xlabel('Distance')
pylab.show()
|
bolverkREPO_NAMEhuji-richPATH_START.@huji-rich_extracted@huji-rich-master@tests@newtonian@one_dimensional@pure_advection_2o@plotit.py@.PATH_END.py
|
{
"filename": "_textcase.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scattergeo/textfont/_textcase.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class TextcaseValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="textcase", parent_name="scattergeo.textfont", **kwargs
):
super(TextcaseValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop("values", ["normal", "word caps", "upper", "lower"]),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scattergeo@textfont@_textcase.py@.PATH_END.py
|
{
"filename": "_sizemode.py",
"repo_name": "plotly/plotly.py",
"repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/scatterpolargl/marker/_sizemode.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class SizemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="sizemode", parent_name="scatterpolargl.marker", **kwargs
):
super(SizemodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop("values", ["diameter", "area"]),
**kwargs,
)
|
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@scatterpolargl@marker@_sizemode.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "plotly/plotly.py",
"repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/tests/test_optional/test_kaleido/__init__.py",
"type": "Python"
}
|
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@tests@test_optional@test_kaleido@__init__.py@.PATH_END.py
|
|
{
"filename": "test_mapmaking.py",
"repo_name": "litebird/litebird_sim",
"repo_path": "litebird_sim_extracted/litebird_sim-master/test/test_mapmaking.py",
"type": "Python"
}
|
# -*- encoding: utf-8 -*-
import numpy as np
from litebird_sim.mapmaking.common import cholesky, solve_cholesky, estimate_cond_number
def _generate_random_positive_definite_matrix(
N: int, random: np.random.Generator
) -> np.ndarray:
"""Return a random 3×3 matrix that is symmetric and positive definite"""
# Use Eq. 10 in KurkiSuonio2009 to create an M matrix for a
# pixel that has been observed 10 times with random ψ angles
angles = random.random(10) * np.pi
# We pick a random value for σ (we need to rescale each
# coefficient by 1/σ²)
sigma = random.random() + 0.5
A = np.zeros((N, N))
for cur_angle in angles:
A[0, 0] += 1.0
A[0, 1] += np.cos(2 * cur_angle)
A[0, 2] += np.sin(2 * cur_angle)
A[1, 1] += np.cos(2 * cur_angle) ** 2
A[1, 2] += np.cos(2 * cur_angle) * np.sin(2 * cur_angle)
A[2, 2] += np.sin(2 * cur_angle) ** 2
A[1, 0] = A[0, 1]
A[2, 0] = A[0, 2]
A[2, 1] = A[1, 2]
return A / sigma**2
def test_cholesky_and_solve_random():
# To check the correctness of the two methods `cholesky` and `solve_cholesky`,
# we generate a high number of random 3×3 matrices that satisfy the two
# properties of (1) symmetry, and (2) positive definiteness, and we check
# that the results of our functions match the ones returned by the (slower)
# numpy.linalg.cholesky and numpy.linalg.solve
random = np.random.Generator(np.random.PCG64(12345))
# Run the test on 1000 matrices
for i in range(1000):
A = _generate_random_positive_definite_matrix(3, random)
assert np.allclose(np.transpose(A), A)
L = np.empty(6)
cholesky(
a00=A[0, 0],
a10=A[1, 0],
a11=A[1, 1],
a20=A[2, 0],
a21=A[2, 1],
a22=A[2, 2],
dest_L=L,
)
numpy_L = np.linalg.cholesky(A)
# L[0] = l₀₀
np.testing.assert_almost_equal(actual=L[0], desired=numpy_L[0][0])
# L[1] = l₁₀
np.testing.assert_almost_equal(actual=L[1], desired=numpy_L[1][0])
# L[2] = l₁₁
np.testing.assert_almost_equal(actual=L[2], desired=numpy_L[1][1])
# L[3] = l₂₀
np.testing.assert_almost_equal(actual=L[3], desired=numpy_L[2][0])
# L[4] = l₂₁
np.testing.assert_almost_equal(actual=L[4], desired=numpy_L[2][1])
# L[5] = l₂₂"""
np.testing.assert_almost_equal(actual=L[5], desired=numpy_L[2][2])
v = np.array([1.0, 2.0, 3.0])
x = np.empty(3)
x[:] = solve_cholesky(L=L, v0=v[0], v1=v[1], v2=v[2])
np.testing.assert_allclose(actual=x, desired=np.linalg.solve(A, v))
def test_estimate_cond_number():
random = np.random.Generator(np.random.PCG64(12345))
# Run the test on 1000 matrices
for i in range(1000):
A = _generate_random_positive_definite_matrix(3, random)
assert np.allclose(np.transpose(A), A)
(cond, found) = estimate_cond_number(
a00=A[0][0],
a10=A[1][0],
a11=A[1][1],
a20=A[2][0],
a21=A[2][1],
a22=A[2][2],
)
if found:
np.testing.assert_almost_equal(actual=cond, desired=np.linalg.cond(A))
|
litebirdREPO_NAMElitebird_simPATH_START.@litebird_sim_extracted@litebird_sim-master@test@test_mapmaking.py@.PATH_END.py
|
{
"filename": "README.md",
"repo_name": "j-faria/kima",
"repo_path": "kima_extracted/kima-master/eigen/unsupported/Eigen/CXX11/src/Tensor/README.md",
"type": "Markdown"
}
|
# Eigen Tensors {#eigen_tensors}
Tensors are multidimensional arrays of elements. Elements are typically scalars,
but more complex types such as strings are also supported.
[TOC]
## Tensor Classes
You can manipulate a tensor with one of the following classes. They all are in
the namespace `::Eigen.`
### Class Tensor<data_type, rank>
This is the class to use to create a tensor and allocate memory for it. The
class is templatized with the tensor datatype, such as float or int, and the
tensor rank. The rank is the number of dimensions, for example rank 2 is a
matrix.
Tensors of this class are resizable. For example, if you assign a tensor of a
different size to a Tensor, that tensor is resized to match its new value.
#### Constructor `Tensor<data_type, rank>(size0, size1, ...)`
Constructor for a Tensor. The constructor must be passed `rank` integers
indicating the sizes of the instance along each of the the `rank`
dimensions.
// Create a tensor of rank 3 of sizes 2, 3, 4. This tensor owns
// memory to hold 24 floating point values (24 = 2 x 3 x 4).
Tensor<float, 3> t_3d(2, 3, 4);
// Resize t_3d by assigning a tensor of different sizes, but same rank.
t_3d = Tensor<float, 3>(3, 4, 3);
#### Constructor `Tensor<data_type, rank>(size_array)`
Constructor where the sizes for the constructor are specified as an array of
values instead of an explicitly list of parameters. The array type to use is
`Eigen::array<Eigen::Index>`. The array can be constructed automatically
from an initializer list.
// Create a tensor of strings of rank 2 with sizes 5, 7.
Tensor<string, 2> t_2d({5, 7});
### Class `TensorFixedSize<data_type, Sizes<size0, size1, ...>>`
Class to use for tensors of fixed size, where the size is known at compile
time. Fixed sized tensors can provide very fast computations because all their
dimensions are known by the compiler. FixedSize tensors are not resizable.
If the total number of elements in a fixed size tensor is small enough the
tensor data is held onto the stack and does not cause heap allocation and free.
// Create a 4 x 3 tensor of floats.
TensorFixedSize<float, Sizes<4, 3>> t_4x3;
### Class `TensorMap<Tensor<data_type, rank>>`
This is the class to use to create a tensor on top of memory allocated and
owned by another part of your code. It allows to view any piece of allocated
memory as a Tensor. Instances of this class do not own the memory where the
data are stored.
A TensorMap is not resizable because it does not own the memory where its data
are stored.
#### Constructor `TensorMap<Tensor<data_type, rank>>(data, size0, size1, ...)`
Constructor for a Tensor. The constructor must be passed a pointer to the
storage for the data, and "rank" size attributes. The storage has to be
large enough to hold all the data.
// Map a tensor of ints on top of stack-allocated storage.
int storage[128]; // 2 x 4 x 2 x 8 = 128
TensorMap<Tensor<int, 4>> t_4d(storage, 2, 4, 2, 8);
// The same storage can be viewed as a different tensor.
// You can also pass the sizes as an array.
TensorMap<Tensor<int, 2>> t_2d(storage, 16, 8);
// You can also map fixed-size tensors. Here we get a 1d view of
// the 2d fixed-size tensor.
TensorFixedSize<float, Sizes<4, 5>> t_4x3;
TensorMap<Tensor<float, 1>> t_12(t_4x3.data(), 12);
#### Class `TensorRef`
See Assigning to a TensorRef below.
## Accessing Tensor Elements
#### `<data_type> tensor(index0, index1...)`
Return the element at position `(index0, index1...)` in tensor
`tensor`. You must pass as many parameters as the rank of `tensor`.
The expression can be used as an l-value to set the value of the element at the
specified position. The value returned is of the datatype of the tensor.
// Set the value of the element at position (0, 1, 0);
Tensor<float, 3> t_3d(2, 3, 4);
t_3d(0, 1, 0) = 12.0f;
// Initialize all elements to random values.
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 4; ++k) {
t_3d(i, j, k) = ...some random value...;
}
}
}
// Print elements of a tensor.
for (int i = 0; i < 2; ++i) {
LOG(INFO) << t_3d(i, 0, 0);
}
## TensorLayout
The tensor library supports 2 layouts: `ColMajor` (the default) and
`RowMajor`. Only the default column major layout is currently fully
supported, and it is therefore not recommended to attempt to use the row major
layout at the moment.
The layout of a tensor is optionally specified as part of its type. If not
specified explicitly column major is assumed.
Tensor<float, 3, ColMajor> col_major; // equivalent to Tensor<float, 3>
TensorMap<Tensor<float, 3, RowMajor> > row_major(data, ...);
All the arguments to an expression must use the same layout. Attempting to mix
different layouts will result in a compilation error.
It is possible to change the layout of a tensor or an expression using the
`swap_layout()` method. Note that this will also reverse the order of the
dimensions.
Tensor<float, 2, ColMajor> col_major(2, 4);
Tensor<float, 2, RowMajor> row_major(2, 4);
Tensor<float, 2> col_major_result = col_major; // ok, layouts match
Tensor<float, 2> col_major_result = row_major; // will not compile
// Simple layout swap
col_major_result = row_major.swap_layout();
eigen_assert(col_major_result.dimension(0) == 4);
eigen_assert(col_major_result.dimension(1) == 2);
// Swap the layout and preserve the order of the dimensions
array<int, 2> shuffle(1, 0);
col_major_result = row_major.swap_layout().shuffle(shuffle);
eigen_assert(col_major_result.dimension(0) == 2);
eigen_assert(col_major_result.dimension(1) == 4);
## Tensor Operations
The Eigen Tensor library provides a vast library of operations on Tensors:
numerical operations such as addition and multiplication, geometry operations
such as slicing and shuffling, etc. These operations are available as methods
of the Tensor classes, and in some cases as operator overloads. For example
the following code computes the elementwise addition of two tensors:
Tensor<float, 3> t1(2, 3, 4);
...set some values in t1...
Tensor<float, 3> t2(2, 3, 4);
...set some values in t2...
// Set t3 to the element wise sum of t1 and t2
Tensor<float, 3> t3 = t1 + t2;
While the code above looks easy enough, it is important to understand that the
expression `t1 + t2` is not actually adding the values of the tensors. The
expression instead constructs a "tensor operator" object of the class
TensorCwiseBinaryOp<scalar_sum>, which has references to the tensors
`t1` and `t2`. This is a small C++ object that knows how to add
`t1` and `t2`. It is only when the value of the expression is assigned
to the tensor `t3` that the addition is actually performed. Technically,
this happens through the overloading of `operator=()` in the Tensor class.
This mechanism for computing tensor expressions allows for lazy evaluation and
optimizations which are what make the tensor library very fast.
Of course, the tensor operators do nest, and the expression `t1 + t2 * 0.3f`
is actually represented with the (approximate) tree of operators:
TensorCwiseBinaryOp<scalar_sum>(t1, TensorCwiseUnaryOp<scalar_mul>(t2, 0.3f))
### Tensor Operations and C++ "auto"
Because Tensor operations create tensor operators, the C++ `auto` keyword
does not have its intuitive meaning. Consider these 2 lines of code:
Tensor<float, 3> t3 = t1 + t2;
auto t4 = t1 + t2;
In the first line we allocate the tensor `t3` and it will contain the
result of the addition of `t1` and `t2`. In the second line, `t4`
is actually the tree of tensor operators that will compute the addition of
`t1` and `t2`. In fact, `t4` is *not* a tensor and you cannot get
the values of its elements:
Tensor<float, 3> t3 = t1 + t2;
cout << t3(0, 0, 0); // OK prints the value of t1(0, 0, 0) + t2(0, 0, 0)
auto t4 = t1 + t2;
cout << t4(0, 0, 0); // Compilation error!
When you use `auto` you do not get a Tensor as a result but instead a
non-evaluated expression. So only use `auto` to delay evaluation.
Unfortunately, there is no single underlying concrete type for holding
non-evaluated expressions, hence you have to use auto in the case when you do
want to hold non-evaluated expressions.
When you need the results of set of tensor computations you have to assign the
result to a Tensor that will be capable of holding onto them. This can be
either a normal Tensor, a fixed size Tensor, or a TensorMap on an existing
piece of memory. All the following will work:
auto t4 = t1 + t2;
Tensor<float, 3> result = t4; // Could also be: result(t4);
cout << result(0, 0, 0);
TensorMap<float, 4> result(<a float* with enough space>, <size0>, ...) = t4;
cout << result(0, 0, 0);
TensorFixedSize<float, Sizes<size0, ...>> result = t4;
cout << result(0, 0, 0);
Until you need the results, you can keep the operation around, and even reuse
it for additional operations. As long as you keep the expression as an
operation, no computation is performed.
// One way to compute exp((t1 + t2) * 0.2f);
auto t3 = t1 + t2;
auto t4 = t3 * 0.2f;
auto t5 = t4.exp();
Tensor<float, 3> result = t5;
// Another way, exactly as efficient as the previous one:
Tensor<float, 3> result = ((t1 + t2) * 0.2f).exp();
### Controlling When Expression are Evaluated
There are several ways to control when expressions are evaluated:
* Assignment to a Tensor, TensorFixedSize, or TensorMap.
* Use of the eval() method.
* Assignment to a TensorRef.
#### Assigning to a Tensor, TensorFixedSize, or TensorMap.
The most common way to evaluate an expression is to assign it to a Tensor. In
the example below, the `auto` declarations make the intermediate values
"Operations", not Tensors, and do not cause the expressions to be evaluated.
The assignment to the Tensor `result` causes the evaluation of all the
operations.
auto t3 = t1 + t2; // t3 is an Operation.
auto t4 = t3 * 0.2f; // t4 is an Operation.
auto t5 = t4.exp(); // t5 is an Operation.
Tensor<float, 3> result = t5; // The operations are evaluated.
If you know the ranks and sizes of the Operation value you can assign the
Operation to a TensorFixedSize instead of a Tensor, which is a bit more
efficient.
// We know that the result is a 4x4x2 tensor!
TensorFixedSize<float, Sizes<4, 4, 2>> result = t5;
Simiarly, assigning an expression to a TensorMap causes its evaluation. Like
tensors of type TensorFixedSize, TensorMaps cannot be resized so they have to
have the rank and sizes of the expression that are assigned to them.
#### Calling `eval()`.
When you compute large composite expressions, you sometimes want to tell Eigen
that an intermediate value in the expression tree is worth evaluating ahead of
time. This is done by inserting a call to the `eval()` method of the
expression Operation.
// The previous example could have been written:
Tensor<float, 3> result = ((t1 + t2) * 0.2f).exp();
// If you want to compute (t1 + t2) once ahead of time you can write:
Tensor<float, 3> result = ((t1 + t2).eval() * 0.2f).exp();
Semantically, calling `eval()` is equivalent to materializing the value of
the expression in a temporary Tensor of the right size. The code above in
effect does:
// .eval() knows the size!
TensorFixedSize<float, Sizes<4, 4, 2>> tmp = t1 + t2;
Tensor<float, 3> result = (tmp * 0.2f).exp();
Note that the return value of `eval()` is itself an Operation, so the
following code does not do what you may think:
// Here t3 is an evaluation Operation. t3 has not been evaluated yet.
auto t3 = (t1 + t2).eval();
// You can use t3 in another expression. Still no evaluation.
auto t4 = (t3 * 0.2f).exp();
// The value is evaluated when you assign the Operation to a Tensor, using
// an intermediate tensor to represent t3.x
Tensor<float, 3> result = t4;
While in the examples above calling `eval()` does not make a difference in
performance, in other cases it can make a huge difference. In the expression
below the `broadcast()` expression causes the `X.maximum()` expression
to be evaluated many times:
Tensor<...> X ...;
Tensor<...> Y = ((X - X.maximum(depth_dim).reshape(dims2d).broadcast(bcast))
* beta).exp();
Inserting a call to `eval()` between the `maximum()` and
`reshape()` calls guarantees that maximum() is only computed once and
greatly speeds-up execution:
Tensor<...> Y =
((X - X.maximum(depth_dim).eval().reshape(dims2d).broadcast(bcast))
* beta).exp();
In the other example below, the tensor `Y` is both used in the expression
and its assignment. This is an aliasing problem and if the evaluation is not
done in the right order Y will be updated incrementally during the evaluation
resulting in bogus results:
Tensor<...> Y ...;
Y = Y / (Y.sum(depth_dim).reshape(dims2d).broadcast(bcast));
Inserting a call to `eval()` between the `sum()` and `reshape()`
expressions ensures that the sum is computed before any updates to `Y` are
done.
Y = Y / (Y.sum(depth_dim).eval().reshape(dims2d).broadcast(bcast));
Note that an eval around the full right hand side expression is not needed
because the generated has to compute the i-th value of the right hand side
before assigning it to the left hand side.
However, if you were assigning the expression value to a shuffle of `Y`
then you would need to force an eval for correctness by adding an `eval()`
call for the right hand side:
Y.shuffle(...) =
(Y / (Y.sum(depth_dim).eval().reshape(dims2d).broadcast(bcast))).eval();
#### Assigning to a `TensorRef`.
If you need to access only a few elements from the value of an expression you
can avoid materializing the value in a full tensor by using a TensorRef.
A TensorRef is a small wrapper class for any Eigen Operation. It provides
overloads for the `()` operator that let you access individual values in
the expression. TensorRef is convenient, because the Operation themselves do
not provide a way to access individual elements.
// Create a TensorRef for the expression. The expression is not
// evaluated yet.
TensorRef<Tensor<float, 3> > ref = ((t1 + t2) * 0.2f).exp();
// Use "ref" to access individual elements. The expression is evaluated
// on the fly.
float at_0 = ref(0, 0, 0);
cout << ref(0, 1, 0);
Only use TensorRef when you need a subset of the values of the expression.
TensorRef only computes the values you access. However note that if you are
going to access all the values it will be much faster to materialize the
results in a Tensor first.
In some cases, if the full Tensor result would be very large, you may save
memory by accessing it as a TensorRef. But not always. So don't count on it.
### Controlling How Expressions Are Evaluated
The tensor library provides several implementations of the various operations
such as contractions and convolutions. The implementations are optimized for
different environments: single threaded on CPU, multi threaded on CPU, or on a
GPU using cuda. Additional implementations may be added later.
You can choose which implementation to use with the `device()` call. If
you do not choose an implementation explicitly the default implementation that
uses a single thread on the CPU is used.
The default implementation has been optimized for recent Intel CPUs, taking
advantage of SSE, AVX, and FMA instructions. Work is ongoing to tune the
library on ARM CPUs. Note that you need to pass compiler-dependent flags
to enable the use of SSE, AVX, and other instructions.
For example, the following code adds two tensors using the default
single-threaded CPU implementation:
Tensor<float, 2> a(30, 40);
Tensor<float, 2> b(30, 40);
Tensor<float, 2> c = a + b;
To choose a different implementation you have to insert a `device()` call
before the assignment of the result. For technical C++ reasons this requires
that the Tensor for the result be declared on its own. This means that you
have to know the size of the result.
Eigen::Tensor<float, 2> c(30, 40);
c.device(...) = a + b;
The call to `device()` must be the last call on the left of the operator=.
You must pass to the `device()` call an Eigen device object. There are
presently three devices you can use: DefaultDevice, ThreadPoolDevice and
GpuDevice.
#### Evaluating With the DefaultDevice
This is exactly the same as not inserting a `device()` call.
DefaultDevice my_device;
c.device(my_device) = a + b;
#### Evaluating with a Thread Pool
// Create the Eigen ThreadPool
Eigen::ThreadPool pool(8 /* number of threads in pool */)
// Create the Eigen ThreadPoolDevice.
Eigen::ThreadPoolDevice my_device(&pool, 4 /* number of threads to use */);
// Now just use the device when evaluating expressions.
Eigen::Tensor<float, 2> c(30, 50);
c.device(my_device) = a.contract(b, dot_product_dims);
#### Evaluating On GPU
This is presently a bit more complicated than just using a thread pool device.
You need to create a GPU device but you also need to explicitly allocate the
memory for tensors with cuda.
## API Reference
### Datatypes
In the documentation of the tensor methods and Operation we mention datatypes
that are tensor-type specific:
#### `<Tensor-Type>::``Dimensions`
Acts like an array of ints. Has an `int size` attribute, and can be
indexed like an array to access individual values. Used to represent the
dimensions of a tensor. See `dimensions()`.
#### `<Tensor-Type>::``Index`
Acts like an `int`. Used for indexing tensors along their dimensions. See
`operator()`, `dimension()`, and `size()`.
#### `<Tensor-Type>::``Scalar`
Represents the datatype of individual tensor elements. For example, for a
`Tensor<float>`, `Scalar` is the type `float`. See
`setConstant()`.
#### `<Operation>`
We use this pseudo type to indicate that a tensor Operation is returned by a
method. We indicate in the text the type and dimensions of the tensor that the
Operation returns after evaluation.
The Operation will have to be evaluated, for example by assigning it to a
tensor, before you can access the values of the resulting tensor. You can also
access the values through a TensorRef.
## Built-in Tensor Methods
These are usual C++ methods that act on tensors immediately. They are not
Operations which provide delayed evaluation of their results. Unless specified
otherwise, all the methods listed below are available on all tensor classes:
Tensor, TensorFixedSize, and TensorMap.
## Metadata
### `int NumDimensions`
Constant value indicating the number of dimensions of a Tensor. This is also
known as the tensor "rank".
Eigen::Tensor<float, 2> a(3, 4);
cout << "Dims " << a.NumDimensions;
=> Dims 2
### `Dimensions dimensions()`
Returns an array-like object representing the dimensions of the tensor.
The actual type of the `dimensions()` result is `<Tensor-Type>::``Dimensions`.
Eigen::Tensor<float, 2> a(3, 4);
const Eigen::Tensor<float, 2>::Dimensions& d = a.dimensions();
cout << "Dim size: " << d.size << ", dim 0: " << d[0]
<< ", dim 1: " << d[1];
=> Dim size: 2, dim 0: 3, dim 1: 4
If you use a C++11 compiler, you can use `auto` to simplify the code:
const auto& d = a.dimensions();
cout << "Dim size: " << d.size << ", dim 0: " << d[0]
<< ", dim 1: " << d[1];
=> Dim size: 2, dim 0: 3, dim 1: 4
### `Index dimension(Index n)`
Returns the n-th dimension of the tensor. The actual type of the
`dimension()` result is `<Tensor-Type>::``Index`, but you can
always use it like an int.
Eigen::Tensor<float, 2> a(3, 4);
int dim1 = a.dimension(1);
cout << "Dim 1: " << dim1;
=> Dim 1: 4
### `Index size()`
Returns the total number of elements in the tensor. This is the product of all
the tensor dimensions. The actual type of the `size()` result is
`<Tensor-Type>::``Index`, but you can always use it like an int.
Eigen::Tensor<float, 2> a(3, 4);
cout << "Size: " << a.size();
=> Size: 12
### Getting Dimensions From An Operation
A few operations provide `dimensions()` directly,
e.g. `TensorReslicingOp`. Most operations defer calculating dimensions
until the operation is being evaluated. If you need access to the dimensions
of a deferred operation, you can wrap it in a TensorRef (see Assigning to a
TensorRef above), which provides `dimensions()` and `dimension()` as
above.
TensorRef can also wrap the plain Tensor types, so this is a useful idiom in
templated contexts where the underlying object could be either a raw Tensor
or some deferred operation (e.g. a slice of a Tensor). In this case, the
template code can wrap the object in a TensorRef and reason about its
dimensionality while remaining agnostic to the underlying type.
## Constructors
### Tensor
Creates a tensor of the specified size. The number of arguments must be equal
to the rank of the tensor. The content of the tensor is not initialized.
Eigen::Tensor<float, 2> a(3, 4);
cout << "NumRows: " << a.dimension(0) << " NumCols: " << a.dimension(1) << endl;
=> NumRows: 3 NumCols: 4
### TensorFixedSize
Creates a tensor of the specified size. The number of arguments in the Sizes<>
template parameter determines the rank of the tensor. The content of the tensor
is not initialized.
Eigen::TensorFixedSize<float, Sizes<3, 4>> a;
cout << "Rank: " << a.rank() << endl;
=> Rank: 2
cout << "NumRows: " << a.dimension(0) << " NumCols: " << a.dimension(1) << endl;
=> NumRows: 3 NumCols: 4
### TensorMap
Creates a tensor mapping an existing array of data. The data must not be freed
until the TensorMap is discarded, and the size of the data must be large enough
to accommodate the coefficients of the tensor.
float data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Eigen::TensorMap<Tensor<float, 2>> a(data, 3, 4);
cout << "NumRows: " << a.dimension(0) << " NumCols: " << a.dimension(1) << endl;
=> NumRows: 3 NumCols: 4
cout << "a(1, 2): " << a(1, 2) << endl;
=> a(1, 2): 7
## Contents Initialization
When a new Tensor or a new TensorFixedSize are created, memory is allocated to
hold all the tensor elements, but the memory is not initialized. Similarly,
when a new TensorMap is created on top of non-initialized memory the memory its
contents are not initialized.
You can use one of the methods below to initialize the tensor memory. These
have an immediate effect on the tensor and return the tensor itself as a
result. These are not tensor Operations which delay evaluation.
### `<Tensor-Type> setConstant(const Scalar& val)`
Sets all elements of the tensor to the constant value `val`. `Scalar`
is the type of data stored in the tensor. You can pass any value that is
convertible to that type.
Returns the tensor itself in case you want to chain another call.
a.setConstant(12.3f);
cout << "Constant: " << endl << a << endl << endl;
=>
Constant:
12.3 12.3 12.3 12.3
12.3 12.3 12.3 12.3
12.3 12.3 12.3 12.3
Note that `setConstant()` can be used on any tensor where the element type
has a copy constructor and an `operator=()`:
Eigen::Tensor<string, 2> a(2, 3);
a.setConstant("yolo");
cout << "String tensor: " << endl << a << endl << endl;
=>
String tensor:
yolo yolo yolo
yolo yolo yolo
### `<Tensor-Type> setZero()`
Fills the tensor with zeros. Equivalent to `setConstant(Scalar(0))`.
Returns the tensor itself in case you want to chain another call.
a.setZero();
cout << "Zeros: " << endl << a << endl << endl;
=>
Zeros:
0 0 0 0
0 0 0 0
0 0 0 0
### `<Tensor-Type> setValues({..initializer_list})`
Fills the tensor with explicit values specified in a std::initializer_list.
The type of the initializer list depends on the type and rank of the tensor.
If the tensor has rank N, the initializer list must be nested N times. The
most deeply nested lists must contains P scalars of the Tensor type where P is
the size of the last dimension of the Tensor.
For example, for a `TensorFixedSize<float, 2, 3>` the initializer list must
contains 2 lists of 3 floats each.
`setValues()` returns the tensor itself in case you want to chain another
call.
Eigen::Tensor<float, 2> a(2, 3);
a.setValues({{0.0f, 1.0f, 2.0f}, {3.0f, 4.0f, 5.0f}});
cout << "a" << endl << a << endl << endl;
=>
a
0 1 2
3 4 5
If a list is too short, the corresponding elements of the tensor will not be
changed. This is valid at each level of nesting. For example the following
code only sets the values of the first row of the tensor.
Eigen::Tensor<int, 2> a(2, 3);
a.setConstant(1000);
a.setValues({{10, 20, 30}});
cout << "a" << endl << a << endl << endl;
=>
a
10 20 30
1000 1000 1000
### `<Tensor-Type> setRandom()`
Fills the tensor with random values. Returns the tensor itself in case you
want to chain another call.
a.setRandom();
cout << "Random: " << endl << a << endl << endl;
=>
Random:
0.680375 0.59688 -0.329554 0.10794
-0.211234 0.823295 0.536459 -0.0452059
0.566198 -0.604897 -0.444451 0.257742
You can customize `setRandom()` by providing your own random number
generator as a template argument:
a.setRandom<MyRandomGenerator>();
Here, `MyRandomGenerator` must be a struct with the following member
functions, where Scalar and Index are the same as `<Tensor-Type>::``Scalar`
and `<Tensor-Type>::``Index`.
See `struct UniformRandomGenerator` in TensorFunctors.h for an example.
// Custom number generator for use with setRandom().
struct MyRandomGenerator {
// Default and copy constructors. Both are needed
MyRandomGenerator() { }
MyRandomGenerator(const MyRandomGenerator& ) { }
// Return a random value to be used. "element_location" is the
// location of the entry to set in the tensor, it can typically
// be ignored.
Scalar operator()(Eigen::DenseIndex element_location,
Eigen::DenseIndex /*unused*/ = 0) const {
return <randomly generated value of type T>;
}
// Same as above but generates several numbers at a time.
typename internal::packet_traits<Scalar>::type packetOp(
Eigen::DenseIndex packet_location, Eigen::DenseIndex /*unused*/ = 0) const {
return <a packet of randomly generated values>;
}
};
You can also use one of the 2 random number generators that are part of the
tensor library:
* UniformRandomGenerator
* NormalRandomGenerator
## Data Access
The Tensor, TensorFixedSize, and TensorRef classes provide the following
accessors to access the tensor coefficients:
const Scalar& operator()(const array<Index, NumIndices>& indices)
const Scalar& operator()(Index firstIndex, IndexTypes... otherIndices)
Scalar& operator()(const array<Index, NumIndices>& indices)
Scalar& operator()(Index firstIndex, IndexTypes... otherIndices)
The number of indices must be equal to the rank of the tensor. Moreover, these
accessors are not available on tensor expressions. In order to access the
values of a tensor expression, the expression must either be evaluated or
wrapped in a TensorRef.
### `Scalar* data()` and `const Scalar* data() const`
Returns a pointer to the storage for the tensor. The pointer is const if the
tensor was const. This allows direct access to the data. The layout of the
data depends on the tensor layout: RowMajor or ColMajor.
This access is usually only needed for special cases, for example when mixing
Eigen Tensor code with other libraries.
Scalar is the type of data stored in the tensor.
Eigen::Tensor<float, 2> a(3, 4);
float* a_data = a.data();
a_data[0] = 123.45f;
cout << "a(0, 0): " << a(0, 0);
=> a(0, 0): 123.45
## Tensor Operations
All the methods documented below return non evaluated tensor `Operations`.
These can be chained: you can apply another Tensor Operation to the value
returned by the method.
The chain of Operation is evaluated lazily, typically when it is assigned to a
tensor. See "Controlling when Expression are Evaluated" for more details about
their evaluation.
### `<Operation> constant(const Scalar& val)`
Returns a tensor of the same type and dimensions as the original tensor but
where all elements have the value `val`.
This is useful, for example, when you want to add or subtract a constant from a
tensor, or multiply every element of a tensor by a scalar.
Eigen::Tensor<float, 2> a(2, 3);
a.setConstant(1.0f);
Eigen::Tensor<float, 2> b = a + a.constant(2.0f);
Eigen::Tensor<float, 2> c = b * b.constant(0.2f);
cout << "a" << endl << a << endl << endl;
cout << "b" << endl << b << endl << endl;
cout << "c" << endl << c << endl << endl;
=>
a
1 1 1
1 1 1
b
3 3 3
3 3 3
c
0.6 0.6 0.6
0.6 0.6 0.6
### `<Operation> random()`
Returns a tensor of the same type and dimensions as the current tensor
but where all elements have random values.
This is for example useful to add random values to an existing tensor.
The generation of random values can be customized in the same manner
as for `setRandom()`.
Eigen::Tensor<float, 2> a(2, 3);
a.setConstant(1.0f);
Eigen::Tensor<float, 2> b = a + a.random();
cout << "a" << endl << a << endl << endl;
cout << "b" << endl << b << endl << endl;
=>
a
1 1 1
1 1 1
b
1.68038 1.5662 1.82329
0.788766 1.59688 0.395103
## Unary Element Wise Operations
All these operations take a single input tensor as argument and return a tensor
of the same type and dimensions as the tensor to which they are applied. The
requested operations are applied to each element independently.
### `<Operation> operator-()`
Returns a tensor of the same type and dimensions as the original tensor
containing the opposite values of the original tensor.
Eigen::Tensor<float, 2> a(2, 3);
a.setConstant(1.0f);
Eigen::Tensor<float, 2> b = -a;
cout << "a" << endl << a << endl << endl;
cout << "b" << endl << b << endl << endl;
=>
a
1 1 1
1 1 1
b
-1 -1 -1
-1 -1 -1
### `<Operation> sqrt()`
Returns a tensor of the same type and dimensions as the original tensor
containing the square roots of the original tensor.
### `<Operation> rsqrt()`
Returns a tensor of the same type and dimensions as the original tensor
containing the inverse square roots of the original tensor.
### `<Operation> square()`
Returns a tensor of the same type and dimensions as the original tensor
containing the squares of the original tensor values.
### `<Operation> inverse()`
Returns a tensor of the same type and dimensions as the original tensor
containing the inverse of the original tensor values.
### `<Operation> exp()`
Returns a tensor of the same type and dimensions as the original tensor
containing the exponential of the original tensor.
### `<Operation> log()`
Returns a tensor of the same type and dimensions as the original tensor
containing the natural logarithms of the original tensor.
### `<Operation> abs()`
Returns a tensor of the same type and dimensions as the original tensor
containing the absolute values of the original tensor.
### `<Operation> pow(Scalar exponent)`
Returns a tensor of the same type and dimensions as the original tensor
containing the coefficients of the original tensor to the power of the
exponent.
The type of the exponent, Scalar, is always the same as the type of the
tensor coefficients. For example, only integer exponents can be used in
conjuntion with tensors of integer values.
You can use cast() to lift this restriction. For example this computes
cubic roots of an int Tensor:
Eigen::Tensor<int, 2> a(2, 3);
a.setValues({{0, 1, 8}, {27, 64, 125}});
Eigen::Tensor<double, 2> b = a.cast<double>().pow(1.0 / 3.0);
cout << "a" << endl << a << endl << endl;
cout << "b" << endl << b << endl << endl;
=>
a
0 1 8
27 64 125
b
0 1 2
3 4 5
### `<Operation> operator * (Scalar scale)`
Multiplies all the coefficients of the input tensor by the provided scale.
### `<Operation> cwiseMax(Scalar threshold)`
TODO
### `<Operation> cwiseMin(Scalar threshold)`
TODO
### `<Operation> unaryExpr(const CustomUnaryOp& func)`
TODO
## Binary Element Wise Operations
These operations take two input tensors as arguments. The 2 input tensors should
be of the same type and dimensions. The result is a tensor of the same
dimensions as the tensors to which they are applied, and unless otherwise
specified it is also of the same type. The requested operations are applied to
each pair of elements independently.
### `<Operation> operator+(const OtherDerived& other)`
Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise sums of the inputs.
### `<Operation> operator-(const OtherDerived& other)`
Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise differences of the inputs.
### `<Operation> operator*(const OtherDerived& other)`
Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise products of the inputs.
### `<Operation> operator/(const OtherDerived& other)`
Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise quotients of the inputs.
This operator is not supported for integer types.
### `<Operation> cwiseMax(const OtherDerived& other)`
Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise maximums of the inputs.
### `<Operation> cwiseMin(const OtherDerived& other)`
Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise mimimums of the inputs.
### `<Operation> Logical operators`
The following logical operators are supported as well:
* operator&&(const OtherDerived& other)
* operator||(const OtherDerived& other)
* operator<(const OtherDerived& other)
* operator<=(const OtherDerived& other)
* operator>(const OtherDerived& other)
* operator>=(const OtherDerived& other)
* operator==(const OtherDerived& other)
* operator!=(const OtherDerived& other)
They all return a tensor of boolean values.
## Selection (select(const ThenDerived& thenTensor, const ElseDerived& elseTensor)
Selection is a coefficient-wise ternary operator that is the tensor equivalent
to the if-then-else operation.
Tensor<bool, 3> if = ...;
Tensor<float, 3> then = ...;
Tensor<float, 3> else = ...;
Tensor<float, 3> result = if.select(then, else);
The 3 arguments must be of the same dimensions, which will also be the dimension
of the result. The 'if' tensor must be of type boolean, the 'then' and the
'else' tensor must be of the same type, which will also be the type of the
result.
Each coefficient in the result is equal to the corresponding coefficient in the
'then' tensor if the corresponding value in the 'if' tensor is true. If not, the
resulting coefficient will come from the 'else' tensor.
## Contraction
Tensor *contractions* are a generalization of the matrix product to the
multidimensional case.
// Create 2 matrices using tensors of rank 2
Eigen::Tensor<int, 2> a(2, 3);
a.setValues({{1, 2, 3}, {6, 5, 4}});
Eigen::Tensor<int, 2> b(3, 2);
b.setValues({{1, 2}, {4, 5}, {5, 6}});
// Compute the traditional matrix product
Eigen::array<Eigen::IndexPair<int>, 1> product_dims = { Eigen::IndexPair<int>(1, 0) };
Eigen::Tensor<int, 2> AB = a.contract(b, product_dims);
// Compute the product of the transpose of the matrices
Eigen::array<Eigen::IndexPair<int>, 1> transposed_product_dims = { Eigen::IndexPair<int>(0, 1) };
Eigen::Tensor<int, 2> AtBt = a.contract(b, transposed_product_dims);
// Contraction to scalar value using a double contraction.
// First coordinate of both tensors are contracted as well as both second coordinates, i.e., this computes the sum of the squares of the elements.
Eigen::array<Eigen::IndexPair<int>, 2> double_contraction_product_dims = { Eigen::IndexPair<int>(0, 0), Eigen::IndexPair<int>(1, 1) };
Eigen::Tensor<int, 0> AdoubleContractedA = a.contract(a, double_contraction_product_dims);
// Extracting the scalar value of the tensor contraction for further usage
int value = AdoubleContractedA(0);
## Reduction Operations
A *Reduction* operation returns a tensor with fewer dimensions than the
original tensor. The values in the returned tensor are computed by applying a
*reduction operator* to slices of values from the original tensor. You specify
the dimensions along which the slices are made.
The Eigen Tensor library provides a set of predefined reduction operators such
as `maximum()` and `sum()` and lets you define additional operators by
implementing a few methods from a reductor template.
### Reduction Dimensions
All reduction operations take a single parameter of type
`<TensorType>::``Dimensions` which can always be specified as an array of
ints. These are called the "reduction dimensions." The values are the indices
of the dimensions of the input tensor over which the reduction is done. The
parameter can have at most as many element as the rank of the input tensor;
each element must be less than the tensor rank, as it indicates one of the
dimensions to reduce.
Each dimension of the input tensor should occur at most once in the reduction
dimensions as the implementation does not remove duplicates.
The order of the values in the reduction dimensions does not affect the
results, but the code may execute faster if you list the dimensions in
increasing order.
Example: Reduction along one dimension.
// Create a tensor of 2 dimensions
Eigen::Tensor<int, 2> a(2, 3);
a.setValues({{1, 2, 3}, {6, 5, 4}});
// Reduce it along the second dimension (1)...
Eigen::array<int, 1> dims({1 /* dimension to reduce */});
// ...using the "maximum" operator.
// The result is a tensor with one dimension. The size of
// that dimension is the same as the first (non-reduced) dimension of a.
Eigen::Tensor<int, 1> b = a.maximum(dims);
cout << "a" << endl << a << endl << endl;
cout << "b" << endl << b << endl << endl;
=>
a
1 2 3
6 5 4
b
3
6
Example: Reduction along two dimensions.
Eigen::Tensor<float, 3, Eigen::ColMajor> a(2, 3, 4);
a.setValues({{{0.0f, 1.0f, 2.0f, 3.0f},
{7.0f, 6.0f, 5.0f, 4.0f},
{8.0f, 9.0f, 10.0f, 11.0f}},
{{12.0f, 13.0f, 14.0f, 15.0f},
{19.0f, 18.0f, 17.0f, 16.0f},
{20.0f, 21.0f, 22.0f, 23.0f}}});
// The tensor a has 3 dimensions. We reduce along the
// first 2, resulting in a tensor with a single dimension
// of size 4 (the last dimension of a.)
// Note that we pass the array of reduction dimensions
// directly to the maximum() call.
Eigen::Tensor<float, 1, Eigen::ColMajor> b =
a.maximum(Eigen::array<int, 2>({0, 1}));
cout << "b" << endl << b << endl << endl;
=>
b
20
21
22
23
#### Reduction along all dimensions
As a special case, if you pass no parameter to a reduction operation the
original tensor is reduced along *all* its dimensions. The result is a
scalar, represented as a zero-dimension tensor.
Eigen::Tensor<float, 3> a(2, 3, 4);
a.setValues({{{0.0f, 1.0f, 2.0f, 3.0f},
{7.0f, 6.0f, 5.0f, 4.0f},
{8.0f, 9.0f, 10.0f, 11.0f}},
{{12.0f, 13.0f, 14.0f, 15.0f},
{19.0f, 18.0f, 17.0f, 16.0f},
{20.0f, 21.0f, 22.0f, 23.0f}}});
// Reduce along all dimensions using the sum() operator.
Eigen::Tensor<float, 0> b = a.sum();
cout << "b" << endl << b << endl << endl;
=>
b
276
### `<Operation> sum(const Dimensions& new_dims)`
### `<Operation> sum()`
Reduce a tensor using the sum() operator. The resulting values
are the sum of the reduced values.
### `<Operation> mean(const Dimensions& new_dims)`
### `<Operation> mean()`
Reduce a tensor using the mean() operator. The resulting values
are the mean of the reduced values.
### `<Operation> maximum(const Dimensions& new_dims)`
### `<Operation> maximum()`
Reduce a tensor using the maximum() operator. The resulting values are the
largest of the reduced values.
### `<Operation> minimum(const Dimensions& new_dims)`
### `<Operation> minimum()`
Reduce a tensor using the minimum() operator. The resulting values
are the smallest of the reduced values.
### `<Operation> prod(const Dimensions& new_dims)`
### `<Operation> prod()`
Reduce a tensor using the prod() operator. The resulting values
are the product of the reduced values.
### `<Operation> all(const Dimensions& new_dims)`
### `<Operation> all()`
Reduce a tensor using the all() operator. Casts tensor to bool and then checks
whether all elements are true. Runs through all elements rather than
short-circuiting, so may be significantly inefficient.
### `<Operation> any(const Dimensions& new_dims)`
### `<Operation> any()`
Reduce a tensor using the any() operator. Casts tensor to bool and then checks
whether any element is true. Runs through all elements rather than
short-circuiting, so may be significantly inefficient.
### `<Operation> reduce(const Dimensions& new_dims, const Reducer& reducer)`
Reduce a tensor using a user-defined reduction operator. See `SumReducer`
in TensorFunctors.h for information on how to implement a reduction operator.
## Trace
A *Trace* operation returns a tensor with fewer dimensions than the original
tensor. It returns a tensor whose elements are the sum of the elements of the
original tensor along the main diagonal for a list of specified dimensions, the
"trace dimensions". Similar to the `Reduction Dimensions`, the trace dimensions
are passed as an input parameter to the operation, are of type `<TensorType>::``Dimensions`
, and have the same requirements when passed as an input parameter. In addition,
the trace dimensions must have the same size.
Example: Trace along 2 dimensions.
// Create a tensor of 3 dimensions
Eigen::Tensor<int, 3> a(2, 2, 3);
a.setValues({{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}});
// Specify the dimensions along which the trace will be computed.
// In this example, the trace can only be computed along the dimensions
// with indices 0 and 1
Eigen::array<int, 2> dims({0, 1});
// The output tensor contains all but the trace dimensions.
Tensor<int, 1> a_trace = a.trace(dims);
cout << "a_trace:" << endl;
cout << a_trace << endl;
=>
a_trace:
11
13
15
### `<Operation> trace(const Dimensions& new_dims)`
### `<Operation> trace()`
As a special case, if no parameter is passed to the operation, trace is computed
along *all* dimensions of the input tensor.
Example: Trace along all dimensions.
// Create a tensor of 3 dimensions, with all dimensions having the same size.
Eigen::Tensor<int, 3> a(3, 3, 3);
a.setValues({{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
{{10, 11, 12}, {13, 14, 15}, {16, 17, 18}},
{{19, 20, 21}, {22, 23, 24}, {25, 26, 27}}});
// Result is a zero dimension tensor
Tensor<int, 0> a_trace = a.trace();
cout<<"a_trace:"<<endl;
cout<<a_trace<<endl;
=>
a_trace:
42
## Scan Operations
A *Scan* operation returns a tensor with the same dimensions as the original
tensor. The operation performs an inclusive scan along the specified
axis, which means it computes a running total along the axis for a given
reduction operation.
If the reduction operation corresponds to summation, then this computes the
prefix sum of the tensor along the given axis.
Example:
dd a comment to this line
// Create a tensor of 2 dimensions
Eigen::Tensor<int, 2> a(2, 3);
a.setValues({{1, 2, 3}, {4, 5, 6}});
// Scan it along the second dimension (1) using summation
Eigen::Tensor<int, 2> b = a.cumsum(1);
// The result is a tensor with the same size as the input
cout << "a" << endl << a << endl << endl;
cout << "b" << endl << b << endl << endl;
=>
a
1 2 3
4 5 6
b
1 3 6
4 9 15
### `<Operation> cumsum(const Index& axis)`
Perform a scan by summing consecutive entries.
### `<Operation> cumprod(const Index& axis)`
Perform a scan by multiplying consecutive entries.
## Convolutions
### `<Operation> convolve(const Kernel& kernel, const Dimensions& dims)`
Returns a tensor that is the output of the convolution of the input tensor with the kernel,
along the specified dimensions of the input tensor. The dimension size for dimensions of the output tensor
which were part of the convolution will be reduced by the formula:
output_dim_size = input_dim_size - kernel_dim_size + 1 (requires: input_dim_size >= kernel_dim_size).
The dimension sizes for dimensions that were not part of the convolution will remain the same.
Performance of the convolution can depend on the length of the stride(s) of the input tensor dimension(s) along which the
convolution is computed (the first dimension has the shortest stride for ColMajor, whereas RowMajor's shortest stride is
for the last dimension).
// Compute convolution along the second and third dimension.
Tensor<float, 4, DataLayout> input(3, 3, 7, 11);
Tensor<float, 2, DataLayout> kernel(2, 2);
Tensor<float, 4, DataLayout> output(3, 2, 6, 11);
input.setRandom();
kernel.setRandom();
Eigen::array<ptrdiff_t, 2> dims({1, 2}); // Specify second and third dimension for convolution.
output = input.convolve(kernel, dims);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 6; ++k) {
for (int l = 0; l < 11; ++l) {
const float result = output(i,j,k,l);
const float expected = input(i,j+0,k+0,l) * kernel(0,0) +
input(i,j+1,k+0,l) * kernel(1,0) +
input(i,j+0,k+1,l) * kernel(0,1) +
input(i,j+1,k+1,l) * kernel(1,1);
VERIFY_IS_APPROX(result, expected);
}
}
}
}
## Geometrical Operations
These operations return a Tensor with different dimensions than the original
Tensor. They can be used to access slices of tensors, see them with different
dimensions, or pad tensors with additional data.
### `<Operation> reshape(const Dimensions& new_dims)`
Returns a view of the input tensor that has been reshaped to the specified
new dimensions. The argument new_dims is an array of Index values. The
rank of the resulting tensor is equal to the number of elements in new_dims.
The product of all the sizes in the new dimension array must be equal to
the number of elements in the input tensor.
// Increase the rank of the input tensor by introducing a new dimension
// of size 1.
Tensor<float, 2> input(7, 11);
array<int, 3> three_dims{{7, 11, 1}};
Tensor<float, 3> result = input.reshape(three_dims);
// Decrease the rank of the input tensor by merging 2 dimensions;
array<int, 1> one_dim{{7 * 11}};
Tensor<float, 1> result = input.reshape(one_dim);
This operation does not move any data in the input tensor, so the resulting
contents of a reshaped Tensor depend on the data layout of the original Tensor.
For example this is what happens when you `reshape()` a 2D ColMajor tensor
to one dimension:
Eigen::Tensor<float, 2, Eigen::ColMajor> a(2, 3);
a.setValues({{0.0f, 100.0f, 200.0f}, {300.0f, 400.0f, 500.0f}});
Eigen::array<Eigen::DenseIndex, 1> one_dim({3 * 2});
Eigen::Tensor<float, 1, Eigen::ColMajor> b = a.reshape(one_dim);
cout << "b" << endl << b << endl;
=>
b
0
300
100
400
200
500
This is what happens when the 2D Tensor is RowMajor:
Eigen::Tensor<float, 2, Eigen::RowMajor> a(2, 3);
a.setValues({{0.0f, 100.0f, 200.0f}, {300.0f, 400.0f, 500.0f}});
Eigen::array<Eigen::DenseIndex, 1> one_dim({3 * 2});
Eigen::Tensor<float, 1, Eigen::RowMajor> b = a.reshape(one_dim);
cout << "b" << endl << b << endl;
=>
b
0
100
200
300
400
500
The reshape operation is a lvalue. In other words, it can be used on the left
side of the assignment operator.
The previous example can be rewritten as follow:
Eigen::Tensor<float, 2, Eigen::ColMajor> a(2, 3);
a.setValues({{0.0f, 100.0f, 200.0f}, {300.0f, 400.0f, 500.0f}});
Eigen::array<Eigen::DenseIndex, 2> two_dim({2, 3});
Eigen::Tensor<float, 1, Eigen::ColMajor> b(6);
b.reshape(two_dim) = a;
cout << "b" << endl << b << endl;
=>
b
0
300
100
400
200
500
Note that "b" itself was not reshaped but that instead the assignment is done to
the reshape view of b.
### `<Operation> shuffle(const Shuffle& shuffle)`
Returns a copy of the input tensor whose dimensions have been
reordered according to the specified permutation. The argument shuffle
is an array of Index values. Its size is the rank of the input
tensor. It must contain a permutation of 0, 1, ..., rank - 1. The i-th
dimension of the output tensor equals to the size of the shuffle[i]-th
dimension of the input tensor. For example:
// Shuffle all dimensions to the left by 1.
Tensor<float, 3> input(20, 30, 50);
// ... set some values in input.
Tensor<float, 3> output = input.shuffle({1, 2, 0})
eigen_assert(output.dimension(0) == 30);
eigen_assert(output.dimension(1) == 50);
eigen_assert(output.dimension(2) == 20);
Indices into the output tensor are shuffled accordingly to formulate
indices into the input tensor. For example, one can assert in the above
code snippet that:
eigen_assert(output(3, 7, 11) == input(11, 3, 7));
In general, one can assert that
eigen_assert(output(..., indices[shuffle[i]], ...) ==
input(..., indices[i], ...))
The shuffle operation results in a lvalue, which means that it can be assigned
to. In other words, it can be used on the left side of the assignment operator.
Let's rewrite the previous example to take advantage of this feature:
// Shuffle all dimensions to the left by 1.
Tensor<float, 3> input(20, 30, 50);
// ... set some values in input.
Tensor<float, 3> output(30, 50, 20);
output.shuffle({2, 0, 1}) = input;
### `<Operation> stride(const Strides& strides)`
Returns a view of the input tensor that strides (skips stride-1
elements) along each of the dimensions. The argument strides is an
array of Index values. The dimensions of the resulting tensor are
ceil(input_dimensions[i] / strides[i]).
For example this is what happens when you `stride()` a 2D tensor:
Eigen::Tensor<int, 2> a(4, 3);
a.setValues({{0, 100, 200}, {300, 400, 500}, {600, 700, 800}, {900, 1000, 1100}});
Eigen::array<Eigen::DenseIndex, 2> strides({3, 2});
Eigen::Tensor<int, 2> b = a.stride(strides);
cout << "b" << endl << b << endl;
=>
b
0 200
900 1100
It is possible to assign a tensor to a stride:
Tensor<float, 3> input(20, 30, 50);
// ... set some values in input.
Tensor<float, 3> output(40, 90, 200);
output.stride({2, 3, 4}) = input;
### `<Operation> slice(const StartIndices& offsets, const Sizes& extents)`
Returns a sub-tensor of the given tensor. For each dimension i, the slice is
made of the coefficients stored between offset[i] and offset[i] + extents[i] in
the input tensor.
Eigen::Tensor<int, 2> a(4, 3);
a.setValues({{0, 100, 200}, {300, 400, 500},
{600, 700, 800}, {900, 1000, 1100}});
Eigen::array<int, 2> offsets = {1, 0};
Eigen::array<int, 2> extents = {2, 2};
Eigen::Tensor<int, 1> slice = a.slice(offsets, extents);
cout << "a" << endl << a << endl;
=>
a
0 100 200
300 400 500
600 700 800
900 1000 1100
cout << "slice" << endl << slice << endl;
=>
slice
300 400
600 700
### `<Operation> chip(const Index offset, const Index dim)`
A chip is a special kind of slice. It is the subtensor at the given offset in
the dimension dim. The returned tensor has one fewer dimension than the input
tensor: the dimension dim is removed.
For example, a matrix chip would be either a row or a column of the input
matrix.
Eigen::Tensor<int, 2> a(4, 3);
a.setValues({{0, 100, 200}, {300, 400, 500},
{600, 700, 800}, {900, 1000, 1100}});
Eigen::Tensor<int, 1> row_3 = a.chip(2, 0);
Eigen::Tensor<int, 1> col_2 = a.chip(1, 1);
cout << "a" << endl << a << endl;
=>
a
0 100 200
300 400 500
600 700 800
900 1000 1100
cout << "row_3" << endl << row_3 << endl;
=>
row_3
600 700 800
cout << "col_2" << endl << col_2 << endl;
=>
col_2
100 400 700 1000
It is possible to assign values to a tensor chip since the chip operation is a
lvalue. For example:
Eigen::Tensor<int, 1> a(3);
a.setValues({{100, 200, 300}});
Eigen::Tensor<int, 2> b(2, 3);
b.setZero();
b.chip(0, 0) = a;
cout << "a" << endl << a << endl;
=>
a
100
200
300
cout << "b" << endl << b << endl;
=>
b
100 200 300
0 0 0
### `<Operation> reverse(const ReverseDimensions& reverse)`
Returns a view of the input tensor that reverses the order of the coefficients
along a subset of the dimensions. The argument reverse is an array of boolean
values that indicates whether or not the order of the coefficients should be
reversed along each of the dimensions. This operation preserves the dimensions
of the input tensor.
For example this is what happens when you `reverse()` the first dimension
of a 2D tensor:
Eigen::Tensor<int, 2> a(4, 3);
a.setValues({{0, 100, 200}, {300, 400, 500},
{600, 700, 800}, {900, 1000, 1100}});
Eigen::array<bool, 2> reverse({true, false});
Eigen::Tensor<int, 2> b = a.reverse(reverse);
cout << "a" << endl << a << endl << "b" << endl << b << endl;
=>
a
0 100 200
300 400 500
600 700 800
900 1000 1100
b
900 1000 1100
600 700 800
300 400 500
0 100 200
### `<Operation> broadcast(const Broadcast& broadcast)`
Returns a view of the input tensor in which the input is replicated one to many
times.
The broadcast argument specifies how many copies of the input tensor need to be
made in each of the dimensions.
Eigen::Tensor<int, 2> a(2, 3);
a.setValues({{0, 100, 200}, {300, 400, 500}});
Eigen::array<int, 2> bcast({3, 2});
Eigen::Tensor<int, 2> b = a.broadcast(bcast);
cout << "a" << endl << a << endl << "b" << endl << b << endl;
=>
a
0 100 200
300 400 500
b
0 100 200 0 100 200
300 400 500 300 400 500
0 100 200 0 100 200
300 400 500 300 400 500
0 100 200 0 100 200
300 400 500 300 400 500
### `<Operation> concatenate(const OtherDerived& other, Axis axis)`
TODO
### `<Operation> pad(const PaddingDimensions& padding)`
Returns a view of the input tensor in which the input is padded with zeros.
Eigen::Tensor<int, 2> a(2, 3);
a.setValues({{0, 100, 200}, {300, 400, 500}});
Eigen::array<pair<int, int>, 2> paddings;
paddings[0] = make_pair(0, 1);
paddings[1] = make_pair(2, 3);
Eigen::Tensor<int, 2> b = a.pad(paddings);
cout << "a" << endl << a << endl << "b" << endl << b << endl;
=>
a
0 100 200
300 400 500
b
0 0 0 0
0 0 0 0
0 100 200 0
300 400 500 0
0 0 0 0
0 0 0 0
0 0 0 0
### `<Operation> extract_patches(const PatchDims& patch_dims)`
Returns a tensor of coefficient patches extracted from the input tensor, where
each patch is of dimension specified by 'patch_dims'. The returned tensor has
one greater dimension than the input tensor, which is used to index each patch.
The patch index in the output tensor depends on the data layout of the input
tensor: the patch index is the last dimension ColMajor layout, and the first
dimension in RowMajor layout.
For example, given the following input tensor:
Eigen::Tensor<float, 2, DataLayout> tensor(3,4);
tensor.setValues({{0.0f, 1.0f, 2.0f, 3.0f},
{4.0f, 5.0f, 6.0f, 7.0f},
{8.0f, 9.0f, 10.0f, 11.0f}});
cout << "tensor: " << endl << tensor << endl;
=>
tensor:
0 1 2 3
4 5 6 7
8 9 10 11
Six 2x2 patches can be extracted and indexed using the following code:
Eigen::Tensor<float, 3, DataLayout> patch;
Eigen::array<ptrdiff_t, 2> patch_dims;
patch_dims[0] = 2;
patch_dims[1] = 2;
patch = tensor.extract_patches(patch_dims);
for (int k = 0; k < 6; ++k) {
cout << "patch index: " << k << endl;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
if (DataLayout == ColMajor) {
cout << patch(i, j, k) << " ";
} else {
cout << patch(k, i, j) << " ";
}
}
cout << endl;
}
}
This code results in the following output when the data layout is ColMajor:
patch index: 0
0 1
4 5
patch index: 1
4 5
8 9
patch index: 2
1 2
5 6
patch index: 3
5 6
9 10
patch index: 4
2 3
6 7
patch index: 5
6 7
10 11
This code results in the following output when the data layout is RowMajor:
(NOTE: the set of patches is the same as in ColMajor, but are indexed differently).
patch index: 0
0 1
4 5
patch index: 1
1 2
5 6
patch index: 2
2 3
6 7
patch index: 3
4 5
8 9
patch index: 4
5 6
9 10
patch index: 5
6 7
10 11
### `<Operation> extract_image_patches(const Index patch_rows, const Index patch_cols, const Index row_stride, const Index col_stride, const PaddingType padding_type)`
Returns a tensor of coefficient image patches extracted from the input tensor,
which is expected to have dimensions ordered as follows (depending on the data
layout of the input tensor, and the number of additional dimensions 'N'):
*) ColMajor
1st dimension: channels (of size d)
2nd dimension: rows (of size r)
3rd dimension: columns (of size c)
4th-Nth dimension: time (for video) or batch (for bulk processing).
*) RowMajor (reverse order of ColMajor)
1st-Nth dimension: time (for video) or batch (for bulk processing).
N+1'th dimension: columns (of size c)
N+2'th dimension: rows (of size r)
N+3'th dimension: channels (of size d)
The returned tensor has one greater dimension than the input tensor, which is
used to index each patch. The patch index in the output tensor depends on the
data layout of the input tensor: the patch index is the 4'th dimension in
ColMajor layout, and the 4'th from the last dimension in RowMajor layout.
For example, given the following input tensor with the following dimension
sizes:
*) depth: 2
*) rows: 3
*) columns: 5
*) batch: 7
Tensor<float, 4> tensor(2,3,5,7);
Tensor<float, 4, RowMajor> tensor_row_major = tensor.swap_layout();
2x2 image patches can be extracted and indexed using the following code:
*) 2D patch: ColMajor (patch indexed by second-to-last dimension)
Tensor<float, 5> twod_patch;
twod_patch = tensor.extract_image_patches<2, 2>();
// twod_patch.dimension(0) == 2
// twod_patch.dimension(1) == 2
// twod_patch.dimension(2) == 2
// twod_patch.dimension(3) == 3*5
// twod_patch.dimension(4) == 7
*) 2D patch: RowMajor (patch indexed by the second dimension)
Tensor<float, 5, RowMajor> twod_patch_row_major;
twod_patch_row_major = tensor_row_major.extract_image_patches<2, 2>();
// twod_patch_row_major.dimension(0) == 7
// twod_patch_row_major.dimension(1) == 3*5
// twod_patch_row_major.dimension(2) == 2
// twod_patch_row_major.dimension(3) == 2
// twod_patch_row_major.dimension(4) == 2
## Special Operations
### `<Operation> cast<T>()`
Returns a tensor of type T with the same dimensions as the original tensor.
The returned tensor contains the values of the original tensor converted to
type T.
Eigen::Tensor<float, 2> a(2, 3);
Eigen::Tensor<int, 2> b = a.cast<int>();
This can be useful for example if you need to do element-wise division of
Tensors of integers. This is not currently supported by the Tensor library
but you can easily cast the tensors to floats to do the division:
Eigen::Tensor<int, 2> a(2, 3);
a.setValues({{0, 1, 2}, {3, 4, 5}});
Eigen::Tensor<int, 2> b =
(a.cast<float>() / a.constant(2).cast<float>()).cast<int>();
cout << "a" << endl << a << endl << endl;
cout << "b" << endl << b << endl << endl;
=>
a
0 1 2
3 4 5
b
0 0 1
1 2 2
### `<Operation> eval()`
TODO
## Representation of scalar values
Scalar values are often represented by tensors of size 1 and rank 0.For example
Tensor<T, N>::maximum() currently returns a Tensor<T, 0>. Similarly, the inner
product of 2 1d tensors (through contractions) returns a 0d tensor.
## Limitations
* The number of tensor dimensions is currently limited to 250 when using a
compiler that supports cxx11. It is limited to only 5 for older compilers.
* The IndexList class requires a cxx11 compliant compiler. You can use an
array of indices instead if you don't have access to a modern compiler.
* On GPUs only floating point values are properly tested and optimized for.
* Complex and integer values are known to be broken on GPUs. If you try to use
them you'll most likely end up triggering a static assertion failure such as
EIGEN_STATIC_ASSERT(packetSize > 1, YOU_MADE_A_PROGRAMMING_MISTAKE)
|
j-fariaREPO_NAMEkimaPATH_START.@kima_extracted@kima-master@eigen@unsupported@Eigen@CXX11@src@Tensor@README.md@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/cycler/py3/cycler/__init__.py",
"type": "Python"
}
|
"""
Cycler
======
Cycling through combinations of values, producing dictionaries.
You can add cyclers::
from cycler import cycler
cc = (cycler(color=list('rgb')) +
cycler(linestyle=['-', '--', '-.']))
for d in cc:
print(d)
Results in::
{'color': 'r', 'linestyle': '-'}
{'color': 'g', 'linestyle': '--'}
{'color': 'b', 'linestyle': '-.'}
You can multiply cyclers::
from cycler import cycler
cc = (cycler(color=list('rgb')) *
cycler(linestyle=['-', '--', '-.']))
for d in cc:
print(d)
Results in::
{'color': 'r', 'linestyle': '-'}
{'color': 'r', 'linestyle': '--'}
{'color': 'r', 'linestyle': '-.'}
{'color': 'g', 'linestyle': '-'}
{'color': 'g', 'linestyle': '--'}
{'color': 'g', 'linestyle': '-.'}
{'color': 'b', 'linestyle': '-'}
{'color': 'b', 'linestyle': '--'}
{'color': 'b', 'linestyle': '-.'}
"""
from __future__ import annotations
from collections.abc import Hashable, Iterable, Generator
import copy
from functools import reduce
from itertools import product, cycle
from operator import mul, add
# Dict, List, Union required for runtime cast calls
from typing import TypeVar, Generic, Callable, Union, Dict, List, Any, overload, cast
__version__ = "0.12.1"
K = TypeVar("K", bound=Hashable)
L = TypeVar("L", bound=Hashable)
V = TypeVar("V")
U = TypeVar("U")
def _process_keys(
left: Cycler[K, V] | Iterable[dict[K, V]],
right: Cycler[K, V] | Iterable[dict[K, V]] | None,
) -> set[K]:
"""
Helper function to compose cycler keys.
Parameters
----------
left, right : iterable of dictionaries or None
The cyclers to be composed.
Returns
-------
keys : set
The keys in the composition of the two cyclers.
"""
l_peek: dict[K, V] = next(iter(left)) if left != [] else {}
r_peek: dict[K, V] = next(iter(right)) if right is not None else {}
l_key: set[K] = set(l_peek.keys())
r_key: set[K] = set(r_peek.keys())
if l_key & r_key:
raise ValueError("Can not compose overlapping cycles")
return l_key | r_key
def concat(left: Cycler[K, V], right: Cycler[K, U]) -> Cycler[K, V | U]:
r"""
Concatenate `Cycler`\s, as if chained using `itertools.chain`.
The keys must match exactly.
Examples
--------
>>> num = cycler('a', range(3))
>>> let = cycler('a', 'abc')
>>> num.concat(let)
cycler('a', [0, 1, 2, 'a', 'b', 'c'])
Returns
-------
`Cycler`
The concatenated cycler.
"""
if left.keys != right.keys:
raise ValueError(
"Keys do not match:\n"
"\tIntersection: {both!r}\n"
"\tDisjoint: {just_one!r}".format(
both=left.keys & right.keys, just_one=left.keys ^ right.keys
)
)
_l = cast(Dict[K, List[Union[V, U]]], left.by_key())
_r = cast(Dict[K, List[Union[V, U]]], right.by_key())
return reduce(add, (_cycler(k, _l[k] + _r[k]) for k in left.keys))
class Cycler(Generic[K, V]):
"""
Composable cycles.
This class has compositions methods:
``+``
for 'inner' products (zip)
``+=``
in-place ``+``
``*``
for outer products (`itertools.product`) and integer multiplication
``*=``
in-place ``*``
and supports basic slicing via ``[]``.
Parameters
----------
left, right : Cycler or None
The 'left' and 'right' cyclers.
op : func or None
Function which composes the 'left' and 'right' cyclers.
"""
def __call__(self):
return cycle(self)
def __init__(
self,
left: Cycler[K, V] | Iterable[dict[K, V]] | None,
right: Cycler[K, V] | None = None,
op: Any = None,
):
"""
Semi-private init.
Do not use this directly, use `cycler` function instead.
"""
if isinstance(left, Cycler):
self._left: Cycler[K, V] | list[dict[K, V]] = Cycler(
left._left, left._right, left._op
)
elif left is not None:
# Need to copy the dictionary or else that will be a residual
# mutable that could lead to strange errors
self._left = [copy.copy(v) for v in left]
else:
self._left = []
if isinstance(right, Cycler):
self._right: Cycler[K, V] | None = Cycler(
right._left, right._right, right._op
)
else:
self._right = None
self._keys: set[K] = _process_keys(self._left, self._right)
self._op: Any = op
def __contains__(self, k):
return k in self._keys
@property
def keys(self) -> set[K]:
"""The keys this Cycler knows about."""
return set(self._keys)
def change_key(self, old: K, new: K) -> None:
"""
Change a key in this cycler to a new name.
Modification is performed in-place.
Does nothing if the old key is the same as the new key.
Raises a ValueError if the new key is already a key.
Raises a KeyError if the old key isn't a key.
"""
if old == new:
return
if new in self._keys:
raise ValueError(
f"Can't replace {old} with {new}, {new} is already a key"
)
if old not in self._keys:
raise KeyError(
f"Can't replace {old} with {new}, {old} is not a key"
)
self._keys.remove(old)
self._keys.add(new)
if self._right is not None and old in self._right.keys:
self._right.change_key(old, new)
# self._left should always be non-None
# if self._keys is non-empty.
elif isinstance(self._left, Cycler):
self._left.change_key(old, new)
else:
# It should be completely safe at this point to
# assume that the old key can be found in each
# iteration.
self._left = [{new: entry[old]} for entry in self._left]
@classmethod
def _from_iter(cls, label: K, itr: Iterable[V]) -> Cycler[K, V]:
"""
Class method to create 'base' Cycler objects
that do not have a 'right' or 'op' and for which
the 'left' object is not another Cycler.
Parameters
----------
label : hashable
The property key.
itr : iterable
Finite length iterable of the property values.
Returns
-------
`Cycler`
New 'base' cycler.
"""
ret: Cycler[K, V] = cls(None)
ret._left = list({label: v} for v in itr)
ret._keys = {label}
return ret
def __getitem__(self, key: slice) -> Cycler[K, V]:
# TODO : maybe add numpy style fancy slicing
if isinstance(key, slice):
trans = self.by_key()
return reduce(add, (_cycler(k, v[key]) for k, v in trans.items()))
else:
raise ValueError("Can only use slices with Cycler.__getitem__")
def __iter__(self) -> Generator[dict[K, V], None, None]:
if self._right is None:
for left in self._left:
yield dict(left)
else:
if self._op is None:
raise TypeError(
"Operation cannot be None when both left and right are defined"
)
for a, b in self._op(self._left, self._right):
out = {}
out.update(a)
out.update(b)
yield out
def __add__(self, other: Cycler[L, U]) -> Cycler[K | L, V | U]:
"""
Pair-wise combine two equal length cyclers (zip).
Parameters
----------
other : Cycler
"""
if len(self) != len(other):
raise ValueError(
f"Can only add equal length cycles, not {len(self)} and {len(other)}"
)
return Cycler(
cast(Cycler[Union[K, L], Union[V, U]], self),
cast(Cycler[Union[K, L], Union[V, U]], other),
zip
)
@overload
def __mul__(self, other: Cycler[L, U]) -> Cycler[K | L, V | U]:
...
@overload
def __mul__(self, other: int) -> Cycler[K, V]:
...
def __mul__(self, other):
"""
Outer product of two cyclers (`itertools.product`) or integer
multiplication.
Parameters
----------
other : Cycler or int
"""
if isinstance(other, Cycler):
return Cycler(
cast(Cycler[Union[K, L], Union[V, U]], self),
cast(Cycler[Union[K, L], Union[V, U]], other),
product
)
elif isinstance(other, int):
trans = self.by_key()
return reduce(
add, (_cycler(k, v * other) for k, v in trans.items())
)
else:
return NotImplemented
@overload
def __rmul__(self, other: Cycler[L, U]) -> Cycler[K | L, V | U]:
...
@overload
def __rmul__(self, other: int) -> Cycler[K, V]:
...
def __rmul__(self, other):
return self * other
def __len__(self) -> int:
op_dict: dict[Callable, Callable[[int, int], int]] = {zip: min, product: mul}
if self._right is None:
return len(self._left)
l_len = len(self._left)
r_len = len(self._right)
return op_dict[self._op](l_len, r_len)
# iadd and imul do not exapand the the type as the returns must be consistent with
# self, thus they flag as inconsistent with add/mul
def __iadd__(self, other: Cycler[K, V]) -> Cycler[K, V]: # type: ignore[misc]
"""
In-place pair-wise combine two equal length cyclers (zip).
Parameters
----------
other : Cycler
"""
if not isinstance(other, Cycler):
raise TypeError("Cannot += with a non-Cycler object")
# True shallow copy of self is fine since this is in-place
old_self = copy.copy(self)
self._keys = _process_keys(old_self, other)
self._left = old_self
self._op = zip
self._right = Cycler(other._left, other._right, other._op)
return self
def __imul__(self, other: Cycler[K, V] | int) -> Cycler[K, V]: # type: ignore[misc]
"""
In-place outer product of two cyclers (`itertools.product`).
Parameters
----------
other : Cycler
"""
if not isinstance(other, Cycler):
raise TypeError("Cannot *= with a non-Cycler object")
# True shallow copy of self is fine since this is in-place
old_self = copy.copy(self)
self._keys = _process_keys(old_self, other)
self._left = old_self
self._op = product
self._right = Cycler(other._left, other._right, other._op)
return self
def __eq__(self, other: object) -> bool:
if not isinstance(other, Cycler):
return False
if len(self) != len(other):
return False
if self.keys ^ other.keys:
return False
return all(a == b for a, b in zip(self, other))
__hash__ = None # type: ignore
def __repr__(self) -> str:
op_map = {zip: "+", product: "*"}
if self._right is None:
lab = self.keys.pop()
itr = list(v[lab] for v in self)
return f"cycler({lab!r}, {itr!r})"
else:
op = op_map.get(self._op, "?")
msg = "({left!r} {op} {right!r})"
return msg.format(left=self._left, op=op, right=self._right)
def _repr_html_(self) -> str:
# an table showing the value of each key through a full cycle
output = "<table>"
sorted_keys = sorted(self.keys, key=repr)
for key in sorted_keys:
output += f"<th>{key!r}</th>"
for d in iter(self):
output += "<tr>"
for k in sorted_keys:
output += f"<td>{d[k]!r}</td>"
output += "</tr>"
output += "</table>"
return output
def by_key(self) -> dict[K, list[V]]:
"""
Values by key.
This returns the transposed values of the cycler. Iterating
over a `Cycler` yields dicts with a single value for each key,
this method returns a `dict` of `list` which are the values
for the given key.
The returned value can be used to create an equivalent `Cycler`
using only `+`.
Returns
-------
transpose : dict
dict of lists of the values for each key.
"""
# TODO : sort out if this is a bottle neck, if there is a better way
# and if we care.
keys = self.keys
out: dict[K, list[V]] = {k: list() for k in keys}
for d in self:
for k in keys:
out[k].append(d[k])
return out
# for back compatibility
_transpose = by_key
def simplify(self) -> Cycler[K, V]:
"""
Simplify the cycler into a sum (but no products) of cyclers.
Returns
-------
simple : Cycler
"""
# TODO: sort out if it is worth the effort to make sure this is
# balanced. Currently it is is
# (((a + b) + c) + d) vs
# ((a + b) + (c + d))
# I would believe that there is some performance implications
trans = self.by_key()
return reduce(add, (_cycler(k, v) for k, v in trans.items()))
concat = concat
@overload
def cycler(arg: Cycler[K, V]) -> Cycler[K, V]:
...
@overload
def cycler(**kwargs: Iterable[V]) -> Cycler[str, V]:
...
@overload
def cycler(label: K, itr: Iterable[V]) -> Cycler[K, V]:
...
def cycler(*args, **kwargs):
"""
Create a new `Cycler` object from a single positional argument,
a pair of positional arguments, or the combination of keyword arguments.
cycler(arg)
cycler(label1=itr1[, label2=iter2[, ...]])
cycler(label, itr)
Form 1 simply copies a given `Cycler` object.
Form 2 composes a `Cycler` as an inner product of the
pairs of keyword arguments. In other words, all of the
iterables are cycled simultaneously, as if through zip().
Form 3 creates a `Cycler` from a label and an iterable.
This is useful for when the label cannot be a keyword argument
(e.g., an integer or a name that has a space in it).
Parameters
----------
arg : Cycler
Copy constructor for Cycler (does a shallow copy of iterables).
label : name
The property key. In the 2-arg form of the function,
the label can be any hashable object. In the keyword argument
form of the function, it must be a valid python identifier.
itr : iterable
Finite length iterable of the property values.
Can be a single-property `Cycler` that would
be like a key change, but as a shallow copy.
Returns
-------
cycler : Cycler
New `Cycler` for the given property
"""
if args and kwargs:
raise TypeError(
"cycler() can only accept positional OR keyword arguments -- not both."
)
if len(args) == 1:
if not isinstance(args[0], Cycler):
raise TypeError(
"If only one positional argument given, it must "
"be a Cycler instance."
)
return Cycler(args[0])
elif len(args) == 2:
return _cycler(*args)
elif len(args) > 2:
raise TypeError(
"Only a single Cycler can be accepted as the lone "
"positional argument. Use keyword arguments instead."
)
if kwargs:
return reduce(add, (_cycler(k, v) for k, v in kwargs.items()))
raise TypeError("Must have at least a positional OR keyword arguments")
def _cycler(label: K, itr: Iterable[V]) -> Cycler[K, V]:
"""
Create a new `Cycler` object from a property name and iterable of values.
Parameters
----------
label : hashable
The property key.
itr : iterable
Finite length iterable of the property values.
Returns
-------
cycler : Cycler
New `Cycler` for the given property
"""
if isinstance(itr, Cycler):
keys = itr.keys
if len(keys) != 1:
msg = "Can not create Cycler from a multi-property Cycler"
raise ValueError(msg)
lab = keys.pop()
# Doesn't need to be a new list because
# _from_iter() will be creating that new list anyway.
itr = (v[lab] for v in itr)
return Cycler._from_iter(label, itr)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@cycler@py3@cycler@__init__.py@.PATH_END.py
|
{
"filename": "conf.py",
"repo_name": "segasai/rvspecfit",
"repo_path": "rvspecfit_extracted/rvspecfit-master/docs/conf.py",
"type": "Python"
}
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
import os
import sys
sys.path.insert(0, os.path.abspath('../py/'))
fp = open('../py/rvspecfit/_version.py','w')
print('version="dev"',file=fp)
fp.close()
import rvspecfit
# -- Project information -----------------------------------------------------
project = 'rvspecfit'
copyright = '2020, Sergey Koposov'
author = 'Sergey Koposov'
master_doc = 'index' ## see https://github.com/readthedocs/readthedocs.org/issues/2569
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['recommonmark', 'sphinx.ext.autodoc', 'numpydoc'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
#source_suffix='.rst'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
|
segasaiREPO_NAMErvspecfitPATH_START.@rvspecfit_extracted@rvspecfit-master@docs@conf.py@.PATH_END.py
|
{
"filename": "test_experiment.py",
"repo_name": "FRBs/FRB",
"repo_path": "FRB_extracted/FRB-main/frb/tests/test_experiment.py",
"type": "Python"
}
|
# Module to run tests on instantiating FRBObs
from __future__ import print_function, absolute_import, division, unicode_literals
# TEST_UNICODE_LITERALS
import pytest
import os
from frb.experiment import Experiment
#def data_path(filename):
# data_dir = os.path.join(os.path.dirname(__file__), 'files')
# return os.path.join(data_dir, filename)
def test_init():
chime = Experiment('chime')
for key in ['FOV', 'G', 'np', 'Trec', 'Channels']:
assert key in chime.data.keys()
|
FRBsREPO_NAMEFRBPATH_START.@FRB_extracted@FRB-main@frb@tests@test_experiment.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "simonsobs/apluggy",
"repo_path": "apluggy_extracted/apluggy-main/tests/stack/aexit/__init__.py",
"type": "Python"
}
|
simonsobsREPO_NAMEapluggyPATH_START.@apluggy_extracted@apluggy-main@tests@stack@aexit@__init__.py@.PATH_END.py
|
|
{
"filename": "G__l_a_t.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/fonttools/fontTools/ttLib/tables/G__l_a_t.py",
"type": "Python"
}
|
from fontTools.misc import sstruct
from fontTools.misc.fixedTools import floatToFixedToStr
from fontTools.misc.textTools import safeEval
# from itertools import *
from functools import partial
from . import DefaultTable
from . import grUtils
import struct
Glat_format_0 = """
> # big endian
version: 16.16F
"""
Glat_format_3 = """
>
version: 16.16F
compression:L # compression scheme or reserved
"""
Glat_format_1_entry = """
>
attNum: B # Attribute number of first attribute
num: B # Number of attributes in this run
"""
Glat_format_23_entry = """
>
attNum: H # Attribute number of first attribute
num: H # Number of attributes in this run
"""
Glat_format_3_octabox_metrics = """
>
subboxBitmap: H # Which subboxes exist on 4x4 grid
diagNegMin: B # Defines minimum negatively-sloped diagonal (si)
diagNegMax: B # Defines maximum negatively-sloped diagonal (sa)
diagPosMin: B # Defines minimum positively-sloped diagonal (di)
diagPosMax: B # Defines maximum positively-sloped diagonal (da)
"""
Glat_format_3_subbox_entry = """
>
left: B # xi
right: B # xa
bottom: B # yi
top: B # ya
diagNegMin: B # Defines minimum negatively-sloped diagonal (si)
diagNegMax: B # Defines maximum negatively-sloped diagonal (sa)
diagPosMin: B # Defines minimum positively-sloped diagonal (di)
diagPosMax: B # Defines maximum positively-sloped diagonal (da)
"""
class _Object:
pass
class _Dict(dict):
pass
class table_G__l_a_t(DefaultTable.DefaultTable):
"""
Support Graphite Glat tables
"""
def __init__(self, tag=None):
DefaultTable.DefaultTable.__init__(self, tag)
self.scheme = 0
def decompile(self, data, ttFont):
sstruct.unpack2(Glat_format_0, data, self)
self.version = float(floatToFixedToStr(self.version, precisionBits=16))
if self.version <= 1.9:
decoder = partial(self.decompileAttributes12, fmt=Glat_format_1_entry)
elif self.version <= 2.9:
decoder = partial(self.decompileAttributes12, fmt=Glat_format_23_entry)
elif self.version >= 3.0:
(data, self.scheme) = grUtils.decompress(data)
sstruct.unpack2(Glat_format_3, data, self)
self.hasOctaboxes = (self.compression & 1) == 1
decoder = self.decompileAttributes3
gloc = ttFont["Gloc"]
self.attributes = {}
count = 0
for s, e in zip(gloc, gloc[1:]):
self.attributes[ttFont.getGlyphName(count)] = decoder(data[s:e])
count += 1
def decompileAttributes12(self, data, fmt):
attributes = _Dict()
while len(data) > 3:
e, data = sstruct.unpack2(fmt, data, _Object())
keys = range(e.attNum, e.attNum + e.num)
if len(data) >= 2 * e.num:
vals = struct.unpack_from((">%dh" % e.num), data)
attributes.update(zip(keys, vals))
data = data[2 * e.num :]
return attributes
def decompileAttributes3(self, data):
if self.hasOctaboxes:
o, data = sstruct.unpack2(Glat_format_3_octabox_metrics, data, _Object())
numsub = bin(o.subboxBitmap).count("1")
o.subboxes = []
for b in range(numsub):
if len(data) >= 8:
subbox, data = sstruct.unpack2(
Glat_format_3_subbox_entry, data, _Object()
)
o.subboxes.append(subbox)
attrs = self.decompileAttributes12(data, Glat_format_23_entry)
if self.hasOctaboxes:
attrs.octabox = o
return attrs
def compile(self, ttFont):
data = sstruct.pack(Glat_format_0, self)
if self.version <= 1.9:
encoder = partial(self.compileAttributes12, fmt=Glat_format_1_entry)
elif self.version <= 2.9:
encoder = partial(self.compileAttributes12, fmt=Glat_format_1_entry)
elif self.version >= 3.0:
self.compression = (self.scheme << 27) + (1 if self.hasOctaboxes else 0)
data = sstruct.pack(Glat_format_3, self)
encoder = self.compileAttributes3
glocs = []
for n in range(len(self.attributes)):
glocs.append(len(data))
data += encoder(self.attributes[ttFont.getGlyphName(n)])
glocs.append(len(data))
ttFont["Gloc"].set(glocs)
if self.version >= 3.0:
data = grUtils.compress(self.scheme, data)
return data
def compileAttributes12(self, attrs, fmt):
data = b""
for e in grUtils.entries(attrs):
data += sstruct.pack(fmt, {"attNum": e[0], "num": e[1]}) + struct.pack(
(">%dh" % len(e[2])), *e[2]
)
return data
def compileAttributes3(self, attrs):
if self.hasOctaboxes:
o = attrs.octabox
data = sstruct.pack(Glat_format_3_octabox_metrics, o)
numsub = bin(o.subboxBitmap).count("1")
for b in range(numsub):
data += sstruct.pack(Glat_format_3_subbox_entry, o.subboxes[b])
else:
data = ""
return data + self.compileAttributes12(attrs, Glat_format_23_entry)
def toXML(self, writer, ttFont):
writer.simpletag("version", version=self.version, compressionScheme=self.scheme)
writer.newline()
for n, a in sorted(
self.attributes.items(), key=lambda x: ttFont.getGlyphID(x[0])
):
writer.begintag("glyph", name=n)
writer.newline()
if hasattr(a, "octabox"):
o = a.octabox
formatstring, names, fixes = sstruct.getformat(
Glat_format_3_octabox_metrics
)
vals = {}
for k in names:
if k == "subboxBitmap":
continue
vals[k] = "{:.3f}%".format(getattr(o, k) * 100.0 / 255)
vals["bitmap"] = "{:0X}".format(o.subboxBitmap)
writer.begintag("octaboxes", **vals)
writer.newline()
formatstring, names, fixes = sstruct.getformat(
Glat_format_3_subbox_entry
)
for s in o.subboxes:
vals = {}
for k in names:
vals[k] = "{:.3f}%".format(getattr(s, k) * 100.0 / 255)
writer.simpletag("octabox", **vals)
writer.newline()
writer.endtag("octaboxes")
writer.newline()
for k, v in sorted(a.items()):
writer.simpletag("attribute", index=k, value=v)
writer.newline()
writer.endtag("glyph")
writer.newline()
def fromXML(self, name, attrs, content, ttFont):
if name == "version":
self.version = float(safeEval(attrs["version"]))
self.scheme = int(safeEval(attrs["compressionScheme"]))
if name != "glyph":
return
if not hasattr(self, "attributes"):
self.attributes = {}
gname = attrs["name"]
attributes = _Dict()
for element in content:
if not isinstance(element, tuple):
continue
tag, attrs, subcontent = element
if tag == "attribute":
k = int(safeEval(attrs["index"]))
v = int(safeEval(attrs["value"]))
attributes[k] = v
elif tag == "octaboxes":
self.hasOctaboxes = True
o = _Object()
o.subboxBitmap = int(attrs["bitmap"], 16)
o.subboxes = []
del attrs["bitmap"]
for k, v in attrs.items():
setattr(o, k, int(float(v[:-1]) * 255.0 / 100.0 + 0.5))
for element in subcontent:
if not isinstance(element, tuple):
continue
(tag, attrs, subcontent) = element
so = _Object()
for k, v in attrs.items():
setattr(so, k, int(float(v[:-1]) * 255.0 / 100.0 + 0.5))
o.subboxes.append(so)
attributes.octabox = o
self.attributes[gname] = attributes
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@fonttools@fontTools@ttLib@tables@G__l_a_t.py@.PATH_END.py
|
{
"filename": "kinematics_2d.py",
"repo_name": "bek0s/gbkfit",
"repo_path": "gbkfit_extracted/gbkfit-master/src/gbkfit/model/gmodels/kinematics_2d.py",
"type": "Python"
}
|
from collections.abc import Sequence
from gbkfit.model.core import GModelSCube
from gbkfit.utils import iterutils, parseutils
from . import _detail
from .core import SpectralComponent2D
from .spectral_smdisk_2d import SpectralSMDisk2D
__all__ = [
'GModelKinematics2D'
]
_scmp_parser = parseutils.TypedParser(SpectralComponent2D, [
SpectralSMDisk2D])
class GModelKinematics2D(GModelSCube):
@staticmethod
def type():
return 'kinematics_2d'
@classmethod
def load(cls, info):
desc = parseutils.make_typed_desc(cls, 'gmodel')
parseutils.load_if_exists(_scmp_parser, info, 'components')
opts = parseutils.parse_options_for_callable(info, desc, cls.__init__)
return cls(**opts)
def dump(self):
return dict(
type=self.type(),
components=_scmp_parser.dump(self._components))
def __init__(
self,
components: SpectralComponent2D | Sequence[SpectralComponent2D]
):
if not components:
raise RuntimeError("at least one component must be configured")
self._components = iterutils.tuplify(components, False)
self._size = [None, None]
self._step = [None, None]
self._zero = [None, None]
self._wdata = None
self._dtype = None
self._driver = None
self._backend = None
(self._params,
self._mappings) = _detail.make_gmodel_2d_params(
self._components)
def params(self):
return self._params
def is_weighted(self):
return _detail.is_gmodel_weighted(self._components)
def _prepare(self, driver, scube_w, size, step, zero, dtype):
self._driver = driver
self._size = size
self._step = step
self._zero = zero
self._wdata = None
self._dtype = dtype
# If weighting is requested, store it in a 2d spatial array.
if scube_w is not None:
self._wdata = driver.mem_alloc_d(self._size[::-1], dtype)
# Create backend
self._backend = driver.backends().gmodel(dtype)
def evaluate_scube(
self, driver, params,
scube_d, scube_w, size, step, zero, rota, dtype,
out_extra):
if (self._driver is not driver
or self._size != size[:2]
or self._dtype != dtype):
self._prepare(driver, scube_w, size[:2], step[:2], zero[:2], dtype)
spat_size = self._size
spat_step = self._step
spat_zero = self._zero
spat_rota = rota
spec_size = size[2]
spec_step = step[2]
spec_zero = zero[2]
wdata = self._wdata
components = self._components
mappings = self._mappings
backend = self._backend
bdata = None
if out_extra is not None:
bdata = driver.mem_alloc_d(spat_size[::-1], dtype)
driver.mem_fill(bdata, 0)
# Evaluate components
_detail.evaluate_components_s2d(
components, driver, params, mappings,
scube_d, scube_w, bdata,
spat_size, spat_step, spat_zero, spat_rota,
spec_size, spec_step, spec_zero,
dtype, out_extra, '')
# Evaluate the provided spectral weight cube using
# the 2d spatial weight data evaluated above
if scube_w is not None:
backend.wcube_evaluate(
tuple(spat_size) + (1,), spec_size, wdata, scube_w)
if out_extra is not None:
if wdata is not None:
out_extra['total_wdata'] = driver.mem_copy_d2h(wdata)
if bdata is not None:
out_extra['total_bdata'] = driver.mem_copy_d2h(bdata)
|
bek0sREPO_NAMEgbkfitPATH_START.@gbkfit_extracted@gbkfit-master@src@gbkfit@model@gmodels@kinematics_2d.py@.PATH_END.py
|
{
"filename": "fit_imaging.py",
"repo_name": "Jammy2211/PyAutoLens",
"repo_path": "PyAutoLens_extracted/PyAutoLens-main/autolens/aggregator/fit_imaging.py",
"type": "Python"
}
|
from typing import Optional, List
import autofit as af
import autoarray as aa
from autolens.imaging.fit_imaging import FitImaging
from autolens.analysis.preloads import Preloads
from autogalaxy.aggregator.imaging.imaging import _imaging_from
from autogalaxy.aggregator.dataset_model import _dataset_model_from
from autogalaxy.aggregator import agg_util
from autolens.aggregator.tracer import _tracer_from
def _fit_imaging_from(
fit: af.Fit,
instance: Optional[af.ModelInstance] = None,
settings_inversion: aa.SettingsInversion = None,
use_preloaded_grid: bool = True,
) -> List[FitImaging]:
"""
Returns a list of `FitImaging` object from a `PyAutoFit` sqlite database `Fit` object.
The results of a model-fit can be stored in a sqlite database, including the following attributes of the fit:
- The imaging data, noise-map, PSF and settings as .fits files (e.g. `dataset/data.fits`).
- The mask used to mask the `Imaging` data structure in the fit (`dataset/mask.fits`).
- The settings of inversions used by the fit (`dataset/settings_inversion.json`).
Each individual attribute can be loaded from the database via the `fit.value()` method.
This method combines all of these attributes and returns a `FitImaging` object for a given non-linear search sample
(e.g. the maximum likelihood model). This includes associating adapt images with their respective galaxies.
If multiple `FitImaging` objects were fitted simultaneously via analysis summing, the `fit.child_values()` method
is instead used to load lists of the data, noise-map, PSF and mask and combine them into a list of
`FitImaging` objects.
The settings of an inversion can be overwritten by inputting a `settings_inversion` object, for example
if you want to use a grid with a different inversion solver.
Parameters
----------
fit
A `PyAutoFit` `Fit` object which contains the results of a model-fit as an entry in a sqlite database.
instance
A manual instance that overwrites the max log likelihood instance in fit (e.g. for drawing the instance
randomly from the PDF).
settings_inversion
Optionally overwrite the `SettingsInversion` of the `Inversion` object that is created from the fit.
use_preloaded_grid
Certain pixelization's construct their mesh in the source-plane from a stochastic KMeans algorithm. This grid
may be output to hard-disk after the model-fit and loaded via the database to ensure the same grid is used
as the fit.
"""
dataset_list = _imaging_from(fit=fit)
tracer_list = _tracer_from(fit=fit, instance=instance)
dataset_model_list = _dataset_model_from(fit=fit, instance=instance)
adapt_images_list = agg_util.adapt_images_from(fit=fit)
settings_inversion = settings_inversion or fit.value(name="settings_inversion")
mesh_grids_of_planes_list = agg_util.mesh_grids_of_planes_list_from(
fit=fit, total_fits=len(dataset_list), use_preloaded_grid=use_preloaded_grid
)
fit_dataset_list = []
for dataset, tracer, dataset_model, adapt_images, mesh_grids_of_planes in zip(
dataset_list,
tracer_list,
dataset_model_list,
adapt_images_list,
mesh_grids_of_planes_list,
):
preloads = agg_util.preloads_from(
preloads_cls=Preloads,
use_preloaded_grid=use_preloaded_grid,
mesh_grids_of_planes=mesh_grids_of_planes,
use_w_tilde=False,
)
fit_dataset_list.append(
FitImaging(
dataset=dataset,
tracer=tracer,
dataset_model=dataset_model,
adapt_images=adapt_images,
settings_inversion=settings_inversion,
preloads=preloads,
)
)
return fit_dataset_list
class FitImagingAgg(af.AggBase):
def __init__(
self,
aggregator: af.Aggregator,
settings_inversion: Optional[aa.SettingsInversion] = None,
use_preloaded_grid: bool = True,
):
"""
Interfaces with an `PyAutoFit` aggregator object to create instances of `FitImaging` objects from the results
of a model-fit.
The results of a model-fit can be stored in a sqlite database, including the following attributes of the fit:
- The imaging data, noise-map, PSF and settings as .fits files (e.g. `dataset/data.fits`).
- The mask used to mask the `Imaging` data structure in the fit (`dataset/mask.fits`).
- The settings of inversions used by the fit (`dataset/settings_inversion.json`).
The `aggregator` contains the path to each of these files, and they can be loaded individually. This class
can load them all at once and create an `FitImaging` object via the `_fit_imaging_from` method.
This class's methods returns generators which create the instances of the `FitImaging` objects. This ensures
that large sets of results can be efficiently loaded from the hard-disk and do not require storing all
`FitImaging` instances in the memory at once.
For example, if the `aggregator` contains 3 model-fits, this class can be used to create a generator which
creates instances of the corresponding 3 `FitImaging` objects.
If multiple `FitImaging` objects were fitted simultaneously via analysis summing, the `fit.child_values()` method
is instead used to load lists of the data, noise-map, PSF and mask and combine them into a list of
`FitImaging` objects.
This can be done manually, but this object provides a more concise API.
Parameters
----------
aggregator
A `PyAutoFit` aggregator object which can load the results of model-fits.
settings_inversion
Optionally overwrite the `SettingsInversion` of the `Inversion` object that is created from the fit.
use_preloaded_grid
Certain pixelization's construct their mesh in the source-plane from a stochastic KMeans algorithm. This
grid may be output to hard-disk after the model-fit and loaded via the database to ensure the same grid is
used as the fit.
"""
super().__init__(aggregator=aggregator)
self.settings_inversion = settings_inversion
self.use_preloaded_grid = use_preloaded_grid
def object_via_gen_from(
self, fit, instance: Optional[af.ModelInstance] = None
) -> List[FitImaging]:
"""
Returns a generator of `FitImaging` objects from an input aggregator.
See `__init__` for a description of how the `FitImaging` objects are created by this method.
Parameters
----------
fit
A `PyAutoFit` `Fit` object which contains the results of a model-fit as an entry in a sqlite database.
instance
A manual instance that overwrites the max log likelihood instance in fit (e.g. for drawing the instance
randomly from the PDF).
"""
return _fit_imaging_from(
fit=fit,
instance=instance,
settings_inversion=self.settings_inversion,
use_preloaded_grid=self.use_preloaded_grid,
)
|
Jammy2211REPO_NAMEPyAutoLensPATH_START.@PyAutoLens_extracted@PyAutoLens-main@autolens@aggregator@fit_imaging.py@.PATH_END.py
|
{
"filename": "eep.py",
"repo_name": "timothydmorton/isochrones",
"repo_path": "isochrones_extracted/isochrones-master/isochrones/mist/eep.py",
"type": "Python"
}
|
def default_max_eep(mass):
"""For MIST v1.2
"""
if mass < 0.6:
return 454
elif mass == 0.6:
return 605
elif mass == 0.65:
return 808
elif mass < 6.0:
return 1710
else:
return 808
def max_eep(mass, feh):
"""For MIST v1.2
"""
eep = None
if feh == -4.0:
if mass < 0.6:
eep = 454
elif mass <= 0.94:
eep = 631
elif mass < 3.8:
eep = 808
elif mass <= 4.4:
eep = 1409
elif mass >= 18:
eep = 631
elif feh == -3.5:
if mass == 0.65:
eep = 631
elif 0.65 < mass < 1.78:
eep = 808
elif mass == 1.78:
eep = 1409
elif 1.78 < mass <= 3.4:
eep = 808
elif mass >= 19:
eep = 707
elif feh == -3.0:
if 0.7 <= mass <= 2.48:
eep = 808
elif 2.5 <= mass <= 4.4:
eep = 1409
elif feh == -2.5:
if 0.7 <= mass <= 2.32:
eep = 808
elif 2.32 < mass <= 5.8:
eep = 1409
elif feh == 0.5:
if 0.7 <= mass <= 0.75:
eep = 808
if eep is None:
return default_max_eep(mass)
else:
return eep
|
timothydmortonREPO_NAMEisochronesPATH_START.@isochrones_extracted@isochrones-master@isochrones@mist@eep.py@.PATH_END.py
|
{
"filename": "api.py",
"repo_name": "rennehan/yt-swift",
"repo_path": "yt-swift_extracted/yt-swift-main/yt/analysis_modules/particle_trajectories/api.py",
"type": "Python"
}
|
raise RuntimeError(
"Particle trajectories are now available from DatasetSeries "
"objects as ts.particle_trajectories. The ParticleTrajectories "
"analysis module has been removed."
)
|
rennehanREPO_NAMEyt-swiftPATH_START.@yt-swift_extracted@yt-swift-main@yt@analysis_modules@particle_trajectories@api.py@.PATH_END.py
|
{
"filename": "update_vds_paths.py",
"repo_name": "SWIFTSIM/SOAP",
"repo_path": "SOAP_extracted/SOAP-master/update_vds_paths.py",
"type": "Python"
}
|
#!/bin/env python
import sys
import h5py
import numpy as np
import os.path
def update_vds_paths(dset, modify_function):
"""
Modify the virtual paths of the specified dataset
Note that querying the source dataspace and selection does not appear
to work (invalid pointer error from h5py) so here we assume that we're
referencing all of the source dataspace, which is correct for SWIFT
snapshots.
dset: a h5py.Dataset object
modify_function: a function which takes the old path as its argument and
returns the new path
"""
# Choose a temporary path for the new virtual dataset
path = dset.name
tmp_path = dset.name + ".__tmp__"
# Build the creation property list for the new dataset
plist = h5py.h5p.create(h5py.h5p.DATASET_CREATE)
for vs in dset.virtual_sources():
bounds = vs.vspace.get_select_bounds()
if bounds is not None:
lower, upper = bounds
size = np.asarray(upper, dtype=int) - np.asarray(lower, dtype=int) + 1
src_space = h5py.h5s.create_simple(tuple(size))
new_name = modify_function(vs.file_name)
plist.set_virtual(
vs.vspace, new_name.encode(), vs.dset_name.encode(), src_space
)
# Create the new dataset
tmp_dset = h5py.h5d.create(
dset.file["/"].id,
tmp_path.encode(),
dset.id.get_type(),
dset.id.get_space(),
dcpl=plist,
)
tmp_dset = h5py.Dataset(tmp_dset)
for attr_name in dset.attrs:
tmp_dset.attrs[attr_name] = dset.attrs[attr_name]
# Rename the new dataset
f = dset.file
del f[path]
f[path] = f[tmp_path]
del f[tmp_path]
def update_virtual_snapshot_paths(filename, snapshot_dir=None, membership_dir=None):
"""
Add full paths to virtual datasets in the specified file
"""
f = h5py.File(filename, "r+")
# Find all datasets in the file
all_datasets = []
def visit_datasets(name, obj):
if isinstance(obj, h5py.Dataset):
all_datasets.append(obj)
f.visititems(visit_datasets)
def replace_snapshot_path(old_path):
basename = os.path.basename(old_path)
return os.path.join(snapshot_dir, basename)
def replace_membership_path(old_path):
basename = os.path.basename(old_path)
return os.path.join(membership_dir, basename)
# Loop over datasets and update paths if necessary
for dset in all_datasets:
if dset.is_virtual:
name = dset.name.split("/")[-1]
# Data comes from the membership files
if name in ("GroupNr_all", "GroupNr_bound", "Rank_bound", "HaloCatalogueIndex"):
if membership_dir is not None:
update_vds_paths(dset, replace_membership_path)
# FOF IDs come from membership files
elif (name == "FOFGroupIDs") and ("PartType1/FOFGroupIDs_old" in f):
if membership_dir is not None:
update_vds_paths(dset, replace_membership_path)
# Data comes from the snapshot files
else:
if snapshot_dir is not None:
update_vds_paths(dset, replace_snapshot_path)
f.close()
if __name__ == "__main__":
filename = sys.argv[1] # Virtual snapshot file to update
snapshot_dir = sys.argv[2] # Directory with the real snapshot files
membership_dir = sys.argv[3] # Directory with the real membership files
update_virtual_snapshot_paths(filename, snapshot_dir, membership_dir)
|
SWIFTSIMREPO_NAMESOAPPATH_START.@SOAP_extracted@SOAP-master@update_vds_paths.py@.PATH_END.py
|
{
"filename": "_width.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/layout/shape/line/_width.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class WidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="width", parent_name="layout.shape.line", **kwargs):
super(WidthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
anim=kwargs.pop("anim", True),
edit_type=kwargs.pop("edit_type", "calc+arraydraw"),
min=kwargs.pop("min", 0),
role=kwargs.pop("role", "style"),
**kwargs
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@layout@shape@line@_width.py@.PATH_END.py
|
{
"filename": "sync.py",
"repo_name": "mpi4py/mpi4py",
"repo_path": "mpi4py_extracted/mpi4py-master/src/mpi4py/util/sync.py",
"type": "Python"
}
|
# Author: Lisandro Dalcin
# Contact: dalcinl@gmail.com
"""Synchronization utilities."""
import array as _array
import time as _time
from .. import MPI
__all__ = [
"Sequential",
"Counter",
"Mutex",
"Condition",
"Semaphore",
]
class Sequential:
"""Sequential execution."""
def __init__(self, comm, tag=0):
"""Initialize sequential execution.
Args:
comm: Intracommunicator context.
tag: Tag for point-to-point communication.
"""
self.comm = comm
self.tag = int(tag)
def __enter__(self):
"""Enter sequential execution."""
self.begin()
return self
def __exit__(self, *exc):
"""Exit sequential execution."""
self.end()
def begin(self):
"""Begin sequential execution."""
comm = self.comm
size = comm.Get_size()
if size == 1:
return
rank = comm.Get_rank()
buf = (bytearray(), 0, MPI.BYTE)
tag = self.tag
if rank != 0:
comm.Recv(buf, rank - 1, tag)
def end(self):
"""End sequential execution."""
comm = self.comm
size = comm.Get_size()
if size == 1:
return
rank = comm.Get_rank()
buf = (bytearray(), 0, MPI.BYTE)
tag = self.tag
if rank != size - 1:
comm.Send(buf, rank + 1, tag)
class Counter:
"""Global counter."""
def __init__(
self,
start=0,
step=1,
*,
typecode='i',
comm=MPI.COMM_SELF,
info=MPI.INFO_NULL,
root=0,
):
"""Initialize global counter.
Args:
start: Start value.
step: Increment value.
typecode: Type code as defined in the `array` module.
comm: Intracommunicator context.
info: Info object for RMA context creation.
root: Process rank holding the counter memory.
"""
# pylint: disable=too-many-arguments
datatype = MPI.Datatype.fromcode(typecode)
typechar = datatype.typechar
rank = comm.Get_rank()
count = 1 if rank == root else 0
unitsize = datatype.Get_size()
window = MPI.Win.Allocate(count * unitsize, unitsize, info, comm)
self._start = start
self._step = step
self._window = window
self._typechar = typechar
self._location = (root, 0)
self._comm = comm
init = _array.array(typechar, [start] * count)
window.Lock(rank, MPI.LOCK_SHARED)
window.Accumulate(init, rank, op=MPI.REPLACE)
window.Unlock(rank)
comm.Barrier()
def __iter__(self):
"""Implement ``iter(self)``."""
return self
def __next__(self):
"""Implement ``next(self)``."""
return self.next()
def next(self, incr=None):
"""Return current value and increment.
Args:
incr: Increment value.
Returns:
The counter value before incrementing.
"""
if not self._window:
raise RuntimeError("counter already freed")
window = self._window
typechar = self._typechar
root, disp = self._location
incr = incr if incr is not None else self._step
incr = _array.array(typechar, [incr])
prev = _array.array(typechar, [0])
op = MPI.SUM if incr[0] != 0 else MPI.NO_OP
window.Lock(root, MPI.LOCK_SHARED)
window.Fetch_and_op(incr, prev, root, disp, op)
window.Unlock(root)
return prev[0]
def free(self):
"""Free counter resources."""
window = self._window
self._window = MPI.WIN_NULL
self._comm = MPI.COMM_NULL
window.free()
class Mutex:
"""Mutual exclusion."""
def __init__(
self,
*,
recursive=False,
comm=MPI.COMM_SELF,
info=MPI.INFO_NULL,
):
"""Initialize mutex object.
Args:
comm: Intracommunicator context.
recursive: Whether to allow recursive acquisition.
info: Info object for RMA context creation.
"""
null_rank, tail_rank = MPI.PROC_NULL, 0
rank = comm.Get_rank()
count = 3 if rank == tail_rank else 2
unitsize = MPI.INT.Get_size()
window = MPI.Win.Allocate(count * unitsize, unitsize, info, comm)
self._recursive = bool(recursive)
self._window = window
self._comm = comm
init = [False, null_rank, null_rank][:count]
init = _array.array('i', init)
window.Lock(rank, MPI.LOCK_SHARED)
window.Accumulate(init, rank, op=MPI.REPLACE)
window.Unlock(rank)
comm.Barrier()
def _acquire(self, blocking=True):
null_rank, tail_rank = MPI.PROC_NULL, 0
lock_id, next_id, tail_id = (0, 1, 2)
window = self._window
self_rank = window.group_rank
window.Lock_all()
rank = _array.array('i', [self_rank])
null = _array.array('i', [null_rank])
prev = _array.array('i', [null_rank])
window.Accumulate(null, self_rank, next_id, MPI.REPLACE)
if blocking:
window.Fetch_and_op(rank, prev, tail_rank, tail_id, MPI.REPLACE)
else:
window.Compare_and_swap(rank, null, prev, tail_rank, tail_id)
window.Flush(tail_rank)
locked = int(prev[0] == null_rank)
if blocking and not locked:
# Add ourselves to the waiting queue
window.Accumulate(rank, prev[0], next_id, MPI.REPLACE)
# Spin until we are given the lock
locked = self._spinloop(lock_id, 0)
# Set the local lock flag
flag = _array.array('i', [locked])
window.Accumulate(flag, self_rank, lock_id, MPI.REPLACE)
window.Unlock_all()
return bool(locked)
def _release(self):
null_rank, tail_rank = MPI.PROC_NULL, 0
lock_id, next_id, tail_id = (0, 1, 2)
window = self._window
self_rank = window.group_rank
window.Lock_all()
rank = _array.array('i', [self_rank])
null = _array.array('i', [null_rank])
prev = _array.array('i', [null_rank])
window.Compare_and_swap(null, rank, prev, tail_rank, tail_id)
window.Flush(tail_rank)
if prev[0] != rank[0]:
# Spin until the next process notify us
next_rank = self._spinloop(next_id, null_rank)
# Pass the lock over to the next process
true = _array.array('i', [True])
window.Accumulate(true, next_rank, lock_id, MPI.REPLACE)
# Set the local lock flag
false = _array.array('i', [False])
window.Accumulate(false, self_rank, lock_id, MPI.REPLACE)
window.Unlock_all()
def _count_fetch_and_op(self, value, op):
lock_id = 0
window = self._window
self_rank = window.group_rank
incr = _array.array('i', [value])
prev = _array.array('i', [0])
window.Lock(self_rank, MPI.LOCK_SHARED)
window.Fetch_and_op(incr, prev, self_rank, lock_id, op)
window.Unlock(self_rank)
return prev[0]
def _acquire_restore(self, state):
self._acquire()
if self._recursive:
self._count_fetch_and_op(state, MPI.REPLACE)
def _release_save(self):
state = None
if self._recursive:
state = self._count_fetch_and_op(0, MPI.NO_OP)
self._release()
return state
def _spinloop(self, index, sentinel):
window = self._window
return _rma_spinloop(window, 'i', index, sentinel)
def __enter__(self):
"""Acquire mutex."""
self.acquire()
return self
def __exit__(self, *exc):
"""Release mutex."""
self.release()
def acquire(self, blocking=True):
"""Acquire mutex, blocking or non-blocking.
Args:
blocking: If `True`, block until the mutex is held.
Returns:
`True` if the mutex is held, `False` otherwise.
"""
if not self._window:
raise RuntimeError("mutex already freed")
if self.locked():
if self._recursive:
self._count_fetch_and_op(+1, MPI.SUM)
return True
raise RuntimeError("cannot acquire already held mutex")
return self._acquire(blocking)
def release(self):
"""Release mutex."""
if not self._window:
raise RuntimeError("mutex already freed")
if not self.locked():
raise RuntimeError("cannot release unheld mutex")
if self._recursive:
if self._count_fetch_and_op(-1, MPI.SUM) > 1:
return
self._release()
def locked(self):
"""Return whether the mutex is held."""
if not self._window:
raise RuntimeError("mutex already freed")
lock_id = 0
memory = memoryview(self._window).cast('i')
return bool(memory[lock_id])
def count(self):
"""Return the recursion count."""
if not self._window:
raise RuntimeError("mutex already freed")
return self._count_fetch_and_op(0, MPI.NO_OP)
def free(self):
"""Free mutex resources."""
if self._window:
if self.locked():
self._release()
window = self._window
self._window = MPI.WIN_NULL
self._comm = MPI.COMM_NULL
window.free()
class Condition:
"""Condition variable."""
def __init__(
self,
mutex=None,
*,
recursive=True,
comm=MPI.COMM_SELF,
info=MPI.INFO_NULL,
):
"""Initialize condition variable.
Args:
mutex: Mutual exclusion object.
recursive: Whether to allow recursive acquisition.
comm: Intracommunicator context.
info: Info object for RMA context creation.
"""
if mutex is None:
self._mutex = Mutex(recursive=recursive, comm=comm, info=info)
self._mutex_free = self._mutex.free
else:
self._mutex = mutex
self._mutex_free = lambda: None
comm = mutex._comm # pylint disable=protected-access
null_rank, tail_rank = MPI.PROC_NULL, 0
rank = comm.Get_rank()
count = 3 if rank == tail_rank else 2
unitsize = MPI.INT.Get_size()
window = MPI.Win.Allocate(count * unitsize, unitsize, info, comm)
self._window = window
self._comm = comm
init = [0, null_rank, null_rank][:count]
init = _array.array('i', init)
window.Lock(rank, MPI.LOCK_SHARED)
window.Accumulate(init, rank, op=MPI.REPLACE)
window.Unlock(rank)
comm.Barrier()
def _enqueue(self, process):
null_rank, tail_rank = MPI.PROC_NULL, 0
next_id, tail_id = (1, 2)
window = self._window
rank = _array.array('i', [process])
prev = _array.array('i', [null_rank])
next = _array.array('i', [process]) # pylint: disable=W0622
window.Lock_all()
window.Fetch_and_op(rank, prev, tail_rank, tail_id, MPI.REPLACE)
window.Flush(tail_rank)
if prev[0] != null_rank:
window.Fetch_and_op(rank, next, prev[0], next_id, MPI.REPLACE)
window.Flush(prev[0])
window.Accumulate(next, rank[0], next_id, MPI.REPLACE)
window.Unlock_all()
def _dequeue(self, maxnumprocs):
null_rank, tail_rank = MPI.PROC_NULL, 0
next_id, tail_id = (1, 2)
window = self._window
null = _array.array('i', [null_rank])
prev = _array.array('i', [null_rank])
next = _array.array('i', [null_rank]) # pylint: disable=W0622
processes = []
maxnumprocs = max(0, min(maxnumprocs, window.group_size))
window.Lock_all()
window.Fetch_and_op(null, prev, tail_rank, tail_id, MPI.NO_OP)
window.Flush(tail_rank)
if prev[0] != null_rank:
empty = False
window.Fetch_and_op(null, next, prev[0], next_id, MPI.NO_OP)
window.Flush(prev[0])
while len(processes) < maxnumprocs and not empty:
rank = next[0]
processes.append(rank)
window.Fetch_and_op(null, next, rank, next_id, MPI.NO_OP)
window.Flush(rank)
empty = processes[0] == next[0]
if not empty:
window.Accumulate(next, prev[0], next_id, MPI.REPLACE)
else:
window.Accumulate(null, tail_rank, tail_id, MPI.REPLACE)
window.Unlock_all()
return processes
def _sleep(self):
flag_id = 0
window = self._window
window.Lock_all()
_rma_spinloop(window, 'i', flag_id, 0, reset=True)
window.Unlock_all()
def _wakeup(self, processes):
flag_id = 0
window = self._window
flag = _array.array('i', [1])
window.Lock_all()
for rank in processes:
window.Accumulate(flag, rank, flag_id, MPI.REPLACE)
window.Unlock_all()
def _release_save(self):
# pylint: disable=protected-access
return self._mutex._release_save()
def _acquire_restore(self, state):
# pylint: disable=protected-access
self._mutex._acquire_restore(state)
def _mutex_reset(self):
# pylint: disable=protected-access
if self._mutex._window:
if self._mutex.locked():
self._mutex._release()
def __enter__(self):
"""Acquire the underlying mutex."""
self.acquire()
return self
def __exit__(self, *exc):
"""Release the underlying mutex."""
self.release()
def acquire(self, blocking=True):
"""Acquire the underlying mutex."""
if not self._window:
raise RuntimeError("condition already freed")
return self._mutex.acquire(blocking)
def release(self):
"""Release the underlying mutex."""
if not self._window:
raise RuntimeError("condition already freed")
self._mutex.release()
def locked(self):
"""Return whether the underlying mutex is held."""
return self._mutex.locked()
def wait(self):
"""Wait until notified by another process.
Returns:
Always `True`.
"""
if not self._window:
raise RuntimeError("condition already freed")
if not self.locked():
raise RuntimeError("cannot wait on unheld mutex")
self._enqueue(self._window.group_rank)
state = self._release_save()
self._sleep()
self._acquire_restore(state)
return True
def wait_for(self, predicate):
"""Wait until a predicate evaluates to `True`.
Args:
predicate: callable returning a boolean.
Returns:
The result of predicate once it evaluates to `True`.
"""
result = predicate()
while not result:
self.wait()
result = predicate()
return result
def notify(self, n=1):
"""Wake up one or more processes waiting on this condition.
Args:
n: Maximum number of processes to wake up.
Returns:
The actual number of processes woken up.
"""
if not self._window:
raise RuntimeError("condition already freed")
if not self.locked():
raise RuntimeError("cannot notify on unheld mutex")
processes = self._dequeue(n)
numprocs = len(processes)
self._wakeup(processes)
return numprocs
def notify_all(self):
"""Wake up all processes waiting on this condition.
Returns:
The actual number of processes woken up.
"""
return self.notify((1 << 31) - 1)
def free(self):
"""Free condition resources."""
self._mutex_reset()
self._mutex_free()
window = self._window
self._window = MPI.WIN_NULL
self._comm = MPI.COMM_NULL
window.free()
class Semaphore:
"""Semaphore object."""
def __init__(
self,
value=1,
*,
bounded=True,
comm=MPI.COMM_SELF,
info=MPI.INFO_NULL,
):
"""Initialize semaphore object.
Args:
value: Initial value for internal counter.
bounded: Bound internal counter to initial value.
comm: Intracommunicator context.
info: Info object for RMA context creation.
"""
if value < 0:
raise ValueError("initial value must be non-negative")
self._bounded = bool(bounded)
self._counter = Counter(value, comm=comm, info=info)
self._condvar = Condition(recursive=False, comm=comm, info=info)
self._comm = comm
def __enter__(self):
"""Acquire semaphore."""
self.acquire()
return self
def __exit__(self, *exc):
"""Release semaphore."""
self.release()
def acquire(self, blocking=True):
"""Acquire semaphore, decrementing the internal counter by one.
Args:
blocking: If `True`, block until the semaphore is acquired.
Returns:
`True` if the semaphore is acquired, `False` otherwise.
"""
with self._condvar:
while self._counter.next(0) == 0:
if not blocking:
return False
self._condvar.wait()
self._counter.next(-1)
return True
def release(self, n=1):
"""Release semaphore, incrementing the internal counter by one or more.
Args:
n: Increment for the internal counter.
"""
if n < 1:
raise ValueError('increment must be one or more')
with self._condvar:
if self._bounded:
# pylint: disable=protected-access
current = self._counter.next(0)
initial = self._counter._start
if current + n > initial:
raise ValueError("semaphore released too many times")
self._counter.next(n)
self._condvar.notify(n)
def free(self):
"""Free semaphore resources."""
self._counter.free()
self._condvar.free()
self._comm = MPI.COMM_NULL
_BACKOFF_DELAY_MAX = 1 / 1024
_BACKOFF_DELAY_MIN = _BACKOFF_DELAY_MAX / 1024
_BACKOFF_DELAY_INIT = 0.0
_BACKOFF_DELAY_RATIO = 2.0
def _new_backoff(
delay_max=_BACKOFF_DELAY_MAX,
delay_min=_BACKOFF_DELAY_MIN,
delay_init=_BACKOFF_DELAY_INIT,
delay_ratio=_BACKOFF_DELAY_RATIO,
):
def backoff_iterator():
delay = delay_init
while True:
_time.sleep(delay)
delay = min(delay_max, max(delay_min, delay * delay_ratio))
yield
backoff = backoff_iterator()
return lambda: next(backoff)
def _rma_progress(window):
window.Flush(window.group_rank)
def _rma_spinloop(
window, typecode, index, sentinel, reset=False,
backoff=None, progress=None,
): # pylint: disable=too-many-arguments,too-many-positional-arguments
memory = memoryview(window).cast(typecode)
backoff = backoff or _new_backoff()
progress = progress or _rma_progress
window.Sync()
while memory[index] == sentinel:
backoff()
progress(window)
window.Sync()
value = memory[index]
if reset:
memory[index] = sentinel
return value
|
mpi4pyREPO_NAMEmpi4pyPATH_START.@mpi4py_extracted@mpi4py-master@src@mpi4py@util@sync.py@.PATH_END.py
|
{
"filename": "setjy.py",
"repo_name": "RTIP/artip",
"repo_path": "artip_extracted/artip-master/casa_scripts/setjy.py",
"type": "Python"
}
|
import sys
script_parameters_start_index = sys.argv.index('-c') + 2
parameters = sys.argv[script_parameters_start_index:]
spw = parameters[0]
ms_dataset = parameters[1]
field = parameters[2]
model_path = parameters[3]
setjy(vis=ms_dataset, field=field, spw=spw, modimage=model_path, usescratch=True)
|
RTIPREPO_NAMEartipPATH_START.@artip_extracted@artip-master@casa_scripts@setjy.py@.PATH_END.py
|
{
"filename": "_borderwidth.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scattermapbox/marker/colorbar/_borderwidth.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class BorderwidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name="borderwidth",
parent_name="scattermapbox.marker.colorbar",
**kwargs,
):
super(BorderwidthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
min=kwargs.pop("min", 0),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scattermapbox@marker@colorbar@_borderwidth.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "hahnec/torchimize",
"repo_path": "torchimize_extracted/torchimize-master/tests/__init__.py",
"type": "Python"
}
|
hahnecREPO_NAMEtorchimizePATH_START.@torchimize_extracted@torchimize-master@tests@__init__.py@.PATH_END.py
|
|
{
"filename": "pse.py",
"repo_name": "GalSim-developers/GalSim",
"repo_path": "GalSim_extracted/GalSim-main/galsim/pse.py",
"type": "Python"
}
|
# Copyright (c) 2012-2023 by the GalSim developers team on GitHub
# https://github.com/GalSim-developers
#
# This file is part of GalSim: The modular galaxy image simulation toolkit.
# https://github.com/GalSim-developers/GalSim
#
# GalSim is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
#
"""
Module containing code for estimating shear power spectra from shears at gridded positions.
The code below was developed largely by Joe Zuntz and tweaked by assorted GalSim
developers. This development and testing took place in a separate (private) repository before the
code was moved into the GalSim repository, but there are some demonstrations of the performance of
this code in devel/modules/lensing_engine.pdf
"""
import numpy as np
import os
import sys
from .errors import GalSimError, GalSimValueError, GalSimIncompatibleValuesError
from .table import LookupTable
class PowerSpectrumEstimator:
"""Class for estimating the shear power spectrum from gridded shears.
This class stores all the data used in power spectrum estimation that is fixed with the geometry
of the problem - the binning and spin weighting factors.
The only public method is estimate(), which is called with 2D ``g1`` and ``g2`` arrays on a
square grid. It assumes the flat sky approximation (where ``ell`` and ``k`` are
interchangeable), and rebins the observed ell modes into a user-defined number of logarithimic
bins in ell. Given that the grid parameters are precomputed and stored when the
`PowerSpectrumEstimator` is initialized, computation of the PS for multiple sets of shears
corresponding to the same grid setup can proceed more rapidly than if everything had to be
recomputed each time.
Below is an example of how to use this code (relying on GalSim to provide the arrays of g1 and
g2, though that is by no means required, and assuming that the user is sitting in the examples/
directory)::
>>> grid_size = 10. # Define the total grid extent, in degrees
>>> ngrid = 100 # Define the number of grid points in each dimension: (ngrid x ngrid)
>>> n_ell = 15 # Choose the number of logarithmic bins in ell or k for outputs
>>>
>>> # Define a lookup-table for the power spectrum as a function of k based on the outputs
>>> # of iCosmo (see demo11.py for more description of how this was generated).
>>> my_tab = galsim.LookupTable(file='data/cosmo-fid.zmed1.00.out')
>>>
>>> # Generate a galsim.PowerSpectrum with this P(k), noting the units.
>>> my_ps = galsim.PowerSpectrum(my_tab, units=galsim.radians)
>>>
>>> # Build a grid of shear values with the desired parameters.
>>> g1, g2 = my_ps.buildGrid(grid_spacing=grid_size/ngrid, ngrid=ngrid,
... units=galsim.degrees)
>>>
>>> # Initialize a PowerSpectrumEstimator with the chosen grid geometry and number of ell
>>> # bins. Note that these values are actually the default, so we didn't technically have
>>> # to specifythem.
>>> my_pse = galsim.pse.PowerSpectrumEstimator(ngrid, grid_size, n_ell)
>>>
>>> # Estimate the power based on this set of g1, g2. If we get another set of shears for
>>> # the same grid geometry, we can reuse the same PowerSpectrumEstimator object.
>>> ell, P_e, P_b, P_eb = my_pse.estimate(g1, g2)
The output NumPy arrays ``ell``, ``P_e``, ``P_b``, and ``P_eb`` contain the effective ell
value, the E-mode auto-power spectrum, the B-mode auto-power spectrum, and the EB cross-power
spectrum. The units are inverse radians for ell, and radians^2 for the output power spectra.
Some important notes:
1) Power spectrum estimation requires a weight function which decides how the averaging is done
across ell within each bin. By default that weighting is flat in ell using an analytic
calculation of the area in ell space, but this is easy to change with the ``_bin_power``
function. (Note this area averaged bin weighting is only approximate for the higher
frequency bins in which the lower ``ell`` edge is greater than ``pi * ngrid / grid_size``,
due to the annular ``ell`` region being cut off by the square grid edges beyond this value.)
A keyword allows for weighting by the power itself.
2) This is the power spectrum of the gridded *data*, not the underlying field - we do not
account for the effects of the finite grid (basically, ignoring all the reasons why power
spectrum estimation is hard - see devel/modules/lensing_engine.pdf in the GalSim repository).
Users must account for the contribution of noise in ``g1``, ``g2`` and any masking.
3) The binning is currently fixed as uniform in log(ell).
4) The code for this class uses the notation of the GREAT10 handbook (Kitching et al. 2011,
http://dx.doi.org/10.1214/11-AOAS484), equations 17-21.
"""
def __init__(self, N=100, sky_size_deg=10., nbin=15):
"""Create a PowerSpectrumEstimator object given some grid parameters.
This constructor precomputes some numbers related to the grid geometry, so the same
PowerSpectrumEstimator can be used to estimate the power spectrum quickly for many sets of
shears at gridded positions.
Parameters:
N: The number of pixels along each side of the grid. [default: 100]
sky_size_deg: The total grid width (in one dimension) in degrees. [default: 10]
nbin: The number of evenly-spaced logarithmic ``ell`` bins to use for
estimating the power spectrum. [default: 15]
"""
# Set up the scales of the sky and pixels
self.N = N
self.sky_size_deg = sky_size_deg
self.nbin = nbin
self.sky_size = np.radians(sky_size_deg)
self.dx = self.sky_size / N
# Define the possible ell range, the bin edges and effective ell values.
# This is necessary for binning the power spectrum in ell.
lmin = 2*np.pi / self.sky_size
lmax = np.sqrt(2.)*np.pi / self.dx # in 2 dimensions
self.bin_edges = np.logspace(np.log10(lmin), np.log10(lmax), nbin+1)
# By default, report an area-averaged value of ell, which should be fine if there is
# no weighting (in which case it's recomputed) and if there are many ell modes in
# each bin. The latter assumption is most likely to break down at low ell. Note also that
# at high ell when the lower ell edge is greater than pi * ngrid / grid_size, due to the
# annular ell region being cut off by the square grid edges beyond this value, this annular
# average is only approximate.
self.ell = (2./3.)*(self.bin_edges[1:]**3-self.bin_edges[:-1]**3) \
/ (self.bin_edges[1:]**2-self.bin_edges[:-1]**2)
# Precompute and store two useful factors, both in the form of 2D grids in Fourier space.
# These are the lengths of the wavevector |ell| for each point in the space, and the complex
# valued spin-weighting that takes the complex shear fields -> E,B
self.l_abs, self.eb_rot = self._generate_eb_rotation()
def __repr__(self):
return "galsim.pse.PowerSpectrumEstimator(N=%r, sky_size_deg=%r, nbin=%r)"%(
self.N, self.sky_size_deg, self.nbin)
def __eq__(self, other): return self is other or repr(self) == repr(other)
def __ne__(self, other): return not self.__eq__(other)
def __hash__(self): return hash(repr(self))
def _generate_eb_rotation(self):
# Set up the Fourier space grid lx, ly.
ell = 2*np.pi*np.fft.fftfreq(self.N, self.dx)
lx, ly = np.meshgrid(ell,ell)
# Now compute the lengths and angles of the ell vectors.
l_sq = lx**2 + ly**2
# Compute exp(-2i psi) where psi = atan2(ly,lx)
l_sq[0,0] = 1 # Avoid division by 0
expm2ipsi = (lx - 1j * ly)**2 / l_sq
l_abs = np.sqrt(l_sq)
l_abs[0,0] = 0 # Go back to correct value at 0,0.
self.lx = lx
self.ly = ly
return l_abs, expm2ipsi
def _bin_power(self, C, ell_weight=None):
# This little utility function bins a 2D C^{E/B, E/B}_{ell} based on |ell|. The use of
# histogram is a little hack, but is quite convenient since it means everything is done in C
# so it is very fast. The first call to `histogram` just returns an array over the
# logarithmic ell bins of
# sum_{|ell| in bin} weight(|ell|)*C_{ell_x,ell_y}
# and the second call returns
# sum_{|ell| in bin} weight(|ell|).
# Thus, the ratio is just the mean power in the bin. If `ell_weight` is None, then weight=1
# for all ell, corresponding to a simple averaging process. If `ell_weight` is not None,
# then some non-flat weighting scheme is used for averaging over the ell values within a
# bin.
if ell_weight is not None:
ell_weight = np.abs(ell_weight)
P,_ = np.histogram(self.l_abs, self.bin_edges, weights=C*ell_weight)
count,_ = np.histogram(self.l_abs, self.bin_edges, weights=ell_weight)
else:
P,_ = np.histogram(self.l_abs, self.bin_edges, weights=C)
count,_ = np.histogram(self.l_abs, self.bin_edges)
if (count == 0).any():
raise GalSimError("Logarithmic bin definition resulted in >=1 empty bin!")
return P/count
def estimate(self, g1, g2, weight_EE=False, weight_BB=False, theory_func=None):
"""Compute the EE, BB, and EB power spectra of two 2D arrays ``g1`` and ``g2``.
For example usage, see the docstring for the `PowerSpectrumEstimator` class.
Parameters:
g1: The shear component g1 as a square 2D NumPy array.
g2: The shear component g2 as a square 2D NumPy array.
weight_EE: If True, then the E auto-power spectrum is re-computed weighting by
the power within each logarithmically-spaced ell bin. [default: False]
weight_BB: If True, then the B auto-power spectrum is re-computed weighting by
the power within each logarithmically-spaced ell bin. [default: False]
theory_func: An optional callable function that can be used to get an idealized
value of power at each point on the grid, and then see what results
it gives for our chosen ell binning. [default: None]
"""
# Check for the expected square geometry consistent with the previously-defined grid size.
if g1.shape != g2.shape:
raise GalSimIncompatibleValuesError(
"g1 and g2 grids do not have the same shape.", g1=g1, g2=g2)
if g1.shape[0] != g1.shape[1]:
raise GalSimValueError("Input shear arrays must be square.", g1.shape)
if g1.shape[0] != self.N:
raise GalSimValueError("Input shear array size is not correct!", g1.shape)
if not isinstance(weight_EE, bool) or not isinstance(weight_BB, bool):
raise TypeError("Input weight flags must be bools!")
# Transform g1+j*g2 into Fourier space and rotate into E-B, then separate into E and B.
EB = np.fft.ifft2(self.eb_rot * np.fft.fft2(g1 + 1j*g2))
E = np.fft.fft2(EB.real)
B = np.fft.fft2(EB.imag)
# Use the internal function above to bin, and account for the normalization of the FFT.
# Recall that power has units of angle^2, which is the reason why we need a self.dx^2 in the
# equations below in addition to the standard 1/N^2 coming from the FFTs.
C_EE = self._bin_power(E*np.conjugate(E))*(self.dx/self.N)**2
C_BB = self._bin_power(B*np.conjugate(B))*(self.dx/self.N)**2
C_EB = self._bin_power(E*np.conjugate(B))*(self.dx/self.N)**2
if theory_func is not None:
# theory_func needs to be a callable function
C_theory_ell = np.zeros_like(self.l_abs)
C_theory_ell[self.l_abs>0] = theory_func(self.l_abs[self.l_abs>0])
C_theory = self._bin_power(C_theory_ell)
if weight_EE or weight_BB:
# Need to interpolate C_EE to values of self.l_abs. A bit of kludginess as we go off
# the end of our final ell grid...
new_ell = np.zeros(len(self.ell)+2)
new_ell[1:len(self.ell)+1] = self.ell
new_ell[len(self.ell)+1] = 10.*max(self.ell)
if theory_func is not None:
C_theory = self._bin_power(C_theory_ell, ell_weight=C_theory_ell)
if weight_EE:
new_CEE = np.zeros_like(new_ell)
new_CEE[1:len(self.ell)+1] = np.real(C_EE)
new_CEE[len(self.ell)+1] = new_CEE[len(self.ell)]
EE_table = LookupTable(new_ell, new_CEE)
ell_weight = EE_table(self.l_abs)
C_EE = self._bin_power(E*np.conjugate(E), ell_weight=ell_weight)*(self.dx/self.N)**2
if weight_BB:
new_CBB = np.zeros_like(new_ell)
new_CBB[1:len(self.ell)+1] = np.real(C_BB)
new_CBB[len(self.ell)+1] = new_CBB[len(self.ell)]
BB_table = LookupTable(new_ell, new_CBB)
ell_weight = BB_table(self.l_abs)
C_BB = self._bin_power(B*np.conjugate(B), ell_weight=ell_weight)*(self.dx/self.N)**2
# For convenience, return ell (copied in case the user messes with it) and the three power
# spectra. If the user requested a binned theoretical spectrum, return that as well.
if theory_func is None:
return self.ell.copy(), np.real(C_EE), np.real(C_BB), np.real(C_EB)
else:
return self.ell.copy(), np.real(C_EE), np.real(C_BB), np.real(C_EB), np.real(C_theory)
|
GalSim-developersREPO_NAMEGalSimPATH_START.@GalSim_extracted@GalSim-main@galsim@pse.py@.PATH_END.py
|
{
"filename": "__init__.py",
"repo_name": "enthought/mayavi",
"repo_path": "mayavi_extracted/mayavi-master/tvtk/util/__init__.py",
"type": "Python"
}
|
# Author: Prabhu Ramachandran
# Copyright (c) 2006, Enthought, Inc.
# License: BSD Style.
|
enthoughtREPO_NAMEmayaviPATH_START.@mayavi_extracted@mayavi-master@tvtk@util@__init__.py@.PATH_END.py
|
{
"filename": "tables_dict.py",
"repo_name": "rbuehler/vasca",
"repo_path": "vasca_extracted/vasca-main/vasca/tables_dict.py",
"type": "Python"
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Defines dictionary for the tables used by vasca.tables.TableCollection
"""
# %% dtype guidelines
#
# >np.finfo(np.float16)
# >finfo(resolution=0.001, min=-6.55040e+04, max=6.55040e+04, dtype=float16)
#
# >np.finfo(np.float32)
# >finfo(resolution=1e-06, min=-3.4028235e+38, max=3.4028235e+38, dtype=float32)
#
# >np.finfo(np.float64)
# >ffinfo(resolution=1e-15, min=-1.7976931348623157e+308, max=1.7976931348623157e+308, dtype=float64)
#
# >np.iinfo(np.int32)
# >info(min=-2147483648, max=2147483647, dtype=int32)
#
# >np.iinfo(np.int64)
# >iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)
#
# Based on the above, we need float64 for MJD, ra, dec and int64 for external ID numbers
# For everything else float32 and int32 should be sufficient
# (e.g. for all flux variables and errors)
# import numpy as np
# global dictionaries defining the table structures
# %% Column definitions
dd_vasca_columns: dict[str, dict[str, str | float]] = {
# %%% field_id
"field_id": {
"name": "field_id",
"dtype": "S32",
"unit": "1",
"default": "none",
"description": "Field source ID number",
},
"src_name": {
"name": "src_name",
"dtype": "S24",
"unit": "1",
"default": "none",
"description": "VASCA catalog source name",
},
# %%% field_name
"field_name": {
"name": "field_name",
"dtype": "S32",
"unit": "",
"default": "none",
"description": "Field name",
},
# %%% project
"project": {
"name": "project",
"dtype": "S32",
"unit": "",
"default": "none",
"description": "Field project, typically survey name",
},
# %%% ra
"ra": {
"name": "ra",
"dtype": "float64",
"unit": "degree",
"default": -1.0,
"description": "Sky coordinate Right Ascension (J2000)",
},
# %%% dec
"dec": {
"name": "dec",
"dtype": "float64",
"unit": "degree",
"default": -1.0,
"description": "Sky coordinate Declination (J2000)",
},
# %%% observatory
"observatory": {
"name": "observatory",
"dtype": "S22",
"unit": "",
"default": "none",
"description": "Telescope of the observation (e.g. GALEX)",
},
# %%% obs_filter
"obs_filter": {
"name": "obs_filter",
"dtype": "S8",
"unit": "",
"default": "none",
"description": "Filter of the observation (e.g. NUV)",
},
# %%% obs_filter_idx
"obs_filter_idx": {
"name": "obs_filter_idx",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Filter index in filter dependent arrays",
},
# %%% obs_filter_id
"obs_filter_id": {
"name": "obs_filter_id",
"dtype": "int32",
"unit": "1",
"default": 0,
"description": "Observation filter ID number",
},
# %%% wavelength
"wavelength": {
"name": "wavelength",
"dtype": "float32",
"unit": "AA",
"default": -1.0,
"description": "Effective wavelength of the observation filter",
},
# %%% fov_diam
"fov_diam": {
"name": "fov_diam",
"dtype": "float32",
"unit": "degree",
"default": -1.0,
"description": "Field radius or box size (depending on the observatory)",
},
# %%% vis_id
"vis_id": {
"name": "vis_id",
"dtype": "uint64",
"unit": "1",
"default": -1,
"description": "Visit ID number",
},
# %%% time_bin_start
"time_bin_start": {
"name": "time_bin_start",
"dtype": "float64",
"unit": "d",
"default": -1.0,
"description": "Visit exposure start date and time in MJD",
},
# %%% time_bin_size
"time_bin_size": {
"name": "time_bin_size",
"dtype": "float32",
"unit": "s",
"default": -1.0,
"description": "Visit exposure time in s",
},
# %%% fd_src_id
"fd_src_id": {
"name": "fd_src_id",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Source ID associated to the visit detection",
},
# %%% pos_err
"pos_err": {
"name": "pos_err",
"dtype": "float32",
"unit": "arcsec",
"default": -1.0,
"description": "Sky coordinate position error",
},
# %%% flux
"flux": {
"name": "flux",
"dtype": "float32",
"unit": "1e-6Jy",
"default": -1.0,
"description": "Flux density",
},
"flux_model": {
"name": "flux",
"dtype": "float32",
"unit": "1e-6Jy",
"default": -1.0,
"description": "Flux from SDSS model spectrum.",
},
# %%% flux_app_ratio
"flux_app_ratio": {
"name": "flux_app_ratio",
"dtype": "float32",
"unit": "1",
"default": -1.0,
"description": "Flux ratio measured at a different apertures (3.8 arcsec / 6 arcsec radius for GALEX)",
},
# %%% flux_err
"flux_err": {
"name": "flux_err",
"dtype": "float32",
"unit": "1e-6Jy",
"default": -1.0,
"description": "Flux density error",
},
# %%% s2n
"s2n": {
"name": "s2n",
"dtype": "float32",
"unit": "1",
"default": -1.0,
"description": "Flux signal to noise",
},
# %%% det_id
"det_id": {
"name": "det_id",
"dtype": "int64",
"unit": "1",
"default": -1,
"description": "Reference source ID number",
},
# %%% mag
"mag": {
"name": "mag",
"dtype": "float32",
"unit": "mag",
"default": -1.0,
"description": "AB magnitude",
},
# %%% mag_err
"mag_err": {
"name": "mag_err",
"dtype": "float32",
"unit": "mag",
"default": -1.0,
"description": "AB magnitude error",
},
# %%% nr_det
"nr_det": {
"name": "nr_det",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Number of detections",
},
# %%% pos_xv
"pos_xv": {
"name": "pos_xv",
"dtype": "float32",
"unit": "arcsec2",
"default": -1.0,
"description": "Sky position excess variance",
},
# %%% pos_var
"pos_var": {
"name": "pos_var",
"dtype": "float32",
"unit": "arcsec2",
"default": -1.0,
"description": "Sky position variance",
},
# %%% pos_cpval
"pos_cpval": {
"name": "pos_cpval",
"dtype": "float32",
"unit": "1",
"default": -1.0,
"description": "Sky position quality",
},
# %%% pos_rchiq
"pos_rchiq": {
"name": "pos_rchiq",
"dtype": "float32",
"unit": "1",
"default": -1.0,
"description": "Sky position reduced chisquared of the constant mean",
},
# %%% coadd_id
"coadd_id": {
"name": "coadd_id",
"dtype": "int64",
"unit": "1",
"default": -1,
"description": "Associated co-add source or detection ID",
},
# %%% coadd_dist
"coadd_dist": {
"name": "coadd_dist",
"dtype": "float32",
"unit": "arcsec",
"default": -1.0,
"description": "Angular distance to associated source",
},
"cat_dist": {
"name": "cat_dist",
"dtype": "float32",
"unit": "arcsec",
"default": -1.0,
"description": "Angular distance to associated catalog source",
},
# %%% match_distance
"match_distance": {
"name": "match_distance",
"dtype": "float32",
"unit": "arcsec",
"default": -1.0,
"description": "Angular distance to associated source",
},
# %%% sel
"sel": {
"name": "sel",
"dtype": "bool",
"unit": "1",
"default": True,
"description": "Selection of rows for VASCA analysis",
},
# %%% flux_nxv
"flux_nxv": {
"name": "flux_nxv",
"dtype": "float32",
"unit": "1",
"default": -100.0,
"description": "Flux normalised excess variance",
},
# %%% flux_ne
"flux_ne": {
"name": "flux_ne",
"dtype": "float32",
"unit": "1",
"default": -100.0,
"description": "Flux square root of normalised excess variance",
},
# %%% flux_var
"flux_var": {
"name": "flux_var",
"dtype": "float32",
"unit": "1e-12Jy2",
"default": -1.0,
"description": "Flux variance",
},
# %%% flux_cpval
"flux_cpval": {
"name": "flux_cpval",
"dtype": "float32",
"unit": "1",
"default": -1.0,
"description": "Probability value for a constant flux from the chisquare test",
},
# %%% flux_rchiq
"flux_rchiq": {
"name": "flux_rchiq",
"dtype": "float32",
"unit": "1",
"default": -1.0,
"description": "Flux reduced chisquared of the constant mean",
},
# %%% coadd_ffactor
"coadd_ffactor": {
"name": "coadd_ffactor",
"dtype": "float32",
"unit": "1",
"default": -100.0,
"description": "Source flux divided by flux of the associated co-add source",
},
# %%% time_start
"time_start": {
"name": "time_start",
"dtype": "float64",
"unit": "d",
"default": -1.0,
"description": "Start date and time in MJD",
},
# %%% time
"time": {
"name": "time",
"dtype": "float64",
"unit": "d",
"default": -1.0,
"description": "Time in MJD",
},
# %%% ul
"ul": {
"name": "ul",
"dtype": "float32",
"unit": "1e-6Jy",
"default": -1.0,
"description": "Flux density upper limit",
},
# %%% time_bin_size_alt_filt
"time_bin_size_alt_filt": {
"name": "time_bin_size_alt_filt",
"dtype": "float64",
"unit": "s",
"default": -1.0,
"description": "Visit exposure time of the alternative filter in s",
},
# %%% r_fov
"r_fov": {
"name": "r_fov",
"dtype": "float32",
"unit": "degree",
"default": -1.0,
"description": "Distance from center of FOV in degrees",
},
# %%% artifacts
"artifacts": {
"name": "artifacts",
"dtype": "int64",
"unit": "1",
"default": -1,
"description": "Logical OR of artifact flags",
},
# %%% flags
"flags": {
"name": "flags",
"dtype": "int64",
"unit": "1",
"default": -1,
"description": "Logical OR of artifact flags from gphoton",
},
# %%% class_star
"class_star": {
"name": "class_star",
"dtype": "float32",
"unit": "1",
"default": -1.0,
"description": "Point-source probability: 0.0 (resolved), 1.0 (unresolved, mcat file filter_CLASS_STAR variable)",
},
# %%% chkobj_type
"chkobj_type": {
"name": "chkobj_type",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Detection matched to a known star (bright_match=1, mcat file chkobj_type variable)",
},
# %%% size_world
"size_world": {
"name": "size_world",
"dtype": "float32",
"unit": "arcsec",
"default": -1,
"description": "Mean RMS of the ellipse size: (major axis + minor axis) / 2",
},
# %%% ellip_world
"ellip_world": {
"name": "ellip_world",
"dtype": "float32",
"unit": "1",
"default": -1,
"description": "Ellipticity of the detection or source",
},
# %%% flux_auto
"flux_auto": {
"name": "flux_auto",
"dtype": "float32",
"unit": "Jy",
"default": -1.0,
"description": "Flux from SExtractor auto option",
},
# %%% flux_auto_err
"flux_auto_err": {
"name": "flux_auto_err",
"dtype": "float32",
"unit": "Jy",
"default": -1.0,
"description": "Flux error from a fixed circular aperture (3.8 arcsec radius for GALEX)",
},
# %%% E_bv
"E_bv": {
"name": "E_bv",
"dtype": "float32",
"unit": "1",
"default": -1.0,
"description": "Galactic reddening expressed as E(B-V)",
},
# %%% nr_vis
"nr_vis": {
"name": "nr_vis",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Total number of visits of the field",
},
# %%% time_bin_size_sum
"time_bin_size_sum": {
"name": "time_bin_size_sum",
"dtype": "float32",
"unit": "s",
"default": -1.0,
"description": "Total exposure time",
},
# %%% time_stop
"time_stop": {
"name": "time_stop",
"dtype": "float64",
"unit": "d",
"default": -1.0,
"description": "End time of last exposure",
},
# %%% pix_id
"pix_id": {
"name": "pix_id",
"dtype": "uint32",
"unit": "1",
"default": 0,
"description": "Healpix ID",
},
# %%% exp
"exp": {
"name": "exp",
"dtype": "float32",
"unit": "1",
"default": -1,
"description": "Total exposure",
},
# %%% coadd_fdiff_s2n
"coadd_fdiff_s2n": {
"name": "coadd_fdiff_s2n",
"dtype": "float32",
"unit": "1",
"default": -10000.0,
"description": "Signal to noise of the flux difference",
},
# %%% rg_src_id
"rg_src_id": {
"name": "rg_src_id",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Region source ID number",
},
# %%% rg_fd_id
"rg_fd_id": {
"name": "rg_fd_id",
"dtype": "int64",
"unit": "1",
"default": -1,
"description": "Region field ID number",
},
# %%% nr_fds
"nr_fds": {
"name": "nr_fds",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Number of fields",
},
# %%% nr_fd_srcs
"nr_fd_srcs": {
"name": "nr_fd_srcs",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Number of field sources",
},
# %%% nr_fd_dets
"nr_fd_dets": {
"name": "nr_fd_dets",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "Number of field detections",
},
# %%% coadd_src_id
"coadd_src_id": {
"name": "coadd_src_id",
"dtype": "int64",
"unit": "1",
"default": -1,
"description": "Co-add source ID number",
},
"cat_src_id": {
"name": "cat_src_id",
"dtype": "int64",
"unit": "1",
"default": -1,
"description": "Catalog source ID number",
},
# %%% otype
"otype": {
"name": "otype",
"dtype": "S32",
"unit": "1",
"default": "none",
"description": "SIMBAD source type",
},
# %%% ogrp
"ogrp": {
"name": "ogrp",
"dtype": "S8",
"unit": "1",
"default": "none",
"description": "SIMBAD source type group in VASCA",
},
# %%% hr
"hr": {
"name": "hr",
"dtype": "float32",
"unit": "1",
"default": -1,
"description": "Flux hardness ratio, only simultaneous detections considered",
},
# %%% hr_err
"hr_err": {
"name": "hr_err",
"dtype": "float32",
"unit": "1",
"default": -1,
"description": "Flux hardness ratio error",
},
# %%% match_id
"match_id": {
"name": "match_id",
"dtype": "int32",
"unit": "1",
"default": -1,
"description": "VASCA internal source ID number for associated sources",
},
"sp_type": {
"name": "sp_type",
"dtype": "S32",
"unit": "",
"default": "none",
"description": "SIMBAD spectral type",
},
"main_id": {
"name": "main_id",
"dtype": "S32",
"unit": "",
"default": "none",
"description": "SIMBAD main ID",
},
"Source": {
"name": "Source",
"dtype": "S32",
"unit": "",
"default": "none",
"description": "GAIA DR3 source ID",
},
"gfcat_objid": {
"name": "gfcat_objid",
"dtype": "S32",
"unit": "",
"default": "none",
"description": "GFCAT object ID",
},
"WDJname": {
"name": "WDJname",
"dtype": "S32",
"unit": "",
"default": "none",
"description": "GAIA-EDR3-WD object name",
},
# %%% origin
"origin": {
"name": "origin",
"dtype": "S22",
"unit": "",
"default": "none",
"description": "Origin of the data",
},
"PQSO": {
"name": "PQSO",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Probability to be a Quasar from GAIA-DR3",
},
"PGal": {
"name": "PGal",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Probability to be a Galaxy from GAIA-DR3",
},
"PSS": {
"name": "PSS",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Probability to be a Single (non-WD) star from GAIA-DR3",
},
"RPlx": {
"name": "RPlx",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Parallax divided by its standard error from GAIA-DR3",
},
"RFRP": {
"name": "RFRP",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Red magnitude by its standard error from GAIA-DR3",
},
"RFBP": {
"name": "RFBP",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Blue magnitude by its standard error from GAIA-DR3",
},
"AG": {
"name": "AG",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "G magnitude absorption from gsp-phot for GAIA-DR3",
},
"E_BP-RP": {
"name": "E_BP-RP",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Reddening from gsp-phot for GAIA-DR3",
},
"VarFlag": {
"name": "VarFlag",
"dtype": "S32",
"unit": "1",
"default": "none",
"description": "Vizier GAIA-DR3 VarFlag",
},
"Plx": {
"name": "Plx",
"dtype": "float32",
"unit": "1e-3 arcsec",
"default": -1,
"description": "Parallax from GAIA-DR3",
},
"e_Plx": {
"name": "e_Plx",
"dtype": "float32",
"unit": "1e-3 arcsec",
"default": -1,
"description": "Parallax error from GAIA-DR3",
},
"Plx_dist": {
"name": "Plx_dist",
"dtype": "float32",
"unit": "pc",
"default": -1,
"description": "Parallax distance from GAIA-DR3",
},
"Gmag": {
"name": "Gmag",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "G-band mean magnitude from GAIA-DR3",
},
"Gmag_abs": {
"name": "Gmag_abs",
"dtype": "float32",
"unit": "",
"default": -100,
"description": "G-band mean absolute magnitude calculated from GAIA-DR3",
},
"BP-RP": {
"name": "BP-RP",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "BP-RP colour from GAIA-DR3",
},
"Pwd": {
"name": "Pwd",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "The probability of being a white dwarf in GAIA-EDR3 WD catalog",
},
"ls_peak_power": {
"name": "ls_peak_power",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "LombScargle power at peak frequency",
},
"ls_peak_freq": {
"name": "ls_peak_freq",
"dtype": "float32",
"unit": "1/d",
"default": -1,
"description": "LombScargle peak frequency",
},
"ls_peak_pval": {
"name": "ls_peak_pval",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "LombScargle power probability value",
},
"ls_pval_alt_flt": {
"name": "ls_pval_alt_flt",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "LombScargle power probability value for alternate filter",
},
"ls_model_rchiq": {
"name": "ls_model_rchiq",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Reduced chisquare of the LombScargle peak frequency sine wave",
},
"ls_model_pval": {
"name": "ls_model_pval",
"dtype": "float32",
"unit": "",
"default": -1,
"description": "Chisquare probability of the LombScargle peak frequency model ",
},
"maincat_match_id": {
"name": "maincat_match_id",
"dtype": "int32",
"unit": "",
"default": -1,
"description": "Internal source ID from associated source in the GAIA-EDR3 White Dwarf catalog",
},
"simbad_match_id": {
"name": "simbad_match_id",
"dtype": "int32",
"unit": "",
"default": -1,
"description": "Internal source ID from associated source in the SIMBAD data base",
},
"gaiadr3_match_id": {
"name": "gaiadr3_match_id",
"dtype": "int32",
"unit": "",
"default": -1,
"description": "Internal source ID from associated source in the GAIA-DR3 catalog",
},
"gfcat_src_id": {
"name": "gfcat_match_id",
"dtype": "int32",
"unit": "",
"default": -1,
"description": "Internal source ID from associated source in the GFCAT catalog",
},
}
"""
Definitions of all columns that are regisitered to be used in VASCA.
Each coulmn definition consists of five required parameters:
`name`
Name of the column
`dtype`
FITS compatible data type
`unit`
FITS compatible data unit
`default`
Default value wich will be used to populate the tabel column
`description`
Short description of the column which is shown by
:py:attr:`~astropy.table.Table.info` method of :py:class:`astropy.table.Table`.
Users may add column items here if required for instrument-specific field classes.
"""
# %% Table definitions
# %%% base_field
base_field: dict[str, dict] = {
"tt_fields": {
"names": [
"field_id",
"field_name",
"project",
"ra",
"dec",
"observatory",
"obs_filter",
"fov_diam",
"sel",
],
"meta": {"DATAPATH": "None", "INFO": "Field information table"},
},
"tt_visits": {
"names": ["vis_id", "time_bin_start", "time_bin_size", "sel", "obs_filter_id"],
"meta": {"INFO": "Visit information table"},
},
"tt_detections": {
"names": [
"vis_id",
"fd_src_id",
"ra",
"dec",
"pos_err",
"flux",
"flux_err",
"flux_app_ratio",
"s2n",
"obs_filter_id",
"sel",
"r_fov",
"artifacts",
"class_star",
"chkobj_type",
"size_world",
"ellip_world",
"flux_auto",
"flux_auto_err",
],
"meta": {"INFO": "Visit detections table"},
},
"tt_coadd_detections": {
"names": [
"det_id",
"ra",
"dec",
"pos_err",
"flux",
"flux_err",
"flux_app_ratio",
"s2n",
"obs_filter_id",
"sel",
],
"meta": {"INFO": "Reference detections table"},
},
"tt_sources": {
"names": [
"fd_src_id",
"nr_det",
"ra",
"dec",
"pos_err",
"pos_xv",
"pos_var",
"pos_cpval",
"pos_rchiq",
"coadd_src_id",
"coadd_dist",
"obs_filter_id",
"sel",
"flux",
"flux_err",
"flux_nxv",
"flux_var",
"flux_cpval",
"flux_rchiq",
"coadd_ffactor",
"coadd_fdiff_s2n",
],
"meta": {"INFO": "Source infomation table", "CLUSTALG": "None"},
},
"tt_source_lc": {
"names": [
"time",
"time_bin_size",
"flux",
"flux_err",
"ul",
"sel",
"obs_filter",
"obs_filter_id",
"r_fov",
"artifacts",
"class_star",
"chkobj_type",
"size_world",
"ellip_world",
"flux_auto",
"flux_auto_err",
"vis_id",
],
"meta": {"INFO": "Light curve flux table for one source"},
},
}
"""
Definitions of tables and columns for the :class:`~vasca.field.BaseField` class.
"""
# %%% galex_field
galex_field = {
"tt_visits": {
"names": [
*base_field["tt_visits"]["names"],
"ra",
"dec",
],
"meta": {"INFO": "Visit information table"},
},
"tt_detections": {
"names": [
*base_field["tt_detections"]["names"],
"det_id",
"E_bv",
],
"meta": {"INFO": "Visit detections table", "PRECUTS": "List of pre-cuts"},
},
"tt_coadd_detections": {
"names": [
*base_field["tt_coadd_detections"]["names"],
"r_fov",
"artifacts",
"class_star",
"chkobj_type",
"size_world",
"ellip_world",
"flux_auto",
"flux_auto_err",
"E_bv",
],
"meta": {"INFO": "Reference detections table", "PRECUTS": "List of pre-cuts"},
},
}
"""
Extension of the `base_field` definitions for the :class:`~vasca.field.GALEXField` class
"""
# %%% region
region = {
"tt_fields": {
"names": [
*base_field["tt_fields"]["names"],
"nr_vis",
"time_bin_size_sum",
"time_start",
"time_stop",
"rg_fd_id",
],
"meta": {"DATAPATH": "None", "INFO": "Field information table"},
},
"tt_visits": {
"names": [*base_field["tt_visits"]["names"]],
"meta": {"INFO": "Visit information table"},
},
"tt_coverage_hp": {
"names": ["pix_id", "nr_vis", "exp", "nr_fds"],
"meta": {
"DATAPATH": "None",
"INFO": "Region observations properties in healpix binning. RING ordering and equatorial coordinates",
"NSIDE": "None",
},
},
"tt_coadd_detections": {
"names": [
*base_field["tt_coadd_detections"]["names"],
"rg_fd_id",
"coadd_src_id",
],
"meta": {"INFO": "Reference detections table"},
},
"tt_detections": {
"names": [*base_field["tt_detections"]["names"], "rg_fd_id", "rg_src_id"],
"meta": {"INFO": "Visit detections table"},
},
"tt_sources": {
"names": [
*base_field["tt_sources"]["names"],
"rg_fd_id",
"rg_src_id",
"nr_fd_srcs",
],
"meta": {"INFO": "Source infomation table", "CLUSTALG": "None"},
},
"tt_coadd_sources": {
"names": [
*base_field["tt_sources"]["names"],
"rg_fd_id",
"nr_fd_dets",
],
"meta": {"INFO": "Source infomation table", "CLUSTALG": "None"},
},
"tt_src_id_map": {
"names": ["rg_src_id", "rg_fd_id", "fd_src_id", "sel"],
"meta": {"INFO": "Map between region and field source IDs"},
},
"tt_filters": {
"names": ["obs_filter_id", "obs_filter", "obs_filter_idx"],
"meta": {
"INFO": "Filters, their IDs and index, the last is specific for this region."
},
},
"tt_sed": {
"names": [
"flux",
"flux_err",
"observatory",
"obs_filter",
"origin",
"wavelength",
],
"meta": {"INFO": "Spectral Energy Distribution from VizieR database"},
},
"tt_gphoton_lc": {
"names": [
"time",
"time_bin_size",
"flux",
"flux_err",
"sel",
"obs_filter",
"obs_filter_id",
"flags",
"s2n",
],
"meta": {"INFO": "Light curve from gPhoton.gAperture"},
},
"tt_spectrum": {
"names": ["flux", "wavelength", "s2n", "flux_model", "sel"],
"meta": {"INFO": "Spectrum"},
},
"tt_lombscargle": {
"names": [
"rg_src_id",
"ls_peak_power",
"ls_peak_freq",
"ls_peak_pval",
"ls_pval_alt_flt",
"ls_model_rchiq",
"ls_model_pval",
],
"meta": {"INFO": "LombScargle results information"},
},
}
"""
Definitions of tables and columns for the :class:`~vasca.region.Region` class.
"""
# global, combined dictionary
class_keys = ["base_field", "galex_field", "region"]
class_dicts = [base_field, galex_field, region]
dd_vasca_tables = {c_key: c_dict for c_key, c_dict in zip(class_keys, class_dicts)}
# Add columns to tables dictionary
for tab_type, table_group in dd_vasca_tables.items():
for tab_name, tab in table_group.items():
tab["dtype"] = []
tab["units"] = []
tab["defaults"] = []
tab["descriptions"] = []
for col_name in tab["names"]:
col = dd_vasca_columns[col_name]
tab["dtype"].append(col["dtype"])
tab["units"].append(col["unit"])
tab["defaults"].append(col["default"])
tab["descriptions"].append(col["description"])
|
rbuehlerREPO_NAMEvascaPATH_START.@vasca_extracted@vasca-main@vasca@tables_dict.py@.PATH_END.py
|
{
"filename": "setup_package.py",
"repo_name": "StingraySoftware/stingray",
"repo_path": "stingray_extracted/stingray-main/stingray/tests/setup_package.py",
"type": "Python"
}
|
StingraySoftwareREPO_NAMEstingrayPATH_START.@stingray_extracted@stingray-main@stingray@tests@setup_package.py@.PATH_END.py
|
|
{
"filename": "2. Plot Spectral Index Error.ipynb",
"repo_name": "mlarichardson/CosmosCanvas",
"repo_path": "CosmosCanvas_extracted/CosmosCanvas-main/2. Plot Spectral Index Error.ipynb",
"type": "Jupyter Notebook"
}
|
# Making an Spectral Index Error Plot with Increasing Chroma.
This notebook is Tutorial 2 of the [```CosmosCanvas```](https://github.com/mlarichardson/CosmosCanvas) package. This Python 3 tutorial highlights the creation of a perception-based colour map designed for plotting spectral index error data. See Tutorial 1 for more discussion.
The galaxy from Tutorial 1 has uncertainties for the spectral index. We have created a default colourmap approach for error maps, but it has more flexibility for the user. The default approach provides a constant colour that transitions from gray (0 chroma) at low error, to orange (high chroma) at high error. The user can choose what fraction of the range of values should have low chroma by choosing the position in the colour map that corresponds to the half-chroma value. This half-chroma point by default has low luminosity, so you can see transitions both in low-error regions, and high-error regions. The example below uses a range of [0:1] and a default of 50% for the half-chroma point.
The user can adjust all of these choices, including the maximum chroma value, the luminosity values at the top and bottom of the colourbar as well as at the half-chroma point, and finally the hue value(s) for the colour map (more on this below).
*Tutorial Aims*: This tutorial begins by outlining the creation of the spectral index error colour map using default and arbitrary settings. We then produce an error map for data measuring the uncertainties in spectral index. This uses cmap = specindex_error in `specindex.py` and demonstrates different parameter settings.
*Package*
This package includes `specindex.py`, `velmap.py` and `galfits.py` for plotting; the latter requires the installation of `Astropy`.
Additionally it uses the [```colourspace```](https://github.com/gillesferrand/colourspace) package by Gilles Ferrand for making custom colour maps in LCH colour space.
Authors: Mark L. A. Richardson, Gilles Ferrand, and Jayanne English, 7 Jan 2021. Updated JE and GF 8 Feb 2023
```python
# Import
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
```
```python
# Import our package and the colourspace package
import specindex as spx
import galfits as gal
from colourspace import maps
```
convertor = 'custom' (illuminant = 'D65')
```python
# Make a folder for saving figures.
import os
plt_dir = 'plots'
if not os.path.exists(plt_dir): os.makedirs(plt_dir)
```
```python
cmap_error_default = 'CC-specindex-error-default'
spx.create_cmap_specindex_error(name=cmap_error_default)
```
loading gamut from /Users/english/pythonPackages/colourspace/gamut/Cmax_res10_full.npy
creating cmap 'CC-specindex-error-default' for Matplotlib (1024 steps)
registering cmap 'CC-specindex-error-default' to Matplotlib
Similar to how we compared two colour maps in workbook 1, we can use `colourspace`'s `maps.test_cmaps` routine to showcase a single colour map. The default title is the colourmap name, but you can pass in a list of titles in the same order as `names`.
```python
maps.test_cmaps(names=[cmap_error_default],nsteps=[17],figsize=(12,7),fname=plt_dir+'/testcmap',titles=["Demo Title"])
```
writing ./plots/testcmap_CC-specindex-error-default.png

```python
# Let's show the default colour map in LCH space, using the plot_path function.
axes = maps.plot_path(cmap_error_default, space='LCH', stack='H', axes=[] , styles=['-' ], legend_label=cmap_error_default)
```
loading gamut from /Users/english/pythonPackages/colourspace/gamut/Cmax_res10_sRGB.npy

Luminosity L stays high with a dip in the middle. Chroma C rises linearly (as much as gamut allows) from zero to the max; the dotted line shows the limits for chroma in the gamut of the sRGB colour space. Hue H stays constant.
Let's look at the galaxy's uncertainty in spectral index data using the default colour map. Here the error/uncertainty data files are also provided in the example_data folder of `CosmosCanvas`.
```python
# Set galaxy information
title='NGC 3079 error'
errfits_file="example_data/SpecIndexError_N3079.FITS"
RA = [10., 1., 57.8] # hh.mm.ss
DEC = [55., 40., 47.0] # deg.mm.ss
#For Rectangle images set
TrimSwitch='rectangle'
ImgWidth=0.08 #degrees
ImgHeight=0.09 #degrees
ImgSize = [ImgWidth, ImgHeight]# degrees
# For square images simply set ImgWidth=ImgHeight
shift = [0.0, 0.2/60.] # degrees
```
```python
nsteps=18
cbar_name='spectral index error'
fig,ax = gal.plot_galaxy(errfits_file,RA,DEC,ImgSize,shift,cmap_error_default,nsteps=nsteps,cb_name=cbar_name,TrimSwitch=TrimSwitch,figsize=(8,9))
fig.savefig(plt_dir+'/plot_galerr_default_Jan2023.png', bbox_inches = "tight", dpi=300)
```
WARNING: FITSFixedWarning: 'obsfix' made the change 'Set OBSGEO-L to -107.618000 from OBSGEO-[XYZ].
Set OBSGEO-B to 34.078827 from OBSGEO-[XYZ].
Set OBSGEO-H to 2115.607 from OBSGEO-[XYZ]'. [astropy.wcs.wcs]

For this galaxy, we see that the vast majority of data values have very low associated noise. We choose to shift the mid-chroma point to 25% of the colourmap. We do this using the c_mid parameter.
```python
cmap_error_A = 'CC-specindex-error-25'
spx.create_cmap_specindex_error(c_mid=0.25,name=cmap_error_A)
```
creating cmap 'CC-specindex-error-25' for Matplotlib (1024 steps)
registering cmap 'CC-specindex-error-25' to Matplotlib
```python
fig,ax = gal.plot_galaxy(errfits_file,RA,DEC,ImgSize,shift,cmap_error_A,nsteps=nsteps,cb_name=cbar_name,TrimSwitch=TrimSwitch,figsize=(8,9))
fig.savefig(plt_dir+'/plot_galerr_default.png', bbox_inches = "tight", dpi=300)
```
WARNING: FITSFixedWarning: 'obsfix' made the change 'Set OBSGEO-L to -107.618000 from OBSGEO-[XYZ].
Set OBSGEO-B to 34.078827 from OBSGEO-[XYZ].
Set OBSGEO-H to 2115.607 from OBSGEO-[XYZ]'. [astropy.wcs.wcs]

To produce a plot that appears continuous, you can again increase nsteps.
There are more optional arguements in *create_cmap_specindex_error* in `specindex.py`. For example one could change the constant colour, create a range of colours, and, in analogy with chroma, shift the fraction of the range that has low luminosity.
```python
# Change the fraction that is luminous by changing L_mid (default = 50) to L_mid=80.
# Note the default L at the top and bottom of the colour map is L_ends=72.
cmap_error_B = 'CC-specindex-error-25-L80'
spx.create_cmap_specindex_error(c_mid=0.25,L_mid=80,name=cmap_error_B)
```
creating cmap 'CC-specindex-error-25-L80' for Matplotlib (1024 steps)
registering cmap 'CC-specindex-error-25-L80' to Matplotlib
```python
fig,ax = gal.plot_galaxy(errfits_file,RA,DEC,ImgSize,shift,cmap_error_B,nsteps=nsteps,cb_name=cbar_name,TrimSwitch=TrimSwitch,figsize=(8,9))
fig.savefig(plt_dir+'/plot_galerr_L80_Jan2023.png', bbox_inches = "tight", dpi=300)
```
WARNING: FITSFixedWarning: 'obsfix' made the change 'Set OBSGEO-L to -107.618000 from OBSGEO-[XYZ].
Set OBSGEO-B to 34.078827 from OBSGEO-[XYZ].
Set OBSGEO-H to 2115.607 from OBSGEO-[XYZ]'. [astropy.wcs.wcs]

```python
# Let's show the two new colour maps in LCH space, using the plot_path function.
axes = maps.plot_path(cmap_error_A, space='LCH', stack='H', axes=[] , styles=['-' ], legend_label=cmap_error_A)
axes = maps.plot_path(cmap_error_B, space='LCH', stack='H', axes=axes, styles=['--'], legend_label=cmap_error_B)
```

```python
# Create a number of colours within the high error range.
# The default for the constant orange is H_0=70. and H_min = H_max = none.
# For a range of colours, H_0 is not used. Instead we set H_max = 70 and H_min = 250 to cover
# 180 degrees on the colour wheel. This creates numerous colours and includes the orange's complementary colour.
cmap_error_C = 'CC-specindex-error-hueV1'
spx.create_cmap_specindex_error(c_mid=0.25,H_min=250.,H_max=70.,name=cmap_error_C)
```
creating cmap 'CC-specindex-error-hueV1' for Matplotlib (1024 steps)
registering cmap 'CC-specindex-error-hueV1' to Matplotlib
```python
fig,ax = gal.plot_galaxy(errfits_file,RA,DEC,ImgSize,shift,cmap_error_C,nsteps=nsteps,cb_name=cbar_name,TrimSwitch=TrimSwitch,figsize=(8,9))
fig.savefig(plt_dir+'/plot_galerr_hueV1_Jan2023.png', bbox_inches = "tight", dpi=300)
```
WARNING: FITSFixedWarning: 'obsfix' made the change 'Set OBSGEO-L to -107.618000 from OBSGEO-[XYZ].
Set OBSGEO-B to 34.078827 from OBSGEO-[XYZ].
Set OBSGEO-H to 2115.607 from OBSGEO-[XYZ]'. [astropy.wcs.wcs]

Similarly you can set `H_mid` if you don't want the hue to change in one end or the other. Where we see this being of most use is for the hue to remain constant in the low-uncertainty regime where chroma is low.
```python
# Colour in high error range only: set H_max and H_mid
# The default for the constant orange is H_0=70. and H_min = H_max = none.
# For a range of colours, H_0 is not used. Instead here we set H_max = 70 and H_mid = 250 to cover
# 180 degrees on the colour wheel. This creates numerous colours and includes the orange's complementary colour.
cmap_error_D = 'CC-specindex-error-hueV2'
spx.create_cmap_specindex_error(c_mid=0.25,H_mid=250.,H_max=70.,name=cmap_error_D)
```
creating cmap 'CC-specindex-error-hueV2' for Matplotlib (1024 steps)
registering cmap 'CC-specindex-error-hueV2' to Matplotlib
```python
fig,ax = gal.plot_galaxy(errfits_file,RA,DEC,ImgSize,shift,cmap_error_D,nsteps=nsteps,cb_name=cbar_name,TrimSwitch=TrimSwitch,figsize=(8,9))
fig.savefig(plt_dir+'/plot_galerr_hueV2_Jan2023.png', bbox_inches = "tight", dpi=300)
```
WARNING: FITSFixedWarning: 'obsfix' made the change 'Set OBSGEO-L to -107.618000 from OBSGEO-[XYZ].
Set OBSGEO-B to 34.078827 from OBSGEO-[XYZ].
Set OBSGEO-H to 2115.607 from OBSGEO-[XYZ]'. [astropy.wcs.wcs]

```python
# Let's show the two new colour maps in LCH space, using the plot_path function.
axes = maps.plot_path(cmap_error_C, space='LCH', stack='H', axes=[] , styles=['-' ], legend_label=cmap_error_C)
axes = maps.plot_path(cmap_error_D, space='LCH', stack='H', axes=axes, styles=['--'], legend_label=cmap_error_D)
```

|
mlarichardsonREPO_NAMECosmosCanvasPATH_START.@CosmosCanvas_extracted@CosmosCanvas-main@2. Plot Spectral Index Error.ipynb@.PATH_END.py
|
{
"filename": "_hovertextsrc.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scattermap/_hovertextsrc.py",
"type": "Python"
}
|
import _plotly_utils.basevalidators
class HovertextsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="hovertextsrc", parent_name="scattermap", **kwargs):
super(HovertextsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs,
)
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scattermap@_hovertextsrc.py@.PATH_END.py
|
{
"filename": "bdist_rpm.py",
"repo_name": "catboost/catboost",
"repo_path": "catboost_extracted/catboost-master/contrib/python/setuptools/py2/setuptools/command/bdist_rpm.py",
"type": "Python"
}
|
import distutils.command.bdist_rpm as orig
class bdist_rpm(orig.bdist_rpm):
"""
Override the default bdist_rpm behavior to do the following:
1. Run egg_info to ensure the name and version are properly calculated.
2. Always run 'install' using --single-version-externally-managed to
disable eggs in RPM distributions.
3. Replace dash with underscore in the version numbers for better RPM
compatibility.
"""
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
orig.bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-', '_')
spec = orig.bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
|
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@setuptools@py2@setuptools@command@bdist_rpm.py@.PATH_END.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.