Create a spectral function instance given its flux.
554021
def create_from_flux(cls, params, emin, emax, flux, scale=1.0):
        """"""
        params = params.copy()
        params[0] = 1.0
        params[0] = flux / cls.eval_flux(emin, emax, params, scale=scale)
        return cls(params, scale)
1037189
def flux_r2(q_vars: List[fl.Var], i: int, j: int):
    """"""
    # Indices with the base of (x, y, z) for each body
    k0 = 3*i
    k1 = 3*j
    # The squared distance bewteen body i and j as a Fluxion instance
    return fl.square(q_vars[k1+0] - q_vars[k0+0]) + \
           fl.square(q_vars[k1+1] - q_vars[k0+1]) + \
           fl.square(q_vars[k1+2] - q_vars[k0+2])
609197
def create_spectrum(spectrum_name):
        
        try:
            spectrum_description = nmrstarlib.SPECTRUM_DESCRIPTIONS[spectrum_name]
        except KeyError:
            raise NotImplementedError("Experiment type is not defined.")

        spectrum = plsimulator.Spectrum(spectrum_name, spectrum_description["Labels"],
                                        spectrum_description["MinNumberPeaksPerSpinSystem"],
                                        spectrum_description.get("ResonanceLimit", None))

        for peak_descr in spectrum_description["PeakDescriptions"]:
            spectrum.append(plsimulator.PeakDescription(peak_descr["fraction"], peak_descr["dimensions"]))

        return spectrum
1036567
def gradient(self):
        """"""
        gradients = [func.gradient for func in self.functionals]
        return DiagonalOperator(*gradients)
99721
def _createFuture(func, *args, **kwargs):
    """"""
    assert callable(func), (
        "The provided func parameter is not a callable."
    )

    if scoop.IS_ORIGIN and "SCOOP_WORKER" not in sys.modules:
        sys.modules["SCOOP_WORKER"] = sys.modules["__main__"]

    # If function is a lambda or class method, share it (or its parent object)
    # beforehand
    lambdaType = type(lambda: None)
    funcIsLambda = isinstance(func, lambdaType) and func.__name__ == '<lambda>'
    # Determine if function is a method. Methods derived from external
    # languages such as C++ aren't detected by ismethod.
    funcIsMethod = ismethod(func)
    if funcIsLambda or funcIsMethod:
        from .shared import SharedElementEncapsulation
        func = SharedElementEncapsulation(func)

    return Future(control.current.id, func, *args, **kwargs)
973910
def make_force_ES(q_vars, mass):
    """"""
    # Build the potential energy fluxion; just one pair of bodies
    U =  U_ij(q_vars, mass, 0, 1)
    # Varname arrays for both the coordinate system and U
    vn_q = np.array([q.var_name for q in q_vars])
    vn_fl = np.array(sorted(U.var_names))
    # Permutation array for putting variables in q in the order expected by U (alphabetical)
    q2fl = np.array([np.argmax((vn_q == v)) for v in vn_fl])
    # Permutation array for putting results of U.diff() in order of q_vars
    fl2q = np.array([np.argmax((vn_fl == v)) for v in vn_q])
    # Return a force function from this potential
    force_func = lambda q: -U.diff(q[q2fl]).squeeze()[fl2q]
    return force_func
993614
def create(fs, channels, application):
    """"""

    result_code = ctypes.c_int()

    result = _create(fs, channels, application, ctypes.byref(result_code))
    if result_code.value is not constants.OK:
        raise OpusError(result_code.value)

    return result
730470
def _create(self):
        """"""
        from samplerate.lowlevel import ffi, src_callback_new, src_delete
        from samplerate.exceptions import ResamplingError

        state, handle, error = src_callback_new(
            self._callback, self._converter_type.value, self._channels)
        if error != 0:
            raise ResamplingError(error)
        self._state = ffi.gc(state, src_delete)
        self._handle = handle
593955
def create_apply_graph(self, signature, input_tensors, name):
    """"""
    signature_def = self._meta_graph.signature_def.get(signature)
    meta_graph = meta_graph_pb2.MetaGraphDef()
    meta_graph.CopyFrom(self._meta_graph)
    apply_graph = tf_v1.get_default_graph()
    infeed_map = tensor_info.build_input_map(signature_def.inputs,
                                             input_tensors)

    # Build a input map to feed when importing the apply-graph by augmenting the
    # state_map with the input args. This allows an input to override a tensor
    # from the state-graph.
    feed_map = dict(self._state_map)
    # If we are applying the module in a function with a TPUReplicateContext, we
    # must capture the state tensors in generating our feedmap and prune out
    # assign ops. Function graph semantics are different in that all ops are
    # executed regardless of dependency.
    # TODO(b/112575006): The following adds functionality of function call
    # within a TPU context. Work to generalize this for all function calls is
    # ongoing.
    if self._is_tpu_graph_function():
      for k, v in self._state_map.items():
        feed_map[k] = apply_graph.capture(v)
      meta_graph_lib.prune_unused_nodes(meta_graph, signature_def)
      # After we prune the metagraph def, we might need to prune away
      # infeeds which no longer exist.
      meta_graph_lib.prune_feed_map(meta_graph, infeed_map)
    elif apply_graph.building_function:
      raise NotImplementedError(
          "Using TF-Hub module within a TensorFlow defined function "
          "is currently not supported.")

    # As state ops in the apply graph are unused, replace them with Placeholders
    # so that in a heirarchical instantiation, apply_graph state ops are
    # ignored.
    replace_apply_state(meta_graph,
                        list_registered_stateful_ops_without_inputs(), feed_map)
    feed_map.update(infeed_map)

    # Make state tensors enter the current context. This way the Module can be
    # applied inside a control flow structure such as a while_loop.
    control_flow = apply_graph._get_control_flow_context()  # pylint: disable=protected-access
    if control_flow:
      for key, value in sorted(feed_map.items()):
        feed_map[key] = control_flow.AddValue(value)

    # Don't mark the name as used at this point - import_scoped_meta_graph will
    # start using it.
    absolute_scope_name = apply_graph.unique_name(name, mark_as_used=False)
    relative_scope_name = absolute_scope_name.split("/")[-1]

    import_collections = [
        # In most cases ASSET_FILEPATHS are only used for the TABLE_INITIALIZERS
        # ops, however one could create a graph that uses an asset at any other
        # time. As so everytime we bring the tensor with that has the asset
        # filename we must annotate it as so, so later re-exports have that
        # semantic information and can handle it.
        tf_v1.GraphKeys.ASSET_FILEPATHS,
        tf_v1.GraphKeys.COND_CONTEXT,
        tf_v1.GraphKeys.WHILE_CONTEXT,
    ]
    if self._trainable:
      import_collections.extend([tf_v1.GraphKeys.UPDATE_OPS])

    meta_graph_lib.filter_collections(meta_graph, import_collections)
    meta_graph_lib.prefix_shared_name_attributes(meta_graph,
                                                 absolute_scope_name)
    if len(meta_graph.collection_def) and self._is_tpu_graph_function():
      raise NotImplementedError(
          "Applying modules with collections inside TPU functions is not "
          "supported.")

    tf_v1.train.import_meta_graph(
        meta_graph,
        input_map=feed_map,
        import_scope=relative_scope_name)
    fix_colocation_after_import(input_map=feed_map,
                                absolute_import_scope=absolute_scope_name)

    def get_tensor(name):
      # When trying to output an input tensor there are no nodes created within
      # the apply scope. So one must look into the input map.
      try:
        return feed_map[name]
      except KeyError:
        return apply_graph.get_tensor_by_name(
            meta_graph_lib.prepend_name_scope(
                name, import_scope=absolute_scope_name))

    return tensor_info.build_output_map(signature_def.outputs, get_tensor)
255315
def _get_binned_arrays(self, wavelengths, flux_unit, area=None,
                           vegaspec=None):
        """"""
        x = self._validate_binned_wavelengths(wavelengths)
        y = self.sample_binned(wavelengths=x, flux_unit=flux_unit, area=area,
                               vegaspec=vegaspec)

        if isinstance(wavelengths, u.Quantity):
            w = x.to(wavelengths.unit, u.spectral())
        else:
            w = x

        return w, y
984459
def create(self, graph):
        
        scoped_config = self.get_scoped_config(graph)
        scoped_graph = ScopedGraph(graph, scoped_config)
        return self.func(scoped_graph)
609462
def _compute_fluxes(self):
        ''' '''
        self.emission = self._compute_emission()
        self.emission_sfc = self._compute_emission_sfc()
        fromspace = self._from_space()
        self.flux_down = self.trans.flux_down(fromspace, self.emission)
        self.flux_reflected_up = self.trans.flux_reflected_up(self.flux_down, self.albedo_sfc)
        # this ensure same dimensions as other fields
        self.flux_to_sfc = self.flux_down[..., -1, np.newaxis]
        self.flux_from_sfc = (self.emission_sfc +
                              self.flux_reflected_up[..., -1, np.newaxis])
        self.flux_up = self.trans.flux_up(self.flux_from_sfc,
                            self.emission + self.flux_reflected_up[...,0:-1])
        self.flux_net = self.flux_up - self.flux_down
        # absorbed radiation (flux convergence) in W / m**2 (per band)
        self.absorbed = np.diff(self.flux_net, axis=-1)
        self.absorbed_total = np.sum(self.absorbed, axis=-1)
        self.flux_to_space = self._compute_flux_top()
897066
def from_main(cls, signature=''):
        
        instance = cls()

        def decorate(function):
            instance.main(signature)(function)
            return instance
        return decorate
109600
def functions_factory(cls, coef, domain, kind, **kwargs):
        
        basis_polynomial = cls._basis_polynomial_factory(kind)
        return basis_polynomial(coef, domain)
979076
def init_kernel(self):
        '''
        

        '''

        if self.kernel_params is None:
            X = self.apply_mask(self.fpix / self.flux.reshape(-1, 1))
            y = self.apply_mask(self.flux) - np.dot(X, np.linalg.solve(
                np.dot(X.T, X), np.dot(X.T, self.apply_mask(self.flux))))
            white = np.nanmedian([np.nanstd(c) for c in Chunks(y, 13)])
            amp = self.gp_factor * np.nanstd(y)
            tau = 30.0
            if self.kernel == 'Basic':
                self.kernel_params = [white, amp, tau]
            elif self.kernel == 'QuasiPeriodic':
                self.kernel_params = [white, amp, 1., 20.]
307399
def run(self, fct, input_):
    """"""
    # TF 2.0
    if tf.executing_eagerly():
      return fct(input_).numpy()
    # TF 1.0
    else:
      # Should compile the function if this is the first time encountered
      if not isinstance(input_, np.ndarray):
        input_ = np.array(input_)
      run_args = RunArgs(fct=fct, input=input_)
      signature = self._build_signature(run_args)
      if signature not in self._graph_run_cache:
        graph_run = self._build_graph_run(run_args)
        self._graph_run_cache[signature] = graph_run
      else:
        graph_run = self._graph_run_cache[signature]

      # Then execute the cached graph
      return graph_run.session.run(
          graph_run.output,
          feed_dict={graph_run.placeholder: input_},
      )
1343961
def spectral_flux(d0, d1):
    
    # compute the spectral flux as the sum of square distances:
    d0 = np.mean(d0, axis=1)
    d1 = np.mean(d1, axis=1)
    nFFT = min(len(d0) // 2, len(d1) // 2)
    X = FFT(d0, nFFT)
    Xprev = FFT(d1, nFFT)

    # L = min(len(X), len(Xprev))

    sumX = np.sum(X + EPSILON)
    sumPrevX = np.sum(Xprev + EPSILON)
    return np.sum((X / sumX - Xprev / sumPrevX) ** 2)